code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
return {
name = "Dynamo",
inputs = {
{ name = "Rotation", type = "rotation" }
},
outputs = {
{ name = "Electricity", type = "electricity" }
}
}
|
Reisz/OuterRim
|
res/nodes/dynamo.lua
|
Lua
|
gpl-2.0
| 162
|
#!/usr/bin/python
# Ubuntu Tweak - PyGTK based desktop configure tool
#
# Copyright (C) 2007-2008 TualatriX <tualatrix@gmail.com>
#
# Ubuntu Tweak 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.
#
# Ubuntu Tweak 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 Ubuntu Tweak; if not, write to the Free Software Foundation, Inc.,
import os
import gtk
import gconf
from common.settings import *
from common.factory import GconfKeys
class Config:
#FIXME The class should be generic config getter and setter
__client = gconf.Client()
def set_value(self, key, value):
if not key.startswith("/"):
key = GconfKeys.keys[key]
if type(value) == int:
self.__client.set_int(key, value)
elif type(value) == float:
self.__client.set_float(key, value)
elif type(value) == str:
self.__client.set_string(key, value)
elif type(value) == bool:
self.__client.set_bool(key, value)
def get_value(self, key, default = None):
if not key.startswith("/"):
key = GconfKeys.keys[key]
try:
value = self.__client.get_value(key)
except:
if default is not None:
self.set_value(key, default)
return default
else:
return None
else:
return value
def set_pair(self, key, type1, type2, value1, value2):
if not key.startswith("/"):
key = GconfKeys.keys[key]
self.__client.set_pair(key, type1, type2, value1, value2)
def get_pair(self, key):
if not key.startswith("/"):
key = GconfKeys.keys[key]
value = self.__client.get(key)
if value:
return value.to_string().strip('()').split(',')
else:
return (0, 0)
def get_string(self, key):
if not key.startswith("/"):
key = GconfKeys.keys[key]
string = self.get_value(key)
if string:
return string
else:
return '0'
def get_client(self):
return self.__client
class TweakSettings:
'''Manage the settings of ubuntu tweak'''
config = Config()
url = 'tweak_url'
version = 'tweak_version'
toolbar_size = 'toolbar_size'
toolbar_color = 'toolbar_color'
toolbar_font_color = 'toolbar_font_color'
window_size= 'window_size'
window_height = 'window_height'
window_width = 'window_width'
show_donate_notify = 'show_donate_notify'
default_launch = 'default_launch'
check_update = 'check_update'
power_user = 'power_user'
need_save = True
@classmethod
def get_power_user(cls):
return cls.config.get_value(cls.power_user, default=False)
@classmethod
def set_power_user(cls, bool):
cls.config.set_value(cls.power_user, bool)
@classmethod
def get_check_update(cls):
return cls.config.get_value(cls.check_update, default = True)
@classmethod
def set_check_update(cls, bool):
cls.config.set_value(cls.check_update, bool)
@classmethod
def get_toolbar_color(cls, instance = False):
color = cls.config.get_value(cls.toolbar_color)
if color == None:
if instance:
return gtk.gdk.Color(32767, 32767, 32767)
return (0.5, 0.5, 0.5)
else:
try:
color = gtk.gdk.color_parse(color)
if instance:
return color
red, green, blue = color.red/65535.0, color.green/65535.0, color.blue/65535.0
return (red, green, blue)
except:
return (0.5, 0.5, 0.5)
@classmethod
def set_toolbar_color(cls, color):
cls.config.set_value(cls.toolbar_color, color)
@classmethod
def get_toolbar_font_color(cls, instance = False):
color = cls.config.get_value(cls.toolbar_font_color)
if color == None:
if instance:
return gtk.gdk.Color(65535, 65535, 65535)
return (1, 1, 1)
else:
try:
color = gtk.gdk.color_parse(color)
if instance:
return color
red, green, blue = color.red/65535.0, color.green/65535.0, color.blue/65535.0
return (red, green, blue)
except:
return (1, 1, 1)
@classmethod
def set_toolbar_font_color(cls, color):
cls.config.set_value(cls.toolbar_font_color, color)
@classmethod
def set_default_launch(cls, id):
cls.config.set_value(cls.default_launch, id)
@classmethod
def get_default_launch(cls):
return cls.config.get_value(cls.default_launch)
@classmethod
def set_show_donate_notify(cls, bool):
return cls.config.set_value(cls.show_donate_notify, bool)
@classmethod
def get_show_donate_notify(cls):
value = cls.config.get_value(cls.show_donate_notify, default = True)
return value
@classmethod
def set_url(cls, url):
return cls.config.set_value(cls.url, url)
@classmethod
def get_url(cls):
return cls.config.get_string(cls.url)
@classmethod
def set_version(cls, version):
return cls.config.set_value(cls.version, version)
@classmethod
def get_version(cls):
return cls.config.get_string(cls.version)
@classmethod
def set_paned_size(cls, size):
cls.config.set_value(cls.toolbar_size, size)
@classmethod
def get_paned_size(cls):
position = cls.config.get_value(cls.toolbar_size)
if position:
return position
else:
return 150
@classmethod
def set_window_size(cls, width, height):
cls.config.set_value(cls.window_width, width)
cls.config.set_value(cls.window_height, height)
@classmethod
def get_window_size(cls):
width = cls.config.get_value(cls.window_width)
height = cls.config.get_value(cls.window_height)
if width and height:
height, width = int(height), int(width)
return (width, height)
else:
return (740, 480)
@classmethod
def get_icon_theme(cls):
return cls.config.get_value('/desktop/gnome/interface/icon_theme')
if __name__ == '__main__':
print Config().get_value('show_donate_notify')
|
tualatrix/ubuntu-tweak-old
|
src/common/config.py
|
Python
|
gpl-2.0
| 6,864
|
<?php
/** Literary Chinese (文言)
*
* See MessagesQqq.php for message documentation incl. usage of parameters
* To improve a translation please visit http://translatewiki.net
*
* @ingroup Language
* @file
*
* @author Itsmine
* @author Omnipaedista
*/
/**
* A list of date format preference keys which can be selected in user
* preferences. New preference keys can be added, provided they are supported
* by the language class's timeanddate(). Only the 5 keys listed below are
* supported by the wikitext converter (DateFormatter.php).
*
* The special key "default" is an alias for either dmy or mdy depending on
* $wgAmericanDates
*/
$datePreferences = array(
'default',
'ISO 8601',
);
$defaultDateFormat = 'zh';
/**
* These are formats for dates generated by MediaWiki (as opposed to the wikitext
* DateFormatter). Documentation for the format string can be found in
* Language.php, search for sprintfDate.
*
* This array is automatically inherited by all subclasses. Individual keys can be
* overridden.
*/
$dateFormats = array(
'zh time' => 'H時i分',
'zh date' => 'Y年n月j日 (l)',
'zh both' => 'Y年n月j日 (D) H時i分',
);
$linkTrail = '/^([a-z]+)(.*)$/sD';
$digitTransformTable = array(
'0' => '〇',
'1' => '一',
'2' => '二',
'3' => '三',
'4' => '四',
'5' => '五',
'6' => '六',
'7' => '七',
'8' => '八',
'9' => '九',
'.' => '點',
',' => '',
);
#-------------------------------------------------------------------
# Default messages
#-------------------------------------------------------------------
# Allowed characters in keys are: A-Z, a-z, 0-9, underscore (_) and
# hyphen (-). If you need more characters, you may be able to change
# the regex in MagicWord::initRegex
$messages = array(
# User preference toggles
'tog-underline' => '鏈墊線:',
'tog-highlightbroken' => '<a href="" class="new">斷鏈</a>,以<a href="" class="internal">?</a>替',
'tog-justify' => '齊段落',
'tog-hideminor' => '隱近校',
'tog-hidepatrolled' => '隱近巡',
'tog-newpageshidepatrolled' => '隱新巡',
'tog-extendwatchlist' => '展列見變',
'tog-usenewrc' => '青出近易(JavaScript)',
'tog-numberheadings' => '生章數',
'tog-showtoolbar' => '多寶列見(JavaScript)',
'tog-editondblclick' => '纂頁雙擊(JavaScript)',
'tog-editsection' => '纂段擊鏈',
'tog-editsectiononrightclick' => '纂段右擊標(JavaScript)',
'tog-showtoc' => '四章見目',
'tog-rememberpassword' => '符節通越',
'tog-editwidth' => '纂幅全',
'tog-watchcreations' => '哨己撰',
'tog-watchdefault' => '哨己纂',
'tog-minordefault' => '慣為校',
'tog-previewontop' => '頂草覽',
'tog-previewonfirst' => '覽首修',
'tog-nocache' => '莫謄文',
'tog-enotifwatchlistpages' => '哨新,遣函',
'tog-enotifusertalkpages' => '議新,遣函',
'tog-enotifminoredits' => '校新,遣函',
'tog-enotifrevealaddr' => '列余址於書內',
'tog-shownumberswatching' => '放哨有',
'tog-fancysig' => '署以本碼待之(免自連)',
'tog-externaleditor' => '它器修文(高人用,需設之)',
'tog-externaldiff' => '它器修異(高人用,需設之)',
'tog-showjumplinks' => '鏈往字',
'tog-uselivepreview' => '即覽嚐鮮(JavaScript)',
'tog-forceeditsummary' => '漏概醒之',
'tog-watchlisthideown' => '不哨己文',
'tog-watchlisthidebots' => '不哨僕文',
'tog-watchlisthideminor' => '不哨小纂',
'tog-watchlisthideliu' => '不哨有簿',
'tog-watchlisthideanons' => '不哨無簿',
'tog-watchlisthidepatrolled' => '不哨已巡',
'tog-nolangconversion' => '非轉',
'tog-ccmeonemails' => '凡所遺書,請存副本。',
'tog-diffonly' => '異下無示頁',
'tog-showhiddencats' => '示隱類',
'tog-noconvertlink' => '非轉鍵題',
'tog-norollbackdiff' => '轉後略異',
'underline-always' => '恆',
'underline-never' => '絕',
'underline-default' => '慣',
# Dates
'sunday' => '週日',
'monday' => '週一',
'tuesday' => '週二',
'wednesday' => '週三',
'thursday' => '週四',
'friday' => '週五',
'saturday' => '週六',
'sun' => '週日',
'mon' => '周一',
'tue' => '周二',
'wed' => '周三',
'thu' => '周四',
'fri' => '周五',
'sat' => '周六',
'january' => '一月',
'february' => '二月',
'march' => '三月',
'april' => '四月',
'may_long' => '五月',
'june' => '六月',
'july' => '七月',
'august' => '八月',
'september' => '九月',
'october' => '十月',
'november' => '十一月',
'december' => '十二月',
'january-gen' => '一月',
'february-gen' => '二月',
'march-gen' => '三月',
'april-gen' => '四月',
'may-gen' => '五月',
'june-gen' => '六月',
'july-gen' => '七月',
'august-gen' => '八月',
'september-gen' => '九月',
'october-gen' => '十月',
'november-gen' => '十一月',
'december-gen' => '十二月',
'jan' => '一月',
'feb' => '二月',
'mar' => '三月',
'apr' => '四月',
'may' => '五月',
'jun' => '六月',
'jul' => '七月',
'aug' => '八月',
'sep' => '九月',
'oct' => '十月',
'nov' => '十一月',
'dec' => '十二月',
# Categories related messages
'pagecategories' => '$1類',
'category_header' => '「$1」中之頁',
'subcategories' => '次類',
'category-media-header' => '「$1」中之媒',
'category-empty' => "''無頁或媒也。''",
'hidden-categories' => '$1隱類',
'hidden-category-category' => '隱類', # Name of the category where hidden categories will be listed
'category-subcat-count' => '{{PLURAL:$2|門有戶壹。|門有戶$1,有$2戶也。}}',
'category-subcat-count-limited' => '門有戶$1。',
'category-article-count' => '{{PLURAL:$2|門有頁壹。|門有頁$1,有$2頁也。}}',
'category-article-count-limited' => '門有頁$1。',
'category-file-count' => '{{PLURAL:$2|門有檔壹。|門有檔$1,有$2檔也。}}',
'category-file-count-limited' => '門有檔$1。',
'listingcontinuesabbrev' => '續',
'mainpagetext' => "<big>'''共筆臺已立'''</big>",
'mainpagedocfooter' => "欲識維基,見[http://meta.wikimedia.org/wiki/Help:Contents User's Guide]
== 始 ==
* [http://www.mediawiki.org/wiki/Manual:Configuration_settings Configuration settings list]
* [http://www.mediawiki.org/wiki/Manual:FAQ MediaWiki FAQ]
* [https://lists.wikimedia.org/mailman/listinfo/mediawiki-announce MediaWiki release mailing list]",
'about' => '述',
'article' => '文',
'newwindow' => '啟窗',
'cancel' => '捨',
'qbfind' => '尋',
'qbbrowse' => '覽',
'qbedit' => '纂',
'qbpageoptions' => '此頁',
'qbpageinfo' => '內文',
'qbmyoptions' => '吾好',
'qbspecialpages' => '非凡',
'moredotdotdot' => '見逾',
'mypage' => '寒舍',
'mytalk' => '書房',
'anontalk' => '與(IP)私議',
'navigation' => '導',
'and' => '與',
# Metadata in edit box
'metadata_help' => '衍意:',
'errorpagetitle' => '誤',
'returnto' => '返$1。',
'tagline' => '語出{{SITENAME}}',
'help' => '助',
'search' => '尋',
'searchbutton' => '尋',
'go' => '往',
'searcharticle' => '始',
'history' => '誌',
'history_short' => '誌',
'updatedmarker' => '新也',
'info_short' => '快訊',
'printableversion' => '印本',
'permalink' => '恆鏈',
'print' => '印',
'edit' => '纂',
'create' => '立',
'editthispage' => '纂',
'create-this-page' => '立',
'delete' => '刪',
'deletethispage' => '刪',
'undelete_short' => '還$1已刪',
'protect' => '緘',
'protect_change' => '易',
'protectthispage' => '緘封',
'unprotect' => '啟',
'unprotectthispage' => '啟函',
'newpage' => '新頁',
'talkpage' => '參議此文',
'talkpagelinktext' => '議',
'specialpage' => '特查',
'personaltools' => '家私',
'postcomment' => '評',
'articlepage' => '閱內文',
'talk' => '議',
'views' => '覽',
'toolbox' => '多寶',
'userpage' => '簿',
'projectpage' => '計畫',
'imagepage' => '述',
'mediawikipage' => '觀訊',
'templatepage' => '鑄模',
'viewhelppage' => '助文',
'categorypage' => '分類',
'viewtalkpage' => '見議',
'otherlanguages' => '他山',
'redirectedfrom' => '(渡自$1)',
'redirectpagesub' => '渡',
'lastmodifiedat' => '此頁於$1$2方易。', # $1 date, $2 time
'viewcount' => '此頁$1閱矣',
'protectedpage' => '此頁錮矣',
'jumpto' => '往:',
'jumptonavigation' => '嚮',
'jumptosearch' => '尋',
# All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage) and the disambiguation template definition (see disambiguations).
'aboutsite' => '述{{SITENAME}}',
'aboutpage' => 'Project:述',
'copyright' => '文奉$1行。',
'copyrightpagename' => '權歸{{SITENAME}}',
'copyrightpage' => '{{ns:project}}:版權',
'currentevents' => '世事',
'currentevents-url' => 'Project:世事',
'disclaimers' => '免責宣',
'disclaimerpage' => 'Project:免責宣',
'edithelp' => '助纂塾',
'edithelppage' => 'Help:纂',
'faq' => '頻答問',
'faqpage' => 'Project:頻答問',
'helppage' => 'Help:目錄',
'mainpage' => '卷首',
'mainpage-description' => '卷首',
'policy-url' => 'Project:策',
'portal' => '市集',
'portal-url' => 'Project:市集',
'privacy' => '隱私通例',
'privacypage' => 'Project:隱私通例',
'badaccess' => '子未逮',
'badaccess-group0' => '子未逮,歉限之。',
'badaccess-groups' => '子未逮,歉限之有{{PLURAL:$2|一|多}}:$1',
'versionrequired' => '惠置$1媒維基',
'versionrequiredtext' => '惠置$1媒維基,見[[Special:Version|版]]。',
'ok' => '可',
'retrievedfrom' => '取自"$1"',
'youhavenewmessages' => '子有$1($2)',
'newmessageslink' => '新訊',
'newmessagesdifflink' => '變更',
'youhavenewmessagesmulti' => '新訊於$1',
'editsection' => '纂',
'editold' => '纂',
'viewsourceold' => '察源碼',
'editlink' => '纂',
'viewsourcelink' => '察源碼',
'editsectionhint' => '纂 $1',
'toc' => '章',
'showtoc' => '示',
'hidetoc' => '藏',
'thisisdeleted' => '還$1或閱之?',
'viewdeleted' => '閱$1之?',
'restorelink' => '$1已刪',
'feedlinks' => '源︰',
'feed-unavailable' => '聯合源無視也',
'site-rss-feed' => '$1之RSS源',
'site-atom-feed' => '$1之Atom源',
'page-rss-feed' => '「$1」之RSS源',
'page-atom-feed' => '「$1」之Atom源',
'red-link-title' => '$1(查無此頁)',
# Short words for each namespace, by default used in the namespace tab in monobook
'nstab-main' => '文',
'nstab-user' => '齋',
'nstab-media' => '雅',
'nstab-special' => '奇',
'nstab-project' => '策',
'nstab-image' => '檔',
'nstab-mediawiki' => '訊',
'nstab-template' => '模',
'nstab-help' => '助',
'nstab-category' => '類',
# Main script and global functions
'nosuchaction' => '無可為',
'nosuchactiontext' => '無此址',
'nosuchspecialpage' => '無此特查',
'nospecialpagetext' => "'''<big>無此特查。</big>'''
見[[Special:SpecialPages|{{int:specialpages}}]]。",
# General errors
'error' => '有誤',
'databaseerror' => '庫藏誤然',
'dberrortext' => '問庫語誤,或軟體瑕焉。
末語道:
<blockquote><tt>$1</tt></blockquote>
內此函式"<tt>$2</tt>".
MySQL報有誤"<tt>$3: $4</tt>"。',
'dberrortextcl' => '庫藏問語有誤,末道:
"$1"
內此函式"$2".
MySQL報有誤"$3: $4"',
'noconnect' => '歉哉有變,莫能問庫藏。<br />
$1',
'nodb' => '莫能擇庫$1',
'cachederror' => '此為謄本,恐不新也',
'laggedslavemode' => '警示,此頁不新',
'readonly' => '鎖庫藏',
'enterlockreason' => '何以鎖之?何日啟之?',
'readonlytext' => '鎖者曰:「$1」,庫藏鎖矣,撰纂謝焉。',
'missing-article' => '或舊、或刪,未見昔者"$1" $2。
若非此故,恐有瑕焉,惠呈此址也。',
'missingarticle-rev' => '(審號:$1)',
'missingarticle-diff' => '(異:$1,$2)',
'internalerror' => '家誤',
'internalerror_info' => '家誤:$1',
'filecopyerror' => '"$1"謄"$2",未可為也。',
'filerenameerror' => '"$2"替"$1"名,未可為也。',
'filedeleteerror' => '"$1"未可刪也。',
'directorycreateerror' => '立目"$1",未可為也。',
'filenotfound' => '"$1"未見。',
'fileexistserror' => '"$1"存焉,未可儲也。',
'unexpected' => '異數,"$1"="$2"。',
'formerror' => '有誤:表不可呈',
'badarticleerror' => '此頁莫為之',
'cannotdelete' => '此頁或刪矣,不復為之。',
'badtitle' => '無此題',
'badtitletext' => '或別、或缺、或違、或他山謬鏈,此題不存也。',
'perfcached' => '下為謄本,恐不新也。',
'perfcachedts' => '下為謄本,$1新之。',
'wrong_wfQuery_params' => 'wfQuery()參數謬然<br />
函式: $1<br />
問語: $2',
'viewsource' => '覽源',
'viewsourcefor' => '$1',
'actionthrottled' => '無為',
'protectedinterface' => '此頁司版,緘之以遠濫。',
'editinginterface' => "'''警示:'''此頁司版,一髮牽身,惠慎之。如譯之,可慮[http://translatewiki.net/wiki/Main_Page?setlang=zh-hant translatewiki.net]也,為MediaWiki軟件本地化之計劃也。",
'sqlhidden' => '(SQL隱然)',
'cascadeprotected' => '此頁"迭緘"矣。$1頁牽連如下:
$2',
'namespaceprotected' => "子權未逮,莫能纂'''$1'''。",
'customcssjsprotected' => '牽他人,子權未逮,莫能纂之。',
'ns-specialprotected' => '奇頁禁纂也。',
'titleprotected' => "緘焉自[[User:$1|$1]]防建也。因''$2''也。",
# Virus scanner
'virus-badscanner' => "壞設:不明之病掃:''$1''",
'virus-scanfailed' => '敗掃(碼$1)',
'virus-unknownscanner' => '不明之反毒:',
# Login and logout pages
'logouttitle' => '去簿',
'logouttext' => "'''子去簿矣'''<br />
子可匿名還覽{{SITENAME}},或[[Special:UserLogin|復登]]同簿、異簿。未清謄本,覽器文舊,且慎之。",
'welcomecreation' => '== $1大駕光臨! ==
子簿增矣,敬更[[Special:Preferences|簿註]]。',
'loginpagetitle' => '合符節',
'yourname' => '名',
'yourpassword' => '符節',
'yourpasswordagain' => '復核節',
'remembermypassword' => '記之',
'externaldberror' => '認庫之錯或禁更爾之外簿。',
'login' => '登簿',
'nav-login-createaccount' => '登簿、增簿',
'loginprompt' => '登簿{{SITENAME}}須cookies,請准之。',
'userlogin' => '登簿、增簿',
'logout' => '去簿',
'userlogout' => '去簿',
'notloggedin' => '尚未登簿',
'nologin' => '無簿乎?往$1。',
'nologinlink' => '增簿',
'createaccount' => '增簿',
'gotaccount' => '有簿矣哉?往$1。',
'gotaccountlink' => '登簿',
'createaccountmail' => '同郵',
'badretype' => '符節不合也。',
'userexists' => '簿名存矣,惠更之',
'youremail' => '郵:',
'username' => '簿名:',
'uid' => '編號︰',
'prefs-memberingroups' => '{{PLURAL:$1|一|權任}}:',
'yourrealname' => '本名:',
'yourlanguage' => '語言:',
'yourvariant' => '變字:',
'yournick' => '署名︰',
'badsig' => '無效之自畫。
查HTML籤之。',
'badsiglength' => '署名宜簡。',
'yourgender' => '性別︰',
'gender-unknown' => '未',
'gender-male' => '男',
'gender-female' => '女',
'email' => '郵',
'prefs-help-realname' => '可用署也,選填之。',
'loginerror' => '登簿誤然',
'prefs-help-email' => '電郵地址,雖非必要,惟失符節之時,新者須寄於此。',
'prefs-help-email-required' => '郵須也。',
'nocookiesnew' => '{{SITENAME}}簿增而未登,惠准cookies後再登之。',
'nocookieslogin' => '登簿{{SITENAME}}須cookies,惠准之後登。',
'noname' => '缺簿名,或不格也。',
'loginsuccesstitle' => '登簿成矣',
'loginsuccess' => "'''$1'''登{{SITENAME}}矣",
'nosuchuser' => '查無此人。',
'nosuchusershort' => '查無"<nowiki>$1</nowiki>",惠核之。',
'nouserspecified' => '簿名須也',
'wrongpassword' => '符節不合,惠核之。',
'wrongpasswordempty' => '缺符節,惠補之。',
'passwordtooshort' => '符節短錯哉,莫逾$1字,且與簿名異也。',
'mailmypassword' => '遣吾符節',
'passwordremindertitle' => '新臨符節自{{SITENAME}}',
'passwordremindertext' => '$1求遣{{SITENAME}}($4):"$2"之臨符節為"$3"。日到有$5。
子若罔須或省更之,如舊即可。',
'noemail' => '"$1"無存郵也。',
'passwordsent' => '新節已遣$1",惠鑒復登之。',
'blocked-mailpassword' => '爾之IP已錮,密復無用之,以之濫也。',
'eauthentsent' => '核文遣矣。惠循核之,簿方活也。',
'throttled-mailpassword' => '密記已寄之於$1時前。
防濫,單一密記短至$1時寄之。',
'mailerror' => '信失遣如下:$1',
'acct_creation_throttle_hit' => '一日之內,但許一註。',
'emailauthenticated' => '$2 $3郵驛證矣',
'emailnotauthenticated' => '郵驛<strong>未證</strong>,下不遺書。',
'noemailprefs' => '郵驛須然如下:',
'emailconfirmlink' => '惠考郵驛',
'invalidemailaddress' => '驛址不格,惠正略之。',
'accountcreated' => '簿增矣',
'accountcreatedtext' => '$1簿增矣',
'createaccount-title' => '於{{SITENAME}}增簿',
'createaccount-text' => '有人於{{SITENAME}}用爾之電郵增名為 "$2" 之簿 ($4),符節為 "$3" 。汝應登,再改符節也。
如簿誤增,爾可略之。',
'login-throttled' => '爾多試於此簿之符中。請候再試之。',
'loginlanguagelabel' => '語:$1',
# Password reset dialog
'resetpass' => '變符',
'resetpass_announce' => '爾乃過郵之臨符登之。要完登,汝乃需設新符節:',
'resetpass_text' => '<!-- 加字 -->',
'resetpass_header' => '改簿符',
'oldpassword' => '舊符節:',
'newpassword' => '新符節:',
'retypenew' => '重察新符節:',
'resetpass_submit' => '設符再登',
'resetpass_success' => '爾之符節已改!現登簿中...',
'resetpass_bad_temporary' => '無效之臨符。
爾或改符,或求新臨符。',
'resetpass_forbidden' => '無改符節',
'resetpass-no-info' => '爾須登簿後方進此頁。',
'resetpass-submit-loggedin' => '改符節',
'resetpass-wrong-oldpass' => '無效之臨符或現符。
爾或改符,或求新臨符。',
'resetpass-temp-password' => '臨符節:',
# Edit page toolbar
'bold_sample' => '粗體',
'bold_tip' => '粗體',
'italic_sample' => '斜體',
'italic_tip' => '斜體',
'link_sample' => '鏈',
'link_tip' => '鏈內',
'extlink_sample' => 'http://www.example.com 鍵 題',
'extlink_tip' => '冠http://以鏈外',
'headline_sample' => '題',
'headline_tip' => '二題',
'math_sample' => '此書方程式',
'math_tip' => '數學方程式(LaTeX)',
'nowiki_sample' => '此不排版',
'nowiki_tip' => '不排維基之版',
'image_tip' => '嵌檔',
'media_tip' => '鏈檔',
'sig_tip' => '署名刻時',
'hr_tip' => '縱線,慎用之',
# Edit pages
'summary' => '概:',
'subject' => '題:',
'minoredit' => '令校',
'watchthis' => '派哨',
'savearticle' => '存儲',
'preview' => '草覽',
'showpreview' => '草覽',
'showlivepreview' => '即覽',
'showdiff' => '示異',
'anoneditwarning' => "'''警示:'''子未登簿,IP將誌。",
'missingsummary' => "''''醒示:'''子未概之,復存則文倍焉。",
'missingcommenttext' => '請贊之',
'summary-preview' => '覽概:',
'subject-preview' => '覽題:',
'blockedtitle' => '子見禁',
'blockedtext' => "<big>'''子名、IP見禁。'''</big>禁者$1也,因''$2''故。
* 始之時為:$8
* 終之時為:$6
* 見禁之人:$7
存惑可詢$1,或[[{{MediaWiki:Grouppage-sysop}}|有秩]],[[Special:Preferences|簿註]]無驛則信不遣。另,子IP為$3,其禁號為#$5。詢時切附之。",
'autoblockedtext' => "爾之IP或簿自禁,因簿先用,禁者$1也。因故::\\'\\'$2\\'\\'
* 始之時為:$8
* 終之時為:$6
* 見禁之人:$7
存惑可詢$1,或[[{{MediaWiki:Grouppage-sysop}}|有秩]],[[Special:Preferences|簿註]]無驛則信不遣。另,子用IP $3,禁號為#$5。詢時切附之。",
'blockedoriginalsource' => "'''$1'''本源如下:",
'blockededitsource' => "子'''$1纂文'''如下:",
'whitelistedittitle' => '登簿以纂',
'whitelistedittext' => '$1後方可纂文。',
'confirmedittitle' => '證驛以纂',
'confirmedittext' => '驛證方可纂文。惠見[[Special:Preferences|簿註]]。',
'loginreqtitle' => '須登簿',
'loginreqlink' => '登簿',
'loginreqpagetext' => '$1以覽它頁。',
'accmailtitle' => '符節傳矣',
'accmailtext' => '"$1"符節至$2矣',
'newarticle' => '撰',
'newarticletext' => '此頁尚缺。欲補,撰於下,有惑見[[{{MediaWiki:Helppage}}|助]]。
誤入者,返前即可。',
'anontalkpagetext' => "----''此匿論也,為未簿或不簿者設,IP俱錄以辨人焉。然IP不獨,恐生亂象,不喜惠[[Special:UserLogin/signup|增]][[Special:UserLogin|登簿]]遠之。",
'noarticletext' => '查無此文。',
'userpage-userdoesnotexist' => '"$1"之簿未增也。請建纂本頁前查之。',
'clearyourcache' => "'''註:'''重取頁面,文方新焉。
'''Mozilla / Firefox / Safari:'''押''Shift''並點''重新載入'',或合鍵''Ctrl-F5''或''Ctrl-R''(Macintosh為''Command-R'')。
'''Konqueror:'''點''Reload'',或押''F5''。
:''Opera:'''須至''Tools→Preferences''清謄本。
'''Internet Explorer:'''押''Ctrl''並點''重新整理'',或合鍵''Ctrl-F5''。",
'usercssjsyoucanpreview' => "'''訣:'''CSS/JS應先預覽而後存。",
'usercsspreview' => "'''預覽CSS。'''
'''尚未儲焉。'''",
'userjspreview' => "'''預覽JavaScript。'''
'''尚未儲焉。'''",
'userinvalidcssjstitle' => "'''警:'''\"\$1\"無此面版。自製者,全名務小寫,如{{ns:user}}:Foo/monobook.css 而非{{ns:user}}:Foo/Monobook.css",
'updated' => '(新)',
'note' => "'''註'''",
'previewnote' => "'''此乃預覽,尚未儲焉。'''",
'session_fail_preview' => "'''歉哉有變,子纂未存焉,惠再之。如復不成,[[Special:UserLogout|重登]]再試也。'''",
'session_fail_preview_html' => "'''歉哉有變,子纂未存焉'''
''此維基亦合純HTML,除預覽以遠惡JavaScript侵。''
'''纂文若合,惠再之。如復不成,簿[[Special:UserLogout|重登]]焉。'''",
'token_suffix_mismatch' => "'''君修見拒,蓋因代理之故,亂事見兮。'''",
'editing' => '纂$1',
'editingsection' => '纂節$1',
'editingcomment' => '贊$1',
'editconflict' => '纂沖$1',
'explainconflict' => '子纂與他人沖,上者時也,下者子也,望子合之。
註,<b>惟</b>上文儲焉<br />',
'yourtext' => '子也',
'storedversion' => '時也',
'nonunicodebrowser' => "'''警示:覽器不識萬國碼,以十六進位數代之,以保纂可也。'''",
'editingold' => "''''''警示'''子纂舊然。強儲之,則新易失焉。'''",
'yourdiff' => '異',
'copyrightwarning' => "{{SITENAME}}全文皆循$2,詳見$1。不喜他纂,但去可矣。文務親撰,或謄公本,
'''萬勿盜版!'''",
'copyrightwarning2' => "{{SITENAME}}全文,允眾人撰、纂、刪、校。不喜他纂,但去可矣。<br />
文務親撰,或謄公本,如$1。'''萬勿盜版!'''",
'longpagewarning' => "'''警示:此頁長$1仟位元組,逾卅二,覽器恐不盡堪,望縮斷之。'''",
'longpageerror' => "'''警示:文長$1仟位元組,越幅$2,未能儲焉。'''",
'readonlywarning' => "'''警示:修庫藏,存儲謝焉。惠謄文備用之。'''
鎖者曰:「$1」",
'protectedpagewarning' => "'''警示:庫藏鎖矣,惟有秩纂之。'''",
'semiprotectedpagewarning' => "'''註記'''庫藏鎖矣,惟登簿纂之。",
'templatesused' => '此文用模:',
'template-protected' => '(錮)',
'template-semiprotected' => '(半錮)',
'hiddencategories' => '此頁屬隱類之員有$1:',
'nocreatetitle' => '新題謝焉',
'nocreatetext' => '舊題可修,新題謝焉。[[Special:UserLogin|登簿、增簿]]以逮權也。',
'nocreate-loggedin' => '子權未逮,新頁謝焉。',
'permissionserrors' => '權未逮也',
'permissionserrorstext' => '子權未逮,有{{PLURAL:$1|因|因}}如下:',
'permissionserrorstext-withaction' => '子權未逮,有{{PLURAL:$1|因|因}}如$2:',
'recreate-deleted-warn' => "'''留意:刪文復造,惠慎纂。'''
誌刪如下:",
'deleted-notice' => '此頁刪矣。
此頁之誌參留之。',
'deletelog-fulllog' => '察整誌',
'edit-hook-aborted' => '鈎纂消矣。
無解也。',
'edit-gone-missing' => '無更頁。
刪之也。',
'edit-conflict' => '纂突。',
'edit-no-change' => '爾之纂已略,由字無改也。',
'edit-already-exists' => '不建新頁。
已存也。',
# Parser/template warnings
'expensive-parserfunction-warning' => '警:頁有多貴功呼。
其須少$2呼,現有$1呼。',
'expensive-parserfunction-category' => '頁有多貴功呼',
'post-expand-template-inclusion-warning' => '警:含模過大也。
一些模板將不會包含。',
'post-expand-template-inclusion-category' => '模含上限已超之頁',
'post-expand-template-argument-warning' => '警:此頁有至少一模數展大。
數略之。',
'post-expand-template-argument-category' => '含略模數之頁',
'parser-template-loop-warning' => '測迴模:[[$1]]',
'parser-template-recursion-depth-warning' => '已超迴模限深($1)',
# "Undo" feature
'undo-success' => '此審可返也。查確然完之。',
'undo-failure' => '中審之異,此審無返也。',
'undo-norev' => '其審無存或刪,此審無返也。',
'undo-summary' => '返[[Special:Contributions/$2|$2]]([[User talk:$2|書]])之審$1',
# Account creation failure
'cantcreateaccounttitle' => '新簿謝焉',
'cantcreateaccount-text' => "[[User:$3|S3]]因''$2''故,封子IP <b>$1</b>。",
# History pages
'viewpagelogs' => '覽誌',
'nohistory' => '此題無誌',
'currentrev' => '今審',
'currentrev-asof' => '$1之今審',
'revisionasof' => '$1審',
'revision-info' => '本版日期︰$1;作者︰$2', # Additionally available: $3: revision id
'previousrevision' => '←舊',
'nextrevision' => '新→',
'currentrevisionlink' => '今審',
'cur' => '辨今',
'next' => '後',
'last' => '前',
'page_first' => '首',
'page_last' => '末',
'histlegend' => "辨異:擇二孔後,按Enter、或點下鈕以辨之。<br />
釋義:'''({{int:cur}})'''與今審辨;'''({{int:last}})'''與前審辨;'''{{int:minoreditletter}}''',校文",
'history-fieldset-title' => '誌覽',
'deletedrev' => '刪矣',
'histfirst' => '初',
'histlast' => '末',
'historysize' => '($1位元組)',
'historyempty' => '(空)',
# Revision feed
'history-feed-title' => '誌審',
'history-feed-description' => '維基誌審',
'history-feed-item-nocomment' => '$1於$2', # user at time
'history-feed-empty' => '此頁不存,或刪、或更。類由此[[Special:Search|尋]]',
# Revision deletion
'rev-deleted-comment' => '(此註刪矣)',
'rev-deleted-user' => '(此簿刪矣)',
'rev-deleted-event' => '(此誌刪矣)',
'rev-deleted-text-permission' => "此審'''刪'''矣,詳見[{{fullurl:Special:Log/delete|page={{PAGENAMEE}}}}誌刪]。",
'rev-deleted-text-view' => "此審'''刪'''矣,惟有秩可見之,詳見[{{fullurl:Special:Log/delete|page={{FULLPAGENAMEE}}}} 誌刪]。",
'rev-deleted-no-diff' => "此審'''刪'''矣,無視之審也。
詳見[{{fullurl:Special:Log/delete|page={{PAGENAMEE}}}}誌刪]。",
'rev-deleted-unhide-diff' => "此審'''刪'''矣,
詳見[{{fullurl:Special:Log/delete|page={{PAGENAMEE}}}}誌刪]。
有秩仍看者,[$1 看此審]也。",
'rev-delundel' => '見/藏',
'revisiondelete' => '刪、還審',
'revdelete-nooldid-title' => '無此審。',
'revdelete-nooldid-text' => '審未擇,審未存,爾隱現審,不可為之。',
'revdelete-nologtype-title' => '無誌類',
'revdelete-nologtype-text' => '爾未定誌類以為之。',
'revdelete-toomanytargets-title' => '多標',
'revdelete-toomanytargets-text' => '爾定多標以為之。',
'revdelete-nologid-title' => '無效之誌項',
'revdelete-nologid-text' => '爾未定標誌項以為之或其無存也。',
'revdelete-selected' => "'''審[[:$1]]已擇$2:'''",
'logdelete-selected' => "'''已擇誌$1:'''",
'revdelete-text' => "'''刪審雖見誌,其文摒公眾,惟有秩可得之。'''無規則有秩可復還焉。",
'revdelete-suppress-text' => "'''限'''於此壓:
* 無適之個訊
*: ''地、號、保等之。''",
'revdelete-legend' => '見,規之以',
'revdelete-hide-text' => '藏審文',
'revdelete-hide-comment' => '藏贊',
'revdelete-hide-user' => '簿、IP以藏',
'revdelete-hide-restricted' => '廢有秩與簿之事',
'revdelete-suppress' => '廢有秩與簿之事',
'revdelete-hide-image' => '藏檔',
'revdelete-unsuppress' => '復審解限',
'revdelete-log' => '誌贊:',
'revdelete-submit' => '擇審使之',
'revdelete-logentry' => '[[$1]]之見審動矣',
'logdelete-logentry' => '[[$1]]之事見動矣',
'revdelete-success' => "'''見審已設也。'''",
'logdelete-success' => "'''見事已設也。'''",
'revdel-restore' => '動見之',
'pagehist' => '頁史',
'deletedhist' => '刪史',
'revdelete-content' => '字',
'revdelete-summary' => '摘',
'revdelete-uname' => '簿名',
'revdelete-restricted' => '應限至有秩',
'revdelete-unrestricted' => '除限自有秩',
'revdelete-hid' => '隱$1',
'revdelete-unhid' => '非隱$1',
'revdelete-log-message' => '$1之修$2',
'logdelete-log-message' => '$1之事$2',
# Suppression log
'suppressionlog' => '誌廢',
'suppressionlogtext' => '下乃刪及錮物之列也。
[[Special:IPBlockList|IP之錮]]有現之閱。',
# History merging
'mergehistory' => '併頁之誌',
'mergehistory-header' => "此頁講汝併一源頁之誌至二頁也。
認之易繼留該頁之前誌也。
'''以源頁之現誌必會保持。'''",
'mergehistory-box' => '併二頁之誌:',
'mergehistory-from' => '源頁:',
'mergehistory-into' => '到頁:',
'mergehistory-list' => '可併之誌',
'mergehistory-merge' => '下[[:$1]]之誌可併至[[:$2]]。用選鈕欄以併只於定時前所建之誌。留心用導連將重設本欄也。',
'mergehistory-go' => '示可併之誌',
'mergehistory-submit' => '併誌',
'mergehistory-empty' => '無誌可併',
'mergehistory-success' => '[[:$1]]之$3誌已併至[[:$2]]。',
'mergehistory-fail' => '併誌無進也,該頁及時間參數請重檢也。',
'mergehistory-no-source' => '源頁$1無存也。',
'mergehistory-no-destination' => '到頁$1無存也。',
'mergehistory-invalid-source' => '源頁之題須效之。',
'mergehistory-invalid-destination' => '到頁之題須效之。',
'mergehistory-autocomment' => '併[[:$1]]至[[:$2]]',
'mergehistory-comment' => '併[[:$1]]至[[:$2]]:$3',
'mergehistory-same-destination' => '源頁和到頁無同也',
'mergehistory-reason' => '因:',
# Merge log
'mergelog' => '誌併',
'pagemerge-logentry' => '併咗[[$1]]至[[$2]] (訂至$3)',
'revertmerge' => '悔併',
'mergelogpagetext' => '下乃近頁之誌併至二頁之表也。',
# Diffs
'history-title' => '$1之誌',
'difference' => '(辨異)',
'lineno' => '列$1:',
'compareselectedversions' => '辨二擇',
'visualcomparison' => '較見',
'wikicodecomparison' => '較字',
'editundo' => '悔',
'diff-multi' => '(未示之途審有$1)',
'diff-movedto' => '遷到$1',
'diff-styleadded' => '加$1樣表',
'diff-added' => '加$1',
'diff-changedto' => '改到$1',
'diff-movedoutof' => '除自$1',
'diff-styleremoved' => '除$1樣表',
'diff-removed' => '除$1',
'diff-changedfrom' => '改自$1',
'diff-src' => '源碼',
'diff-withdestination' => '跟$1目的地',
'diff-with' => '跟 $1 $2',
'diff-with-final' => '與 $1 $2',
'diff-width' => '闊',
'diff-height' => '高',
'diff-p' => '段',
'diff-blockquote' => '錄',
'diff-h1' => '題(一級)',
'diff-h2' => '題(二級)',
'diff-h3' => '題(三級)',
'diff-h4' => '題(四級)',
'diff-h5' => '題(五級)',
'diff-pre' => '預設塊',
'diff-div' => '部分',
'diff-ul' => '未排表',
'diff-ol' => '已排表',
'diff-li' => '表項',
'diff-table' => '表',
'diff-tbody' => '表容',
'diff-tr' => '行',
'diff-td' => '格',
'diff-th' => '表頭',
'diff-br' => '斷行',
'diff-hr' => '橫線',
'diff-code' => '電腦碼塊',
'diff-dl' => '定表',
'diff-dt' => '定字',
'diff-dd' => '解',
'diff-input' => '輸',
'diff-form' => '表',
'diff-img' => '圖',
'diff-span' => '樣',
'diff-a' => '接',
'diff-i' => '斜',
'diff-b' => '粗',
'diff-strong' => '強',
'diff-em' => '重',
'diff-font' => '字體',
'diff-big' => '大',
'diff-del' => '刪',
'diff-tt' => '固闊',
'diff-sub' => '下標',
'diff-sup' => '上標',
'diff-strike' => '刪線',
# Search results
'searchresults' => '得尋',
'searchresults-title' => '"$1"得尋',
'searchresulttext' => '何索{{SITENAME}},詳見[[{{MediaWiki:Helppage}}|{{int:help}}]]。',
'searchsubtitle' => "'''[[:$1]]'''尋焉([[Special:Prefixindex/$1|『$1』之全首頁]]{{int:pipe-separator}}[[Special:WhatLinksHere/$1|『$1』之全取佐]])",
'searchsubtitleinvalid' => "'''$1'''尋焉",
'noexactmatch' => "'''無題曰\"\$1\"。'''子可[[:\$1|撰之]]。",
'noexactmatch-nocreate' => "'''無題曰\"\$1\"。'''",
'toomanymatches' => '多配應之,試異詢也',
'titlematches' => '合題',
'notitlematches' => '無題合',
'textmatches' => '合文',
'notextmatches' => '無文合',
'prevn' => '前$1',
'nextn' => '次$1',
'viewprevnext' => '見($1)($2)($3)',
'searchmenu-legend' => '尋選',
'searchmenu-exists' => "'''在此wiki中有頁為\"[[:\$1]]\"'''",
'searchmenu-new' => "'''在此wiki上建頁\"[[:\$1]]\"!'''",
'searchhelp-url' => 'Help:目錄',
'searchmenu-prefix' => '[[Special:PrefixIndex/$1|查此首之頁]]',
'searchprofile-articles' => '容',
'searchprofile-articles-and-proj' => '容與題',
'searchprofile-project' => '題',
'searchprofile-images' => '檔',
'searchprofile-everything' => '全',
'searchprofile-advanced' => '進',
'searchprofile-articles-tooltip' => '在$1中尋',
'searchprofile-project-tooltip' => '在$1中尋',
'searchprofile-images-tooltip' => '尋檔',
'searchprofile-everything-tooltip' => '尋全(含議)',
'searchprofile-advanced-tooltip' => '自定名集中尋',
'prefs-search-nsdefault' => '用定值尋:',
'prefs-search-nscustom' => '尋自定名集:',
'search-result-size' => '$1 ($2字)',
'search-result-score' => '關:$1%',
'search-redirect' => '(轉 $1)',
'search-section' => '(節 $1)',
'search-suggest' => '爾否解之:$1',
'search-interwiki-caption' => '結義金蘭',
'search-interwiki-default' => '結果有$1:',
'search-interwiki-more' => '(多)',
'search-mwsuggest-enabled' => '有議',
'search-mwsuggest-disabled' => '無議',
'search-relatedarticle' => '關',
'mwsuggest-disable' => '停AJAX議',
'searchrelated' => '關',
'searchall' => '全',
'showingresults' => "見'''$1'''尋,自'''$2'''始:",
'showingresultsnum' => "見'''$3'''尋,自'''$2'''始:",
'showingresultstotal' => "見'''$1{{PLURAL:$4||至$2}}''',共'''$3'''尋",
'nonefound' => "'''注''':部名冊預尋也。。試''all:''尋全名刪之頁(含議模等),或可用要之名冊為前綴也。",
'search-nonefound' => '詢中無結。',
'powersearch' => '尋',
'powersearch-legend' => '尋',
'powersearch-ns' => '尋名集:',
'powersearch-redir' => '轉表',
'powersearch-field' => '尋',
'search-external' => '外尋',
'searchdisabled' => '{{SITENAME}}因性能而停用之。可Gooogle查之,乃之過時也。',
# Preferences page
'preferences' => '簿註',
'mypreferences' => '簿註',
'prefs-edits' => '數計:',
'prefsnologin' => '未登簿',
'prefsnologintext' => '註記須<span class="plainlinks">[{{fullurl:Special:UserLogin|returnto=$1}} 登簿]</span>。',
'prefsreset' => '簿註歸白',
'qbsettings-none' => '無',
'changepassword' => '易符節',
'skin' => '面版',
'skin-preview' => '草覽',
'math' => '數學',
'dateformat' => '日期格式',
'datedefault' => '原註',
'datetime' => '日時',
'math_failure' => '譯不成',
'math_unknown_error' => '未知之誤',
'math_unknown_function' => '未知函式',
'math_lexing_error' => '律有誤',
'math_syntax_error' => '語法有誤',
'prefs-personal' => '概簿',
'prefs-rc' => '近易',
'prefs-watchlist' => '哨站',
'prefs-watchlist-days' => '哨報有日',
'prefs-watchlist-days-max' => '(最大有七)',
'prefs-watchlist-edits' => '哨站有易',
'prefs-watchlist-edits-max' => '(最多之量:一千)',
'prefs-misc' => '雜',
'prefs-resetpass' => '更符節',
'saveprefs' => '儲',
'resetprefs' => '棄',
'restoreprefs' => '重修',
'textboxsize' => '在修',
'prefs-edit-boxsize' => '修框尺',
'rows' => '行:',
'columns' => '列:',
'searchresultshead' => '尋',
'resultsperpage' => '頁示尋',
'contextlines' => '尋分列',
'contextchars' => '列有字',
'recentchangesdays' => '近易示日:',
'recentchangesdays-max' => '(最大有$1)',
'recentchangescount' => '修著凡幾︰',
'savedprefs' => '簿註書矣',
'timezonelegend' => '時區:',
'timezonetext' => '¹與伺服器偏時有',
'localtime' => '本地時:',
'timezoneselect' => '時區:',
'timezoneuseserverdefault' => '用伺服器之預定',
'timezoneuseoffset' => '它(定偏)',
'timezoneoffset' => '偏¹:',
'servertime' => '伺服器時:',
'guesstimezone' => '瀏覽器填之',
'timezoneregion-africa' => '非洲',
'timezoneregion-america' => '美洲',
'timezoneregion-antarctica' => '南極洲',
'timezoneregion-arctic' => '北極',
'timezoneregion-asia' => '亞洲',
'timezoneregion-atlantic' => '大西洋',
'timezoneregion-australia' => '澳洲',
'timezoneregion-europe' => '歐洲',
'timezoneregion-indian' => '印度洋',
'timezoneregion-pacific' => '太平洋',
'allowemail' => '允遺書',
'prefs-searchoptions' => '尋項',
'prefs-namespaces' => '名集',
'defaultns' => '定尋之名集:',
'default' => '予定',
'files' => '檔',
'prefs-custom-css' => '定之CSS',
'prefs-custom-js' => '定之JS',
# User rights
'userrights' => '秉治權任', # Not used as normal message but as header for the special page itself
'userrights-lookup-user' => '司社',
'userrights-user-editname' => '簿名:',
'editusergroup' => '治社',
'editinguser' => "正纂簿'''[[User:$1|$1]]''' ([[User talk:$1|{{int:talkpagelinktext}}]]{{int:pipe-separator}}[[Special:Contributions/$1|{{int:contribslink}}]]) 之權",
'userrights-editusergroup' => '治社',
'saveusergroups' => '定之',
'userrights-groupsmember' => '有員:',
'userrights-groups-help' => '足下可為者有二︰
*賦其權,此其一也;
*去其職,此其二也。
*而星號在前者,一旦賦予,不可去也,宜慎焉。',
'userrights-reason' => '因:',
'userrights-no-interwiki' => '爾無權改他山wiki之簿權也。',
'userrights-nodatabase' => '資料庫$1無存或非本地也。',
'userrights-nologin' => '爾以有秩乲簿[[Special:UserLogin|登]]後以定簿之權也。',
'userrights-notallowed' => '爾之簿無權定簿之權也。',
'userrights-changeable-col' => '爾所管轄',
'userrights-unchangeable-col' => '非爾所轄',
'userrights-irreversible-marker' => '$1*',
# Groups
'group' => '社:',
'group-user' => '簿',
'group-autoconfirmed' => '自證其簿',
'group-bot' => '僕',
'group-sysop' => '有秩',
'group-bureaucrat' => '門下',
'group-suppress' => '監',
'group-all' => '(眾)',
'group-user-member' => '簿',
'group-autoconfirmed-member' => '自證其簿',
'group-bot-member' => '僕',
'group-sysop-member' => '有秩',
'group-bureaucrat-member' => '門下',
'group-suppress-member' => '監',
'grouppage-user' => '{{ns:project}}:簿',
'grouppage-autoconfirmed' => '{{ns:project}}:自證其簿',
'grouppage-bot' => '{{ns:project}}:僕',
'grouppage-sysop' => '{{ns:project}}:有秩',
'grouppage-bureaucrat' => '{{ns:project}}:門下',
'grouppage-suppress' => '{{ns:project}}:監',
# Rights
'right-read' => '閱頁',
'right-edit' => '纂頁',
'right-createpage' => '建頁(議不含)',
'right-createtalk' => '建議頁',
'right-createaccount' => '增簿',
'right-minoredit' => '示小改',
'right-move' => '遷頁',
'right-move-subpages' => '連遷子頁',
'right-move-rootuserpages' => '遷根齋',
'right-movefile' => '遷檔',
'right-suppressredirect' => '遷頁時無增轉',
'right-upload' => '貢獻品物',
'right-reupload' => '蓋現之品物',
'right-reupload-own' => '蓋同簿之品物',
'right-reupload-shared' => '於本無視共媒物庫上之品物',
'right-upload_by_url' => '由URL貢品物',
'right-purge' => '無確認頁除網存',
'right-autoconfirmed' => '纂半錮之頁',
'right-bot' => '視自動之程序',
'right-nominornewtalk' => '小改無發新信之示',
'right-apihighlimits' => '於API查頂上',
'right-writeapi' => '用寫之API',
'right-delete' => '刪頁面',
'right-bigdelete' => '刪大史之頁',
'right-deleterevision' => '刪與反刪頁之審',
'right-deletedhistory' => '看刪之項,無關之字',
'right-browsearchive' => '尋刪之頁',
'right-undelete' => '反刪頁',
'right-suppressrevision' => '看與復由有秩藏之審',
'right-suppressionlog' => '看私之誌',
'right-block' => '鎖他簿無編',
'right-blockemail' => '鎖簿無電郵',
'right-hideuser' => '鎖簿名,予藏眾',
'right-ipblock-exempt' => '繞IP鎖、自鎖與圍鎖',
'right-proxyunbannable' => '繞Proxy之自鎖',
'right-protect' => '改錮級與纂錮頁',
'right-editprotected' => '纂錮頁(無連錮)',
'right-editinterface' => '纂要',
'right-editusercssjs' => '纂他簿之CSS與JS檔',
'right-rollback' => '速復上簿頁之纂',
'right-markbotedits' => '標復纂為機纂',
'right-noratelimit' => '無率之上限',
'right-import' => '由它wiki匯入頁',
'right-importupload' => '由品貢匯入頁',
'right-patrol' => '示它纂作已巡查',
'right-autopatrol' => '將己纂自示為已巡查',
'right-patrolmarks' => '察近巡查記之易',
'right-unwatchedpages' => '看未哨之頁',
'right-trackback' => '交一trackback',
'right-mergehistory' => '併頁之史',
'right-userrights' => '纂簿權',
'right-userrights-interwiki' => '纂另wiki他簿之權',
'right-siteadmin' => '鎖與解鎖資料庫',
'right-reset-passwords' => '設他簿之符節',
'right-override-export-depth' => '出有五層深之頁',
# User rights log
'rightslog' => '職權志',
'rightsnone' => '(凡)',
# Associated actions - in the sentence "You do not have permission to X"
'action-read' => '閱此頁',
'action-edit' => '纂此頁',
'action-createpage' => '建此頁',
'action-createtalk' => '建論頁',
'action-createaccount' => '增簿',
'action-minoredit' => '示纂為小',
'action-move' => '移頁',
'action-move-subpages' => '移頁和其字頁',
'action-move-rootuserpages' => '移根齋',
'action-movefile' => '移檔',
'action-upload' => '貢檔',
'action-reupload' => '蓋現檔',
'action-reupload-shared' => '蓋庫檔',
'action-upload_by_url' => '自URL貢檔',
'action-writeapi' => '寫API',
'action-delete' => '刪頁',
'action-deleterevision' => '刪審',
'action-deletedhistory' => '看此頁之刪史',
'action-browsearchive' => '尋刪頁',
'action-undelete' => '反刪此頁',
'action-suppressrevision' => '查復是次之隱訂',
'action-suppressionlog' => '看此誌私',
'action-block' => '禁簿纂',
'action-protect' => '更頁錮',
'action-import' => '自另wiki入此頁',
'action-importupload' => '自貢入此頁',
'action-patrol' => '示他纂為巡',
'action-autopatrol' => '示己纂為巡',
'action-unwatchedpages' => '查無哨',
'action-trackback' => '交trackback',
'action-mergehistory' => '併此頁之史',
'action-userrights' => '纂全權',
'action-userrights-interwiki' => '纂他wiki上之權',
'action-siteadmin' => '鎖及解鎖其庫',
# Recent changes
'nchanges' => '$1易',
'recentchanges' => '近易',
'recentchanges-legend' => '近易項',
'recentchangestext' => '共筆揮新,悉列於此。',
'rcnote' => "下為自$4$5起,'''$2'''日內'''$1'''近易也。",
'rcnotefrom' => "下為自'''$2'''至'''$1'''之易也。",
'rclistfrom' => '自$1起之易也',
'rcshowhideminor' => '$1校',
'rcshowhidebots' => '$1僕',
'rcshowhideliu' => '$1簿',
'rcshowhideanons' => '$1匿名',
'rcshowhidepatr' => '$1哨',
'rcshowhidemine' => '$1吾纂',
'rclinks' => '$2日內$1近易。<br />$3',
'diff' => '辨',
'hist' => '誌',
'hide' => '藏',
'show' => '示',
'minoreditletter' => '校',
'newpageletter' => '新',
'boteditletter' => '僕',
'number_of_watching_users_pageview' => '[放有$1哨]',
'rc_categories_any' => '任',
'newsectionsummary' => '/* $1 */ 新節',
'rc-enhanced-expand' => '示細(要 JavaScript)',
'rc-enhanced-hide' => '藏細',
# Recent changes linked
'recentchangeslinked' => '援引',
'recentchangeslinked-title' => '「$1」援引近易',
'recentchangeslinked-noresult' => '限期內無近易。',
'recentchangeslinked-summary' => "此奇頁乃列''由''頁援之近易(或對類之員)。
有[[Special:Watchlist|爾有哨]]者'''粗體'''。",
'recentchangeslinked-page' => '頁名:',
'recentchangeslinked-to' => '示援頁',
# Upload
'upload' => '進獻',
'uploadbtn' => '進獻',
'reupload' => '復獻之',
'reuploaddesc' => '消進乃返載獻',
'uploadnologin' => '未登簿',
'uploadnologintext' => '[[Special:UserLogin|登簿]]始可進獻',
'upload_directory_missing' => '目錄$1已失,無建之。',
'upload_directory_read_only' => '目錄$1禁入,無可獻。',
'uploaderror' => '進獻有變',
'uploadtext' => "下表以獻,[[Special:FileList|載獻]]覽之。或見[[Special:Log/upload|誌獻]]與[[Special:Log/delete|誌刪]]。
欲嵌頁中,是格鏈之其一:
* '''<tt><nowiki>[[</nowiki>{{ns:file}}:File.jpg]]</tt>'''用此整獻
* '''<tt><nowiki>[[</nowiki>{{ns:file}}:File.png||200px|thumb|left|名]]</tt>'''以二百像素置左框置『名』
* '''<tt><nowiki>[[</nowiki>{{ns:media}}:File.ogg]]</tt>'''直連獻,無示獻",
'upload-permitted' => '可之物類:$1。',
'upload-preferred' => '議之物類:$1。',
'upload-prohibited' => '禁之物類:$1。',
'uploadlog' => '誌獻',
'uploadlogpage' => '誌獻',
'uploadlogpagetext' => '近獻如下。
看[[Special:NewFiles|新畫獻]]示獻功。',
'filename' => '名',
'filedesc' => '概',
'fileuploadsummary' => '概:',
'filereuploadsummary' => '動:',
'filestatus' => '授權:',
'filesource' => '源:',
'uploadedfiles' => '進獻',
'ignorewarning' => '強儲之',
'ignorewarnings' => '警略。',
'minlength1' => '名務逾一字元。',
'illegalfilename' => '名"$1"不格,更之再焉。',
'badfilename' => '更名"$1。"。',
'filetype-badmime' => '「$1」之MIME類物檔案不能獻之。',
'filetype-bad-ie-mime' => '因 Internet Explorer 偵作「$1」不貢也。它乃有危險之類也。',
'filetype-unwanted-type' => "'''「.$1」'''乃無需之物類也。
議之物類有{{PLURAL:$3|一|多}}$2也。",
'filetype-banned-type' => "'''「.$1」'''乃無允之物類也。
允之物類有{{PLURAL:$3|一|多}}$2也。",
'filetype-missing' => '檔名無後綴也(如「.jpg」)。',
'large-file' => '檔長$2仟位元組,不逾$1為佳。',
'emptyfile' => '無以獻,疑謬名也,惠核之。',
'fileexists' => "'''<tt>$1</tt>'''存矣,欲蓋之則再也。",
'filepageexists' => "此檔之述於'''<tt>$1</tt>'''存矣,檔未存也。爾入述無存也。要現之,爾需纂之。",
'fileexists-thumb' => "<center>'''現存之檔'''</center>",
'file-exists-duplicate' => '此檔乃重檔{{PLURAL:$1|一|數}}:',
'file-deleted-duplicate' => '此檔([[$1]])前刪。爾需查刪錄再貢之。',
'successfulupload' => '檔案安矣',
'uploadwarning' => '慎焉!',
'savefile' => '存之',
'uploadedimage' => '進獻"[[$1]]"',
'overwroteimage' => '新置「[[$1]]」矣',
'uploaddisabledtext' => '貢被禁也。',
'php-uploaddisabledtext' => 'PHP之貢被禁也。查 file_uploads 之。',
'sourcefilename' => '源名:',
'destfilename' => '欲置檔名:',
'upload-maxfilesize' => '檔限:$1',
'watchthisupload' => '派哨',
'upload-wasdeleted' => "'''警示:復獻棄檔,慎續之。'''
誌刪如下:",
'filename-bad-prefix' => "獻檔以'''「$1」'''首,常由相機瞎造,惠更述之。",
'license-nopreview' => '(謝草覽)',
# Special:ListFiles
'listfiles-summary' => '此奇頁示檔之全呈也。
設最後之檔呈示於表頂。
點題改其列之。',
'listfiles_search_for' => '以媒名尋:',
'imgfile' => '檔',
'listfiles' => '見檔',
'listfiles_date' => '時',
'listfiles_name' => '名',
'listfiles_user' => '簿',
'listfiles_size' => '幅(位元組)',
'listfiles_description' => '述',
'listfiles_count' => '擇',
# File description page
'filehist' => '檔史',
'filehist-help' => '揀日尋檔。',
'filehist-deleteall' => '全刪',
'filehist-deleteone' => '刪',
'filehist-revert' => '還',
'filehist-current' => '今',
'filehist-datetime' => '時',
'filehist-thumb' => '縮',
'filehist-thumbtext' => '於$1之縮',
'filehist-nothumb' => '無縮',
'filehist-user' => '薄',
'filehist-dimensions' => '度',
'filehist-filesize' => '檔幅',
'filehist-comment' => '註',
'imagelinks' => '檔所繫者',
'linkstoimage' => '下頁連本檔有$1:',
'linkstoimage-more' => '連檔有多於$1。
下表示連檔之首$1。
[[Special:WhatLinksHere/$2|整表]]可供之閱也。',
'nolinkstoimage' => '無頁連本檔也。',
'morelinkstoimage' => '閱檔[[Special:WhatLinksHere/$1|接]]。',
'redirectstofile' => '下檔轉到此檔有$1:',
'duplicatesoffile' => '下檔重此檔有$1:',
'sharedupload' => '此檔為$1之共傳,可另項用也。', # $1 is the repo name, $2 is shareduploadwiki(-desc)
'shareduploadwiki' => '詳閱$1。',
'shareduploadwiki-desc' => '於共庫上$1之示。',
'shareduploadwiki-linktext' => '檔述',
'noimage' => '查無此檔,爾可$1。',
'noimage-linktext' => '貢焉',
'uploadnewversion-linktext' => '更新此檔',
# File reversion
'filerevert' => '還$1',
'filerevert-legend' => '還檔',
'filerevert-intro' => "'''[[Media:$1|$1]]'''欲還回$2$3之版$4。",
'filerevert-comment' => '註:',
'filerevert-defaultcomment' => '還$1$2之版矣',
'filerevert-submit' => '還',
'filerevert-success' => "'''[[Media:$1|$1]]''',$2$3之版$4還矣。",
'filerevert-badversion' => '該日無版也。',
# File deletion
'filedelete' => '刪$1',
'filedelete-legend' => '刪檔',
'filedelete-intro' => "欲刪'''[[Media:$1|$1]]'''。",
'filedelete-intro-old' => "欲刪'''[[Media:$1|$1]]'''$2$3之版$4。",
'filedelete-comment' => '刪因:',
'filedelete-submit' => '刪',
'filedelete-success' => "'''$1'''刪矣。",
'filedelete-success-old' => "'''[[Media:$1|$1]]'''$2$3之版刪矣。",
'filedelete-nofile' => "無'''$1'''也。",
'filedelete-nofile-old' => "無合'''$1'''藏也。",
'filedelete-otherreason' => '另/附之因:',
'filedelete-reason-otherlist' => '另因',
'filedelete-reason-dropdown' => '
*常刪之因
** 侵版權
** 重檔',
'filedelete-edit-reasonlist' => '纂刪因',
# MIME search
'mimesearch' => '篩檔',
'mimesearch-summary' => '此頁可以MIME篩檔.格仿「文類/次類」,如<tt>image/jpeg</tt>。',
'mimetype' => 'MIME類有:',
'download' => '載下',
# Unwatched pages
'unwatchedpages' => '無哨頁',
# List redirects
'listredirects' => '表轉',
# Unused templates
'unusedtemplates' => '墨乾',
'unusedtemplatestext' => '此表閒模,篤刪前惠考支鏈。',
'unusedtemplateswlh' => '支鏈',
# Random page
'randompage' => '風掀',
# Random redirect
'randomredirect' => '任渡',
'randomredirect-nopages' => '「$1」名冊內無渡也。',
# Statistics
'statistics' => '彙統',
'statistics-header-pages' => '頁彙統',
'statistics-header-edits' => '纂彙統',
'statistics-header-views' => '閱彙統',
'statistics-header-users' => '有簿彙統',
'statistics-articles' => '容頁',
'statistics-pages' => '頁',
'statistics-pages-desc' => 'wiki上之全頁,含議、轉等',
'statistics-files' => '已貢',
'statistics-edits' => '自{{SITENAME}}設之頁纂數',
'statistics-edits-average' => '每頁均纂數',
'statistics-views-total' => '閱總',
'statistics-views-peredit' => '每纂閱數',
'statistics-jobqueue' => '[http://www.mediawiki.org/wiki/Manual:Job_queue 隊]長',
'statistics-users' => '註[[Special:ListUsers|簿]]',
'statistics-users-active' => '活簿',
'statistics-users-active-desc' => '早$1日前更動之簿',
'statistics-mostpopular' => '燴炙',
'disambiguations' => '釋義',
'disambiguations-text' => '頁下引[[MediaWiki:Disambiguationspage]]模,求釋義,宜正題之。',
'doubleredirects' => '窮渡',
'doubleredirectstext' => '頁下窮渡,迭列以示。首尾宿合,宜正渡之。',
'double-redirect-fixed-move' => '[[$1]]遷畢,現渡至[[$2]]',
'double-redirect-fixer' => '修渡',
'brokenredirects' => '斷渡',
'brokenredirectstext' => '頁下斷渡。',
'brokenredirects-edit' => '(替)',
'brokenredirects-delete' => '(刪)',
'withoutinterwiki' => '孤語',
'withoutinterwiki-summary' => '頁下無鏈他語。',
'withoutinterwiki-legend' => '首',
'withoutinterwiki-submit' => '示',
'fewestrevisions' => '鮮察',
# Miscellaneous special pages
'nbytes' => '$1位元組',
'ncategories' => '$1門',
'nlinks' => '$1鏈',
'nmembers' => '$1戶',
'nrevisions' => '$1審',
'nviews' => '$1閱',
'lonelypages' => '孤寡',
'lonelypagestext' => '頁下無鏈或含',
'uncategorizedpages' => '欲訂',
'uncategorizedcategories' => '問栓',
'uncategorizedimages' => '候裱',
'uncategorizedtemplates' => '待蘸',
'unusedcategories' => '樞鏽',
'unusedimages' => '色褪',
'popularpages' => '膾炙',
'wantedcategories' => '求門',
'wantedpages' => '徵頁',
'wantedpages-badtitle' => '結組無題: $1',
'wantedfiles' => '求檔',
'wantedtemplates' => '徵模',
'mostlinked' => '好料',
'mostlinkedcategories' => '豪門',
'mostlinkedtemplates' => '美模',
'mostcategories' => '跨船',
'mostimages' => '名檔',
'mostrevisions' => '屢審',
'prefixindex' => '以鏈外查',
'shortpages' => '短篇',
'longpages' => '長言',
'deadendpages' => '此無路也',
'protectedpages' => '頁錮',
'protectedpages-indef' => '只示無期之錮',
'protectedpages-cascade' => '只示連串之錮',
'listusers' => '點簿',
'listusers-editsonly' => '只示有纂之簿',
'listusers-creationsort' => '按先後列之',
'usereditcount' => '$1纂',
'usercreated' => '建於$1$2',
'newpages' => '新灶',
'newpages-username' => '簿名:',
'ancientpages' => '陳年',
'move' => '遷',
'movethispage' => '遷此頁',
'unusedimagestext' => '<p>他站可以網址鏈檔,故下列並非盡閒,註記之。</p>',
'unusedcategoriestext' => '以下空門,無依可活。',
'notargettitle' => '落靶',
'notargettext' => '簿、頁未定,無可為之。',
'nopagetitle' => '落靶之頁',
'nopagetext' => '頁未定,無可為之。',
'pager-newer-n' => '新$1次',
'pager-older-n' => '陳$1次',
'suppress' => '監',
# Book sources
'booksources' => '書海',
'booksources-search-legend' => '舀書海',
'booksources-go' => '往',
'booksources-text' => '有賈售新舊書,或有助焉。茲列如下:',
'booksources-invalid-isbn' => '供之ISBN無確,查始複之誤。',
# Special:Log
'specialloguserlabel' => '簿:',
'speciallogtitlelabel' => '標:',
'log' => '誌',
'all-logs-page' => '眾誌',
'alllogstext' => '眾{{SITENAME}}之誌有合者,俱併版見。擇門、選簿、限疆以裁之。',
'logempty' => '無合誌也。',
'log-title-wildcard' => '題以此始者,取之',
# Special:AllPages
'allpages' => '全典',
'alphaindexline' => '自$1至$2',
'nextpage' => '次頁($1)',
'prevpage' => '先頁($1)',
'allpagesfrom' => '始頁:',
'allpagesto' => '末頁:',
'allarticles' => '全典',
'allinnamespace' => '全$1名冊',
'allnotinnamespace' => '非$1名冊',
'allpagesprev' => '前',
'allpagesnext' => '次',
'allpagessubmit' => '往',
'allpagesprefix' => '冠頁以:',
'allpagesbadtitle' => '或冠有他語、他山、或含禁字,題標不格。',
'allpages-bad-ns' => '無"$1"名冊',
# Special:Categories
'categories' => '類',
'categoriespagetext' => '大典有頁或媒。
[[Special:UnusedCategories|未類]]無示之。
閱[[Special:WantedCategories|需類]]也。',
'categoriesfrom' => '示此項起之類:',
'special-categories-sort-count' => '排數',
'special-categories-sort-abc' => '排字',
# Special:DeletedContributions
'deletedcontributions' => '已刪之積',
'deletedcontributions-title' => '所棄之事',
# Special:LinkSearch
'linksearch' => '尋網連',
'linksearch-pat' => '尋址:',
'linksearch-ns' => '名集:',
'linksearch-ok' => '尋',
'linksearch-text' => '用似"*.wikipedia.org"之萬字。<br />
援之議:<tt>$1</tt>',
'linksearch-line' => '$1連$2',
'linksearch-error' => '萬字僅用於機之始也。',
# Special:ListUsers
'listusersfrom' => '始簿:',
'listusers-submit' => '見',
'listusers-noresult' => '尋無簿。',
# Special:Log/newusers
'newuserlogpage' => '誌簿',
'newuserlogpagetext' => '此為誌簿之記也',
'newuserlog-byemail' => '號發自電郵',
'newuserlog-create-entry' => '新簿',
'newuserlog-create2-entry' => '已註$1之簿',
'newuserlog-autocreate-entry' => '已自註之簿',
# Special:ListGroupRights
'listgrouprights' => '權任一覽',
'listgrouprights-summary' => '此所列述,諸職所司也,各有異同。欲知其詳,請閱[[{{MediaWiki:Listgrouprights-helppage}}|此文]]。',
'listgrouprights-group' => '組',
'listgrouprights-rights' => '權',
'listgrouprights-helppage' => 'Help:組權',
'listgrouprights-members' => '(社員表)',
'listgrouprights-addgroup' => '加{{PLURAL:$2|一|多}}組:$1',
'listgrouprights-removegroup' => '除{{PLURAL:$2|一|多}}組:$1',
'listgrouprights-addgroup-all' => '加全組',
'listgrouprights-removegroup-all' => '除全組',
# E-mail user
'mailnologin' => '無驛',
'mailnologintext' => '[[Special:UserLogin|登簿]]置郵,方可捎書。',
'emailuser' => '捎君',
'emailpage' => '捎書',
'emailpagetext' => '表下捎焉,以郵制君。
署[[Special:Preferences|子簿郵]]以候往返。',
'usermailererror' => '驛報有誤:',
'defemailsubject' => '{{SITENAME}}來書',
'noemailtitle' => '無郵',
'noemailtext' => '此君無郵。',
'nowikiemailtitle' => '無許之郵',
'nowikiemailtext' => '此君謝收郵之。',
'email-legend' => '發郵至{{SITENAME}}之另一簿',
'emailfrom' => '自:',
'emailto' => '致:',
'emailsubject' => '題:',
'emailmessage' => '訊:',
'emailsend' => '遣',
'emailccme' => '謄複本。',
'emailccsubject' => '致$1複本:$2',
'emailsent' => '書遣矣',
'emailsenttext' => '書遣矣',
'emailuserfooter' => '此捎由$1給$2經{{SITENAME}}之「捎君」發矣。',
# Watchlist
'watchlist' => '哨站',
'mywatchlist' => '哨站',
'watchlistfor' => "('''$1'''之哨)",
'nowatchlist' => '無哨',
'watchlistanontext' => '$1以治哨',
'watchnologin' => '未登簿',
'watchnologintext' => '[[Special:UserLogin|登簿]]以治哨。',
'addedwatch' => '派哨',
'addedwatchtext' => "\"[[:\$1]]\"哨派矣。後有易、議者可見於[[Special:Watchlist|哨站]],且'''粗體'''列於[[Special:RecentChanges|近易]]。",
'removedwatch' => '撤哨',
'removedwatchtext' => '"[[:$1]]"[[Special:Watchlist|哨]]撤矣。',
'watch' => '派哨',
'watchthispage' => '哨此報',
'unwatch' => '撤哨',
'unwatchthispage' => '撤此哨',
'notanarticle' => '此頁非文',
'notvisiblerev' => '易已刪矣',
'watchnochange' => '皆無易也',
'watchlist-details' => '哨上有$1,不含議論。',
'wlheader-enotif' => '*准報信。',
'wlheader-showupdated' => "*易者'''粗體'''。",
'watchmethod-recent' => '哨近易。',
'watchmethod-list' => '報近易…',
'watchlistcontains' => '共$1哨。',
'iteminvalidname' => "'$1'謬名。",
'wlnote' => '近<b>$2</b>時有$1者易。',
'wlshowlast' => '見近$1時、$2天、$3時易',
'watchlist-options' => '哨項',
# Displayed when you click the "watch" button and it is in the process of watching
'watching' => '出陣…',
'unwatching' => '收兵…',
'enotif_mailer' => '{{SITENAME}}報',
'enotif_reset' => '令為盡閱',
'enotif_newpagetext' => '新灶',
'enotif_impersonal_salutation' => '貴客',
'changed' => '易',
'created' => '撰',
'enotif_subject' => '{{SITENAME}}簿{$PAGEEDITOR}{$CHANGEDORCREATED}{$PAGETITLE}',
'enotif_lastvisited' => '自子出簿,有易見$1。',
'enotif_lastdiff' => '欲閱此易,見$1。',
'enotif_anon_editor' => '過客$1',
'enotif_body' => '$WATCHINGUSERNAME鈞鑑
{$PAGEEDITDATE}{{SITENAME}}簿{$PAGEEDITOR}{$CHANGEDORCREATED}{$PAGETITLE},閱審之見{$PAGETITLE_URL}。
$NEWPAGE
纂者彙:$PAGESUMMARY $PAGEMINOREDIT
遣書($PAGEEDITOR_EMAIL)或訪齋($PAGEEDITOR_WIKI)聯繫之。
如不訪頁,哨報止也。可赴哨所令復之。
{{SITENAME}}敬上
--
欲更哨令,惠訪{{fullurl:{{ns:special}}:Watchlist/edit}}
饋助之,惠訪{{fullurl:{{ns:help}}:Contents}}',
# Delete
'deletepage' => '刪頁',
'confirm' => '准',
'excontent' => "文乃'$1'",
'excontentauthor' => "文乃'$1',乃[[Special:Contributions/$2|$2]]獨作。",
'exblank' => '缺頁',
'delete-confirm' => '刪"$1"',
'delete-legend' => '刪',
'historywarning' => '警示,此頁有誌:',
'confirmdeletetext' => '欲刪此物與誌,知後果、合[[{{MediaWiki:Policy-url}}]]後再為之。',
'actioncomplete' => '成矣',
'deletedtext' => '"<nowiki>$1</nowiki>"刪矣,見誌刪於$2。',
'deletedarticle' => '刪焉「[[$1]]」',
'suppressedarticle' => '廢焉「[[$1]]」',
'dellogpage' => '誌刪',
'dellogpagetext' => '近刪如下:',
'deletionlog' => '誌刪',
'reverted' => '已還前審',
'deletecomment' => '刪因:',
'deleteotherreason' => '另/附之因:',
'deletereasonotherlist' => '另因',
'deletereason-dropdown' => '
*常刪之因
** 作者之求
** 侵版權
** 破壞',
'delete-edit-reasonlist' => '纂刪因',
'delete-toobig' => '此頁含大誌,過$1修。刪頁限矣,防於{{SITENAME}}之亂也。',
'delete-warning-toobig' => '此頁含大誌,過$1修。刪之可亂{{SITENAME}}之事也;續時留神之。',
# Rollback
'rollback' => '反正',
'rollback_short' => '正',
'rollbacklink' => '正',
'rollbackfailed' => '未能反正',
'cantrollback' => '獨一作者,無以反正。',
'alreadyrolled' => '[[User:$2|$2]]([[User talk:$2|議]] | [[Special:Contributions/$2|{{int:contribslink}}]])作[[:$1]],退不成也。有易或已退焉。新纂者為[[User:$3|$3]]([[User talk:$3|議]] | [[Special:Contributions/$3|{{int:contribslink}}]])',
'editcomment' => "贊曰\"''\$1''\"", # only shown if there is an edit comment
'revertpage' => '去[[Special:Contributions/$2|$2]]之作(欲言之,可至[[User talk:$2|此]])為[[User:$1|$1]]之本耳', # Additionally available: $3: revid of the revision reverted to, $4: timestamp of the revision reverted to, $5: revid of the revision reverted from, $6: timestamp of the revision reverted from
'rollback-success' => '去$1之作,復為$2之本耳。',
'sessionfailure' => '登簿有變。為防盜簿,返前重取再為之。',
# Protect
'protectlogpage' => '誌緘',
'protectlogtext' => '誌緘如下;近緘見[[Special:ProtectedPages|此]] 。',
'protectedarticle' => '緘焉"[[$1]]"',
'modifiedarticleprotection' => '令"$1"',
'unprotectedarticle' => '啟焉"[[$1]]"',
'movedarticleprotection' => '自「[[$2]]」至「[[$1]]」之錮改矣',
'protect-title' => '更"$1"之緘',
'prot_1movedto2' => '[[$1]]遷至[[$2]]',
'protect-legend' => '准緘',
'protectcomment' => '贊曰',
'protectexpiry' => '屆期',
'protect_expiry_invalid' => '屆期不明。',
'protect_expiry_old' => '屆期已過。',
'protect-unchain' => '准遷之',
'protect-text' => "緘捆'''<nowiki>$1</nowiki>'''。",
'protect-locked-blocked' => "簿禁,'''$1'''緘昔如下:",
'protect-locked-dblock' => "庫鎖,'''$1'''緘昔如下:",
'protect-locked-access' => "未准,'''$1'''緘昔如下:",
'protect-cascadeon' => '取佐緘焉,迭牽此頁;{{PLURAL:$1|此|此}}頁啟篋,無反累焉。',
'protect-default' => '(慣)',
'protect-fallback' => "須''$1''准",
'protect-level-autoconfirmed' => '禁無簿',
'protect-level-sysop' => '惟有秩',
'protect-summary-cascade' => '迭緘',
'protect-expiring' => '$1(UTC)屆',
'protect-expiry-indefinite' => '無屆',
'protect-cascade' => '援引緘,牽迭',
'protect-cantedit' => '汝無動頁之護也,因汝無權纂之矣。',
'protect-othertime' => '它時:',
'protect-othertime-op' => '它時',
'protect-existing-expiry' => '現屆時:$2 $3',
'protect-otherreason' => '它/附之理:',
'protect-otherreason-op' => '它/附之理',
'protect-dropdown' => '*通錮之理
** 多破
** 多灌
** 反產之戰纂
** 高量之頁',
'protect-edit-reasonlist' => '纂護之理',
'protect-expiry-options' => '半時:1 hour,一日:1 day,一週:1 week,兩週:2 weeks,一月:1 month,三月:3 months,六月:6 months,一年:1 year,永久:infinite', # display1:time1,display2:time2,...
'restriction-type' => '准',
'restriction-level' => '緘捆',
'minimum-size' => '幅越',
'maximum-size' => '幅弱:',
'pagesize' => '(位元組)',
# Restrictions (nouns)
'restriction-edit' => '纂',
'restriction-move' => '遷',
'restriction-create' => '建',
'restriction-upload' => '貢',
# Restriction levels
'restriction-level-sysop' => '全封',
'restriction-level-autoconfirmed' => '半封',
'restriction-level-all' => '有封',
# Undelete
'undelete' => '覽刪',
'undeletepage' => '覽刪並還之',
'undeletepagetitle' => "'''如下含[[:$1]]刪之審'''。",
'viewdeletedpage' => '覽刪',
'undeletepagetext' => '如下之$1頁已刪,備謄以還;曆滿乃清之。',
'undelete-fieldset-title' => '復審',
'undeleteextrahelp' => "欲還題,撤核後令'''''還刪'''''。
欲還某審,核之再令。
欲清核、贊,令之'''''歸白'''''。",
'undeleterevisions' => '審備$1',
'undeletehistory' => '如還題,審亦隨焉;若存同題,還如誌,不以代焉。',
'undeleterevdel' => '新審不牽,難還也;銷、見之以篤還。',
'undeletehistorynoadmin' => '文刪矣,何由如下;並示末纂者。詳文藏,惟有迭可閱。',
'undelete-revision' => '自$4$5,$3纂之$1審刪如下:',
'undeleterevision-missing' => '審謬失;棄、還或鏈亡。',
'undeletebtn' => '還',
'undeletelink' => '察焉,以定還否',
'undeletereset' => '歸白',
'undeleteinvert' => '反相',
'undeletecomment' => '贊日',
'undeletedarticle' => '還焉"[[$1]]"',
'undeletedrevisions' => '$1審已還',
'undeletedrevisions-files' => '$1審、$2檔已還',
'undeletedfiles' => '$1檔已還',
'cannotundelete' => '無以還檔;或復矣。',
'undeletedpage' => "<big>'''$1還矣'''</big>
近刪新還,見[[Special:Log/delete|刪還誌]]。",
'undelete-header' => '欲覽近刪,見[[Special:Log/delete|誌刪]]。',
'undelete-search-box' => '尋刪',
'undelete-search-prefix' => '見頁始如',
'undelete-search-submit' => '尋',
'undelete-no-results' => '備本無合者也。',
'undelete-filename-mismatch' => '$1之審名不合,無可還焉。',
'undelete-bad-store-key' => '$1之審乃空,無可還焉。',
'undelete-cleanup-error' => '冗檔$1,欲刪而有誤也。',
'undelete-missing-filearchive' => '$1無尋,或已還矣。',
'undelete-error-short' => '$1欲還而有誤也。',
'undelete-error-long' => '還檔有誤。欲還者:
$1',
'undelete-show-file-confirm' => '汝乃確視於 $2 $3 之「<nowiki>$1</nowiki>」的已刪之審嗎?',
'undelete-show-file-submit' => '是',
# Namespace form on various pages
'namespace' => '名冊:',
'invert' => '反相',
'blanknamespace' => '主',
# Contributions
'contributions' => '功績',
'contributions-title' => '$1之功績',
'mycontris' => '吾績',
'contribsub2' => '$1勛($2)',
'nocontribs' => '無勛及也。', # Optional parameter: $1 is the user name
'uctop' => '(至頂)',
'month' => '且不越',
'year' => '年不越',
'sp-contributions-newbies' => '惟列新進',
'sp-contributions-newbies-sub' => '予新進',
'sp-contributions-newbies-title' => '新進之功績',
'sp-contributions-blocklog' => '誌禁',
'sp-contributions-logs' => '誌',
'sp-contributions-search' => '問勛',
'sp-contributions-username' => '簿名或IP址',
'sp-contributions-submit' => '問',
# What links here
'whatlinkshere' => '取佐',
'whatlinkshere-title' => '「$1」取佐',
'whatlinkshere-page' => '題',
'linkshere' => "取佐'''[[:$1]]'''如下:",
'nolinkshere' => "無頁取佐'''[[:$1]]'''。",
'nolinkshere-ns' => "名冊內無頁取佐'''[[:$1]]'''。",
'isredirect' => '渡',
'istemplate' => '含',
'isimage' => '檔佐',
'whatlinkshere-prev' => '前$1',
'whatlinkshere-next' => '次$1',
'whatlinkshere-links' => '←佐',
'whatlinkshere-hideredirs' => '$1轉',
'whatlinkshere-hidetrans' => '$1含',
'whatlinkshere-hidelinks' => '$1佐',
'whatlinkshere-hideimages' => '$1檔佐',
'whatlinkshere-filters' => '濾',
# Block/unblock
'blockip' => '禁簿',
'blockip-legend' => '禁簿',
'blockiptext' => '函下禁纂,簿、址明判;[[{{MediaWiki:Policy-url}}|秉據]]如斯,立法克亂。指罪證行,了冤無憾。',
'ipaddress' => 'IP址',
'ipadressorusername' => 'IP或簿名',
'ipbexpiry' => '限期',
'ipbreason' => '指證',
'ipbreasonotherlist' => '常犯',
'ipbreason-dropdown' => '
*如下道:
** 造假報
** 毀文貌
** 廣賈告
** 話胡鬧
** 恐嚇擾
** 污名號
** 名瀆道',
'ipbanononly' => '惟禁匿',
'ipbcreateaccount' => '禁增簿',
'ipbemailban' => '禁郵捎',
'ipbenableautoblock' => '屢禁此簿,新IP址、後繼亦如也。',
'ipbsubmit' => '禁簿',
'ipbother' => '別期',
'ipboptions' => '二時:2 hours,一日:1 day,三日:3 days,一週:1 week,二週:2 weeks,一月:1 month,三月:3 months,六月:6 months,一年:1 year,永如:infinite', # display1:time1,display2:time2,...
'ipbotheroption' => '它',
'ipbotherreason' => '補證、加證曰',
'ipbhidename' => '簿名隱乎纂與表',
'ipbwatchuser' => '哨該簿之齋與議',
'ipballowusertalk' => '禁時許其簿纂己之議',
'ipb-change-block' => '用此設重禁此簿',
'badipaddress' => 'IP不格',
'blockipsuccesssub' => '禁焉',
'blockipsuccesstext' => '[[Special:Contributions/$1|$1]]禁焉。表禁<br />見[[Special:IPBlockList|此]]。',
'ipb-edit-dropdown' => '改證',
'ipb-unblock-addr' => '赦$1',
'ipb-unblock' => '赦簿、址',
'ipb-blocklist-addr' => '$1之禁',
'ipb-blocklist' => '列禁',
'ipb-blocklist-contribs' => '$1勛績',
'unblockip' => '赦簿',
'unblockiptext' => '函下赦禁。',
'ipusubmit' => '赦此址',
'unblocked' => '[[User:$1|$1]]赦焉',
'unblocked-id' => '禁$1赦焉',
'ipblocklist' => '列禁簿、禁址',
'ipblocklist-legend' => '尋禁簿',
'ipblocklist-username' => '簿名、IP址:',
'ipblocklist-sh-userblocks' => '$1次禁簿',
'ipblocklist-sh-tempblocks' => '$1次臨禁',
'ipblocklist-sh-addressblocks' => '$1次禁單IP',
'ipblocklist-submit' => '尋',
'blocklistline' => '$1,$2禁$3($4)',
'infiniteblock' => '永如',
'expiringblock' => '屆$1',
'anononlyblock' => '惟匿者',
'noautoblockblock' => '止自禁',
'createaccountblock' => '禁增簿',
'emailblock' => '郵禁焉',
'blocklist-nousertalk' => '禁其議',
'ipblocklist-empty' => '無禁。',
'ipblocklist-no-results' => '簿名、IP址未禁焉。',
'blocklink' => '禁',
'unblocklink' => '赦',
'change-blocklink' => '更',
'contribslink' => '勛',
'autoblocker' => '近日$1"$2";同子IP址,故禁焉。',
'blocklogpage' => '誌禁',
'blocklog-fulllog' => '整誌禁',
'blocklogentry' => '禁[[$1]]屆$2$3',
'reblock-logentry' => '改[[$1]]之禁,屆$2$3',
'blocklogtext' => '此誌禁赦;自禁不示。見[[Special:IPBlockList|此]]列今禁者。',
'unblocklogentry' => '$1赦焉',
'block-log-flags-anononly' => '惟禁匿',
'block-log-flags-nocreate' => '禁增簿',
'block-log-flags-noautoblock' => '止自禁',
'block-log-flags-noemail' => '郵禁焉',
'block-log-flags-nousertalk' => '禁己議',
'block-log-flags-angry-autoblock' => '強自封用也',
'block-log-flags-hiddenname' => '藏簿名',
'range_block_disabled' => '未准有秩圍禁。',
'ipb_expiry_invalid' => '屆期不明。',
'ipb_expiry_temp' => '藏簿禁封必為長久也。',
'ipb_hide_invalid' => '無壓簿以多纂之故。',
'ipb_already_blocked' => '"$1"早禁矣',
'ipb-needreblock' => '== 已禁 ==
$1已被禁矣。爾是否改此置?',
'ipb_cant_unblock' => '有誤:禁$1無尋;或早赦矣。',
'ipb_blocked_as_range' => '錯:該IP $1 無直禁也,無赦之。唯它在 $2 之範禁內,其範可赦之。',
'ip_range_invalid' => 'IP址圍不格',
'blockme' => '自禁',
'proxyblocker' => '禁Proxy',
'proxyblocksuccess' => '成矣。',
'cant-block-while-blocked' => '爾然被禁,勿施於人。',
# Developer tools
'lockdb' => '閉庫',
'unlockdb' => '開庫',
'lockdbtext' => '夫閉庫者,止撰編、凍簿註、休令哨、謝問庫也。篤欲行,事畢開之。',
'unlockdbtext' => '夫開庫者,迎撰編、任註簿、喜令哨、隨問庫也;慎篤之。',
'lockconfirm' => '篤閉之。',
'unlockconfirm' => '篤開之。',
'lockbtn' => '閉庫',
'unlockbtn' => '開庫',
'locknoconfirm' => '未篤焉。',
'lockdbsuccesssub' => '庫已閉',
'unlockdbsuccesssub' => '庫已開',
'lockdbsuccesstext' => '庫閉矣。<br />檢畢切[[Special:UnlockDB|開之]]。',
'unlockdbsuccesstext' => '庫開矣',
'lockfilenotwritable' => '未准更鎖庫檔。欲開閉之,網頁伺服須得更也。',
'databasenotlocked' => '庫未閉焉。',
# Move page
'move-page' => '遷$1',
'move-page-legend' => '遷頁',
'movepagetext' => "函下遷頁,誌隨新往、舊題作渡、取佐欲移。保佐正,[[Special:DoubleRedirects|防窮]]、[[Special:BrokenRedirects|斷渡]]。
囑之者,新題若非空、渡、缺誌,則舊'''不遷'''焉。存頁勿覆,而誤遷可悔也。
<b>警示</b>
膾炙遷焉,禍生不測;戒慎行之。",
'movearticle' => '遷文:',
'movenologin' => '未登簿',
'movenologintext' => '遷文須[[Special:UserLogin|登簿]]。',
'movenotallowed' => '無准遷檔也。',
'cant-move-user-page' => '無動自齋(除字頁)。',
'cant-move-to-user-page' => '無動至齋(除字頁)。',
'newtitle' => '至新題:',
'move-watch' => '派哨',
'movepagebtn' => '遷文',
'pagemovedsub' => '遷成矣',
'movepage-moved' => "<big>'''「$1」已遷至「$2」'''</big>", # The two titles are passed in plain text as $3 and $4 to allow additional goodies in the message.
'movepage-moved-redirect' => '一渡已建。',
'movepage-moved-noredirect' => '建渡已押。',
'articleexists' => '此題早存,或名謬焉;請更之。',
'cantmove-titleprotected' => '爾不可動頁至此,因新題已緘焉,防建之。',
'talkexists' => "'''文遷成而議未移,蓋早存也;請併之。'''",
'movedto' => '遷至',
'movetalk' => '議並遷',
'move-subpages' => '遷議(上至$1)',
'move-talk-subpages' => '遷子議(上至$1)',
'movepage-page-exists' => '頁$1已存矣,非自覆也。',
'movepage-page-moved' => '頁$1遷$2矣。',
'movepage-page-unmoved' => '頁$1遷$2不成。',
'movepage-max-pages' => '上之$1頁遷矣同非自遷之下。',
'1movedto2' => '[[$1]]遷至[[$2]]',
'1movedto2_redir' => '[[$1]]遷至[[$2]]為渡',
'move-redirect-suppressed' => '渡押',
'movelogpage' => '誌遷',
'movelogpagetext' => '頁遷如下:',
'movereason' => '因',
'revertmove' => '還',
'delete_and_move' => '刪遷',
'delete_and_move_text' => '==准刪==
往遷"[[:$1]]"存,刪之以替乎?',
'delete_and_move_confirm' => '刪之',
'delete_and_move_reason' => '為遷而刪之',
'selfmove' => '鄉遷同源,如未移也。',
'immobile-source-namespace' => '名集「$1」上無動',
'immobile-target-namespace' => '無移至「$1」中',
'immobile-target-namespace-iw' => '無移至垮維基,此乃無效也。',
'immobile-source-page' => '此頁無動也。',
'immobile-target-page' => '無動至標之標題。',
'imagenocrossnamespace' => '非勳檔至非檔名間',
'imagetypemismatch' => '其新副檔名非配其類也',
'imageinvalidfilename' => '標之檔名乃無效也',
'fix-double-redirects' => '更指原題之任渡',
'move-leave-redirect' => '留渡',
# Export
'export' => '出匯',
'exporttext' => '文、誌纂、擇頁可編成XML,借MediaWiki[[Special:Import|入匯]他山]。欲出匯,函下題之,每列一題,任牽舊審、誌文;或獨帶末纂之述,以鏈表之,如以[[{{#Special:Export}}/{{MediaWiki:Mainpage}}]]匯"[[{{MediaWiki:Mainpage}}]]"。',
'exportcuronly' => '獨匯今審',
'exportnohistory' => "----
'''囑記,'''封匯全誌,因累甚也。",
'export-submit' => '出匯',
'export-addcattext' => '索門擇題:',
'export-addcat' => '增',
'export-addnstext' => '索名集擇題:',
'export-addns' => '增',
'export-download' => '備檔以載',
'export-templates' => '含模',
# Namespace 8 related
'allmessages' => '官話',
'allmessagesname' => '話',
'allmessagesdefault' => '慣文',
'allmessagescurrent' => '今文',
'allmessagestext' => '此列MediaWiki官話。
如貢正宗MediaWiki本地化,[http://www.mediawiki.org/wiki/Localisation MediaWiki本地化]與[http://translatewiki.net translatewiki.net]閱之。',
'allmessagesnotsupportedDB' => "'''\$wgUseDatabaseMessages'''閉庫,'''無纂也。",
'allmessagesfilter' => '含辭:',
'allmessagesmodified' => '見易',
# Thumbnails
'thumbnail-more' => '展',
'filemissing' => '喪檔',
'thumbnail_error' => '縮圖$1有誤',
'thumbnail_invalid_params' => '縮圖參數不合',
'thumbnail_dest_directory' => '縮圖匣未可造',
# Special:Import
'import' => '圖入匯',
'importinterwiki' => '維基互匯',
'import-interwiki-text' => '欲入匯,擇維基、揀題文,審時、纂者隨記也。互匯錄於[[Special:Log/import|誌入]]。',
'import-interwiki-source' => '來源wiki/頁:',
'import-interwiki-history' => '審、誌同匯',
'import-interwiki-submit' => '入匯',
'import-interwiki-namespace' => '入名集:',
'import-upload-filename' => '檔名:',
'import-comment' => '註:',
'importtext' => '請[[Special:Export|出匯]]儲之。
再入匯於此。',
'importstart' => '入匯…',
'import-revision-count' => '有審$1',
'importnopages' => '無可匯。',
'importfailed' => '入匯有變:<nowiki>$1</nowiki>',
'importunknownsource' => '入類不明',
'importcantopen' => '入未可啟',
'importbadinterwiki' => '維基內鏈壞',
'importnotext' => '空檔或無文',
'importsuccess' => '入匯成矣!',
'importhistoryconflict' => '舊審沖,疑早存焉',
'importnosources' => '互匯而未定入源,審、誌不予直進。',
'importnofile' => '無匯入也。',
'importuploaderrorsize' => '檔未入匯。幅越焉。',
'importuploaderrorpartial' => '檔未入匯。檔部傳。',
'importuploaderrortemp' => '檔未入匯。臨夾已失。',
'import-parse-failure' => 'XML入匯語法敗矣',
'import-noarticle' => '無頁入匯也!',
'import-nonewrevisions' => '全審已入匯也。',
'xml-error-string' => '$1 於行$2,欄$3 ($4字節): $5',
'import-upload' => '貢XML',
'import-token-mismatch' => '節遺。再嘗之。',
'import-invalid-interwiki' => '無乃定之wiki匯入。',
# Import log
'importlogpage' => '誌入',
'importlogpagetext' => '秩入匯自他山之審。',
'import-logentry-upload' => '[[$1]]上傳而匯',
'import-logentry-upload-detail' => '有審$1',
'import-logentry-interwiki' => '互匯$1',
'import-logentry-interwiki-detail' => '$1審自$2',
# Tooltip help for the actions
'tooltip-pt-userpage' => '述平生、紹身家、銘字號',
'tooltip-pt-anonuserpage' => '君IP之舍',
'tooltip-pt-mytalk' => '與眾論、往魚雁、湧文滔',
'tooltip-pt-anontalk' => '此IP所修之議',
'tooltip-pt-preferences' => '更符驛、排版式、投所好',
'tooltip-pt-watchlist' => '收矚目、治眼線、賞萌茂',
'tooltip-pt-mycontris' => '刻勛功、追作續、慰苦勞',
'tooltip-pt-login' => '設書齋、錄功績、廣放哨',
'tooltip-pt-anonlogin' => '設書齋、錄功績、廣放哨',
'tooltip-pt-logout' => '凡事盡,乘雲飄',
'tooltip-ca-talk' => '求異見、辯是非、妥紛擾',
'tooltip-ca-edit' => '拓文意、校誤謬、潤辭藻',
'tooltip-ca-addsection' => '有言議,添新要',
'tooltip-ca-viewsource' => '文函緘,讀源老',
'tooltip-ca-history' => '誌流衍、備謄本、修惡盜',
'tooltip-ca-protect' => '謝撰纂,奏原調',
'tooltip-ca-delete' => '撕書頁,棄於奧',
'tooltip-ca-undelete' => '悔刪斷,奉回轎',
'tooltip-ca-move' => '安居所,嚮正道',
'tooltip-ca-watch' => '哨此報',
'tooltip-ca-unwatch' => '撤此哨',
'tooltip-search' => '索大典,籲自曉',
'tooltip-search-go' => '確合契,躍步到',
'tooltip-search-fulltext' => '尋通篇,列倣傚',
'tooltip-p-logo' => '返卷首,訪露朝',
'tooltip-n-mainpage' => '返卷首,訪露朝',
'tooltip-n-portal' => '識百科、習施行、熟矩教',
'tooltip-n-currentevents' => '知天下、順潮流、察脈絡',
'tooltip-n-recentchanges' => '閱新易、聞脈搏、觀熱鬧',
'tooltip-n-randompage' => '嚐鮮味,隨遊遨',
'tooltip-n-help' => '解疑惑、點明燈、掛病號',
'tooltip-t-whatlinkshere' => '何美餚,佐此料',
'tooltip-t-recentchangeslinked' => '足義友,借鏡照',
'tooltip-feed-rss' => '本卷之RSS源',
'tooltip-feed-atom' => '本卷之Atom源',
'tooltip-t-contributions' => '同肩戰,苦功高',
'tooltip-t-emailuser' => '言未猶,書信捎',
'tooltip-t-upload' => '貢彩件、獻樂謠',
'tooltip-t-specialpages' => '奇怪求,特查找',
'tooltip-t-print' => '備印墨,整版貌',
'tooltip-t-permalink' => '鏈緊焊,橋吊牢',
'tooltip-ca-nstab-main' => '閱文稿',
'tooltip-ca-nstab-user' => '返齋寮',
'tooltip-ca-nstab-media' => '聽媒紹',
'tooltip-ca-nstab-special' => '特查報,謝纂校',
'tooltip-ca-nstab-project' => '探爐灶',
'tooltip-ca-nstab-image' => '觀揮毫',
'tooltip-ca-nstab-mediawiki' => '聞官耗',
'tooltip-ca-nstab-template' => '尋模造',
'tooltip-ca-nstab-help' => '助拳腳',
'tooltip-ca-nstab-category' => '入門道',
'tooltip-minoredit' => '正小錯,謙註校',
'tooltip-save' => '葺修畢,儲之窖',
'tooltip-preview' => '篤存儲,先草稿',
'tooltip-diff' => '留筆過,觀入刀',
'tooltip-compareselectedversions' => '揀二審,辨毀造',
'tooltip-watch' => '哨此報',
'tooltip-recreate' => '昔棄鄙,重起灶',
'tooltip-upload' => '獻品備,伐步跑',
'tooltip-rollback' => '『返』乃反之上貢也。',
'tooltip-undo' => '『復』乃開表加因也。',
# Stylesheets
'common.css' => '/* 此之 CSS 用於全面也 */',
'standard.css' => '/* 此之 CSS 用於經典面之簿也 */',
'nostalgia.css' => '/* 此之 CSS 用於懷古面之簿也 */',
'cologneblue.css' => '/* 此之 CSS 用於馨藍面之簿也 */',
'monobook.css' => '/* 此之 CSS 用於單書面之簿也 */',
'myskin.css' => '/* 此之 CSS 用於吾風面之簿也 */',
'chick.css' => '/* 此之 CSS 用於窈窕面之簿也 */',
'simple.css' => '/* 此之 CSS 用於簡明面之簿也 */',
'modern.css' => '/* 此之 CSS 用於時髦面之簿也 */',
'print.css' => '/* 此之 CSS 用於印之出力也 */',
'handheld.css' => '/* 此之 CSS 用於 $wgHandheldStyle 之手置面也 */',
# Scripts
'common.js' => '/* 此之JavaScript將載於全簿之頁。 */',
'standard.js' => '/* 此之JavaScript將載於用經典面之簿 */',
'nostalgia.js' => '/* 此之JavaScript將載於用懷古面之簿 */',
'cologneblue.js' => '/* 此之JavaScript將載於用馨藍面之簿 */',
'monobook.js' => '/* 此之JavaScript將載於用單書面之簿 */',
'myskin.js' => '/* 此之JavaScript將載於用吾風面之簿 */',
'chick.js' => '/* 此之JavaScript將載於用窈窕面之簿 */',
'simple.js' => '/* 此之JavaScript將載於用簡明面之簿 */',
'modern.js' => '/* 此之JavaScript將載於用時髦面之簿 */',
# Attribution
'anonymous' => '{{SITENAME}}無{{PLURAL:$1|簿|簿}}者',
'siteuser' => '{{SITENAME}}有簿者$1',
'lastmodifiedatby' => '$1$2,$3新易此頁。', # $1 date, $2 time, $3 user
'othercontribs' => '$1主撰',
'others' => '他',
'siteusers' => '{{SITENAME}}有{{PLURAL:$2|簿|簿}}者$1',
'creditspage' => '頁贊',
'nocredits' => '本頁未有贊信也。',
# Spam protection
'spamprotectiontitle' => '防賈濫',
'spamprotectiontext' => '外鏈疑賈。
存頁止焉。',
'spamprotectionmatch' => '憑如下:$1',
'spambot_username' => 'MediaWiki清濫',
'spam_reverting' => '還新審之無鏈$1者。',
'spam_blanking' => '審皆鏈$1,遂令白頁。',
# Info page
'infosubtitle' => '頁註',
'numedits' => '有纂$1',
'numtalkedits' => '有議$1',
'numwatchers' => '有哨$1',
'numauthors' => '編者$1',
'numtalkauthors' => '議者$1',
# Skin names
'skinname-standard' => '經典',
'skinname-nostalgia' => '懷古',
'skinname-cologneblue' => '馨藍',
'skinname-monobook' => '單書',
'skinname-myskin' => '吾風',
'skinname-chick' => '窈窕',
'skinname-simple' => '簡明',
'skinname-modern' => '時髦',
# Math options
'mw_math_png' => '屢作PNG',
'mw_math_simple' => '易為則作HTML,否則PNG',
'mw_math_html' => '堪為則作HTML,否則PNG',
'mw_math_source' => 'TeX依舊,純文覽器適也。',
'mw_math_modern' => '今之覽器此薦。',
'mw_math_mathml' => '實驗者,堪為則作MathML。',
# Patrolling
'markaspatrolleddiff' => '派哨',
'markaspatrolledtext' => '哨此報',
'markedaspatrolled' => '派哨',
'markedaspatrolledtext' => '此審哨矣。',
'rcpatroldisabled' => '不哨近易',
'rcpatroldisabledtext' => '近易之哨,未准行也。',
'markedaspatrollederror' => '哨有誤',
'markedaspatrollederrortext' => '揀一以哨。',
'markedaspatrollederror-noautopatrol' => '己易不可哨。',
# Patrol log
'patrol-log-page' => '誌哨',
'patrol-log-header' => '此乃誌哨也。',
'patrol-log-line' => '令哨$2之$1$3',
'patrol-log-auto' => '(自行)',
'log-show-hide-patrol' => '$1誌巡',
# Image deletion
'deletedrevision' => '刪舊審$1',
'filedeleteerror-short' => '刪檔有誤:$1',
'filedeleteerror-long' => '刪檔有誤:\\n\\n$1\\n',
'filedelete-missing' => '"$1"不存,無可刪也。',
'filedelete-old-unregistered' => '庫無舊審"$1"。',
'filedelete-current-unregistered' => '庫無"$1"也。',
'filedelete-archive-read-only' => '"$1"存匣,未准更之。',
# Browsing diffs
'previousdiff' => '←前辨',
'nextdiff' => '後辨→',
# Visual comparison
'visual-comparison' => '較見',
# Media information
'mediawarning' => "'''警'''日:此檔疑惡,行之恐諜也。<hr />",
'imagemaxsize' => '述檔頁惟列:',
'thumbsize' => '縮圖幅',
'widthheight' => '$1矩$2',
'widthheightpage' => '$1矩$2,共$3頁',
'file-info' => '(大小:$1,MIME類型:$2)',
'file-info-size' => '(像素$1矩$2,大小:$3,MIME類型:$4)',
'file-nohires' => '<small>無以更晰。</small>',
'svg-long-desc' => '(SVG檔,貌有像素$1矩$2,幅$3)',
'show-big-image' => '全幅',
'show-big-image-thumb' => '<small>縮圖幅有像素$1矩$2</small>',
# Special:NewFiles
'newimages' => '新圖之廊',
'imagelisttext' => "下表乃按$2排之的'''$1'''檔。",
'newimages-summary' => '此奇頁示最後呈上之檔也。',
'newimages-legend' => '濾',
'newimages-label' => '名(或其部):',
'showhidebots' => '($1僕)',
'noimages' => '無可見。',
'ilsubmit' => '尋檔',
'bydate' => '時序',
'sp-newimages-showfrom' => '自$1 $2賞新檔',
# Video information, used by Language::formatTimePeriod() to format lengths in the above messages
'video-dims' => '$1,$2矩$3',
# Bad image list
'bad_image_list' => '僅取表件,冠「*」者也。格式如下:
單列數鏈,首通壞檔;而後所鏈之文,允圖見於其內。',
# Metadata
'metadata' => '補註',
'metadata-help' => '此檔補註,製者所添,如相機、掃描之器;後若更檔,補註不誠也。',
'metadata-expand' => '見詳',
'metadata-collapse' => '藏詳',
'metadata-fields' => '若藏詳,此下EXIF補註方現,否則藏焉。
* make
* model
* datetimeoriginal
* exposuretime
* fnumber
* isospeedratings
* focallength', # Do not translate list items
# EXIF tags
'exif-imagewidth' => '寬',
'exif-imagelength' => '長',
'exif-photometricinterpretation' => '像素構成',
'exif-datetime' => '文檔修訂之日期時辰',
'exif-make' => '出廠',
'exif-model' => '型號',
'exif-artist' => '作者',
'exif-exifversion' => 'Exif版本',
'exif-datetimeoriginal' => '數據生成之日期時辰',
'exif-datetimedigitized' => '數位化之日期時辰',
'exif-exposuretime' => '曝光',
'exif-exposuretime-format' => '$1 秒 ($2)',
'exif-fnumber' => '光圈',
'exif-aperturevalue' => '光圈',
'exif-brightnessvalue' => '光度',
'exif-flash' => '閃光燈',
'exif-focallength' => '焦距',
'exif-flashenergy' => '閃光燈能量',
'exif-contrast' => '對比',
'exif-saturation' => '飽和度',
'exif-sharpness' => '清晰度',
'exif-meteringmode-255' => '其他',
# Flash modes
'exif-flash-fired-0' => '閃無火',
'exif-flash-fired-1' => '閃開火',
'exif-flash-return-0' => '無閃測',
'exif-flash-return-2' => '閃無測光',
'exif-flash-return-3' => '閃測光',
'exif-flash-mode-1' => '強開閃',
'exif-flash-mode-2' => '強閉閃',
'exif-flash-mode-3' => '自模',
'exif-flash-function-1' => '無閃',
'exif-flash-redeye-1' => '紅退模',
'exif-focalplaneresolutionunit-2' => '吋',
'exif-gaincontrol-0' => '無',
# External editor support
'edit-externally' => '以外部程式修此文',
'edit-externally-help' => '(請閱[http://www.mediawiki.org/wiki/Manual:External_editors 安裝指引]以知詳情)',
# 'all' in various places, this might be different for inflected languages
'recentchangesall' => '全',
'imagelistall' => '全',
'watchlistall2' => '全',
'namespacesall' => '全',
'monthsall' => '全',
# E-mail address confirmation
'confirmemail' => '核郵驛',
'confirmemail_noemail' => '[[Special:Preferences|簿註]]有驛。',
'confirmemail_send' => '遣核符',
'confirmemail_sent' => '核符遣矣',
'confirmemail_sendfailed' => '{{SITENAME}}信未遣焉,請核郵驛。
郵者覆之:$1',
'confirmemail_invalidated' => '核郵驛消也',
'invalidateemail' => '消核郵驛',
# Scary transclusion
'scarytranscludedisabled' => '[蓋跨共筆之轉碼者,莫之能用也]',
'scarytranscludefailed' => '[$1模不得]',
'scarytranscludetoolong' => '[網址過長]',
# Trackbacks
'trackbackbox' => '此文之引:<br />
$1',
'trackbackremove' => '([$1刪])',
'trackbacklink' => '迴響',
'trackbackdeleteok' => 'Trackback 刪矣。',
# Delete conflict
'deletedwhileediting' => '警:纂中見刪。',
'confirmrecreate' => "[[User:$1|$1]]([[User talk:$1|議]])刪之有由:
''$2''
請爾審視之。",
'recreate' => '復',
# action=purge
'confirm_purge_button' => '准',
'confirm-purge-top' => '清謄本?',
'confirm-purge-bottom' => '清頁會清謄本以迫示近審。',
# Separators for various lists, etc.
'semicolon-separator' => ';',
'comma-separator' => '、',
'colon-separator' => ':',
'pipe-separator' => '|',
'word-separator' => '',
'ellipsis' => '……',
# Multipage image navigation
'imgmultipageprev' => '←前頁',
'imgmultipagenext' => '次頁→',
'imgmultigo' => '往',
'imgmultigoto' => '往頁$1',
# Table pager
'ascending_abbrev' => '升冪',
'descending_abbrev' => '降冪',
'table_pager_next' => '次頁',
'table_pager_prev' => '前頁',
'table_pager_first' => '首頁',
'table_pager_last' => '末頁',
'table_pager_limit' => '頁有物$1',
'table_pager_limit_submit' => '往',
'table_pager_empty' => '空',
# Auto-summaries
'autosumm-blank' => '盡除之',
'autosumm-replace' => "置為'$1'",
'autoredircomment' => '渡至[[$1]]',
'autosumm-new' => '新文:$1',
# Size units
'size-bytes' => '$1 位元組',
# Live preview
'livepreview-loading' => '遺藏…',
'livepreview-ready' => '藏至矣。',
'livepreview-failed' => '弗能即時示之!嘗以本法。',
'livepreview-error' => '莫之連也:$1 "$2" 嘗以本法。',
# Friendlier slave lag warnings
'lag-warn-normal' => '近$1秒新易者疑喪也。',
'lag-warn-high' => '遣藏遲焉。近$1秒新易者疑喪也。',
# Watchlist editor
'watchlistedit-numitems' => '不計議論,哨有題$1。',
'watchlistedit-noitems' => '哨無題也。',
'watchlistedit-normal-title' => '治哨站',
'watchlistedit-normal-legend' => '撤之',
'watchlistedit-normal-explain' => '盡列有哨。欲撤題,揀之再擊。亦[[Special:Watchlist/raw|治源哨]]也。',
'watchlistedit-normal-submit' => '撤題',
'watchlistedit-normal-done' => '$1題之哨已撤:',
'watchlistedit-raw-title' => '治源哨',
'watchlistedit-raw-legend' => '治源哨',
'watchlistedit-raw-explain' => '盡列有哨。治此表以加減題;一行一題之。善,擊更哨。亦[[Special:Watchlist/edit|標準治哨]]也。',
'watchlistedit-raw-titles' => '題:',
'watchlistedit-raw-submit' => '更哨',
'watchlistedit-raw-done' => '哨更矣。',
'watchlistedit-raw-added' => '已添$1題:',
'watchlistedit-raw-removed' => '已撤$1題:',
# Watchlist editing tools
'watchlisttools-view' => '察易',
'watchlisttools-edit' => '治哨站',
'watchlisttools-raw' => '治源哨',
# Core parser functions
'unknown_extension_tag' => '未明之擴標「$1」',
'duplicate-defaultsort' => '警:預之排鍵「$2」蓋前之排鍵「$1」。',
# Special:Version
'version' => '版', # Not used as normal message but as header for the special page itself
'version-extensions' => '裝展',
'version-specialpages' => '奇頁',
'version-parserhooks' => '語鈎',
'version-variables' => '變數',
'version-other' => '他',
'version-mediahandlers' => '媒處',
'version-hooks' => '鈎',
'version-extension-functions' => '展函',
'version-parser-extensiontags' => '語展標',
'version-parser-function-hooks' => '語函鈎',
'version-skin-extension-functions' => '面版展函',
'version-hook-name' => '鈎名',
'version-hook-subscribedby' => '用於',
'version-version' => '版',
'version-license' => '牌',
'version-software' => '裝件',
'version-software-product' => '品',
'version-software-version' => '版',
# Special:FilePath
'filepath' => '檔路',
'filepath-page' => '檔名:',
'filepath-submit' => '尋路',
'filepath-summary' => '此奇頁取一檔之整路。圖以全解像示之,他檔會以有關之程式啟動也。
輸檔名之,不包「{{ns:file}}:」開頭也。',
# Special:FileDuplicateSearch
'fileduplicatesearch' => '擇重檔',
'fileduplicatesearch-summary' => '以重檔之切去查重也。
入名時無 "{{ns:file}}:" 首也。',
'fileduplicatesearch-legend' => '尋重',
'fileduplicatesearch-filename' => '名:',
'fileduplicatesearch-submit' => '尋',
'fileduplicatesearch-info' => '像素$1矩$2<br />大小:$3<br />MIME類型:$4',
'fileduplicatesearch-result-1' => '案 "$1" 無重也。',
'fileduplicatesearch-result-n' => '案 "$1" 重有$2。',
# Special:SpecialPages
'specialpages' => '特查',
'specialpages-note' => '----
* 準特查。
* <strong class="mw-specialpagerestricted">限特查。</strong>',
'specialpages-group-maintenance' => '護報',
'specialpages-group-other' => '它之奇頁',
'specialpages-group-login' => '登/增',
'specialpages-group-changes' => '近易與誌',
'specialpages-group-media' => '媒報兼呈',
'specialpages-group-users' => '簿與權',
'specialpages-group-highuse' => '高用頁',
'specialpages-group-pages' => '頁列',
'specialpages-group-pagetools' => '頁器',
'specialpages-group-wiki' => 'Wiki訊與器',
'specialpages-group-redirects' => '轉之特查',
'specialpages-group-spam' => '反垃圾之器',
# Special:BlankPage
'blankpage' => '白頁',
'intentionallyblankpage' => '此頁為白也,試速之用',
# External image whitelist
'external_image_whitelist' => ' #同留<pre>
#下(中之//)乃正表式
#乃外(連)圖配之
#配乃成像,非配則成連
#有 # 之為注
#無為大小之異也
#入正表式。同留</pre>',
# Special:Tags
'tags-edit' => '纂',
);
|
dantman/mwjs
|
languages/messages/MessagesLzh.php
|
PHP
|
gpl-2.0
| 113,867
|
/* ---------------------------------------------------------------------- *
* old_ldsvguts.c
* This file is part of lincity-ng.
* ---------------------------------------------------------------------- */
/* This file is for loading old games (before NG 1.91)
* and convert them to new format + data structure
*/
#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>
#include <iostream>
#include "tinygettext/gettext.hpp"
#include "gui_interface/screen_interface.h"
#include "gui_interface/shared_globals.h"
#include "stats.h"
#include "init_game.h"
#include <fcntl.h>
#include <sys/types.h>
#if defined (TIME_WITH_SYS_TIME)
#include <time.h>
#include <sys/time.h>
#else
#if defined (HAVE_SYS_TIME_H)
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif
#include <cstdlib>
#include <string.h>
#include <math.h>
/*
#if defined (WIN32)
#include <winsock.h>
#include <io.h>
#include <direct.h>
#include <process.h>
#endif
*/
#ifdef __EMX__
#define chown(x,y,z)
#endif
#if defined (HAVE_DIRENT_H)
#include <dirent.h>
#define NAMLEN(dirent) strlen((dirent)->d_name)
#else
#define dirent direct
#define NAMLEN(dirent) (dirent)->d_namlen
#if defined (HAVE_SYS_NDIR_H)
#include <sys/ndir.h>
#endif
#if defined (HAVE_SYS_DIR_H)
#include <sys/dir.h>
#endif
#if defined (HAVE_NDIR_H)
#include <ndir.h>
#endif
#endif
#include <ctype.h>
//#include "common.h"
/*
#ifdef LC_X11
#include <X11/cursorfont.h>
#endif
*/
#include "lctypes.h"
#include "lin-city.h"
#include "engglobs.h"
#include "fileutil.h"
#include "power.h"
#include "gui_interface/pbar_interface.h"
#include "lincity-ng/ErrorInterface.hpp"
#include "stats.h"
#include "old_ldsvguts.h"
#include "loadsave.h"
#include "simulate.h"
#include "engine.h"
#if defined (WIN32) && !defined (NDEBUG)
#define START_FAST_SPEED 1
#define SKIP_OPENING_SCENE 1
#endif
#define SI_BLACK 252
#define SI_RED 253
#define SI_GREEN 254
#define SI_YELLOW 255
/* Extern resources */
extern void ok_dial_box(const char *, int, const char *);
extern void prog_box(const char *, int);
extern void print_total_money(void);
extern int count_groups(int);
extern void reset_animation_times(void);
/* ---------------------------------------------------------------------- *
* Private Fn Prototypes
* ---------------------------------------------------------------------- */
void upgrade_to_v2 (void);
/* ---------------------------------------------------------------------- *
* Public functions
* ---------------------------------------------------------------------- */
void load_city_old(char *cname)
{
unsigned long q;
int i, x, y, n, p;
unsigned int z;
int num_pbars, pbar_data_size;
int pbar_tmp;
int dummy;
gzFile gzfile;
char s[256];
#ifdef DEBUG
fprintf(stderr, "old file format, so load with old function, and then convert to new format\n");
#endif
gzfile = gzopen(cname, "rb");
if (gzfile == NULL) {
printf(_("Can't open <%s> (gzipped)"), cname);
do_error("Can't open it!");
}
/* Initialise additional structure FIXME random village does not go here*/
for (x = 0; x < WORLD_SIDE_LEN; x++)
for (y = 0; y < WORLD_SIDE_LEN; y++) {
MP_TECH(x,y) = 0;
MP_DATE(x,y) = 0;
MP_ANIM(x,y) = 0;
}
/* Add version to shared global variables for playing/saving games without waterwell */
sscanf(gzgets(gzfile, s, 256), "%d", &ldsv_version);
if (ldsv_version < MIN_LOAD_VERSION) {
//ok_dial_box("too-old.mes", BAD, 0L); // FIXME: AL1 screen is not set, so ok_dial_box fails
// => we have an error message, but not the good one ;-)
fprintf(stderr, "Too old file format, cannot load it, sorry\n");
gzclose(gzfile);
return;
}
fprintf(stderr, " ldsv_version = %i \n", ldsv_version);
use_waterwell = true;
init_pbars();
num_pbars = NUM_PBARS;
pbar_data_size = PBAR_DATA_SIZE;
init_inventory();
print_time_for_year();
q = (unsigned long)sizeof(Map_Point_Info);
prog_box(_("Loading scene"), 0);
for (x = 0; x < WORLD_SIDE_LEN; x++) {
for (y = 0; y < WORLD_SIDE_LEN; y++) {
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).population) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).flags) + z) = n;
}
for (z = 0; z < sizeof(unsigned short); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).coal_reserve) + z) = n;
}
for (z = 0; z < sizeof(unsigned short); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).ore_reserve) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).int_1) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).int_2) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).int_3) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).int_4) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).int_5) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).int_6) + z) = n;
}
for (z = 0; z < sizeof(int); z++) {
sscanf(gzgets(gzfile, s, 256), "%d", &n);
*(((unsigned char *)&MP_INFO(x, y).int_7) + z) = n;
}
sscanf(gzgets(gzfile, s, 256), "%d", &n);
MP_POL(x, y) = (unsigned short)n;
sscanf(gzgets(gzfile, s, 256), "%d", &n);
MP_TYPE(x, y) = (short)n;
if (get_group_of_type(MP_TYPE(x, y)) == GROUP_MARKET)
inventory(x, y);
}
if (((93 * x) / WORLD_SIDE_LEN) % 3 == 0)
prog_box("", (93 * x) / WORLD_SIDE_LEN);
}
check_endian();
set_map_groups();
sscanf(gzgets(gzfile, s, 256), "%d", &main_screen_originx);
sscanf(gzgets(gzfile, s, 256), "%d", &main_screen_originy);
if (main_screen_originx > WORLD_SIDE_LEN - getMainWindowWidth() / 16 - 1)
main_screen_originx = WORLD_SIDE_LEN - getMainWindowWidth() / 16 - 1;
if (main_screen_originy > WORLD_SIDE_LEN - getMainWindowHeight() / 16 - 1)
main_screen_originy = WORLD_SIDE_LEN - getMainWindowHeight() / 16 - 1;
sscanf(gzgets(gzfile, s, 256), "%d", &total_time);
if (ldsv_version <= MM_MS_C_VER)
i = OLD_MAX_NUMOF_SUBSTATIONS;
else
i = MAX_NUMOF_SUBSTATIONS;
for (x = 0; x < i; x++) {
sscanf(gzgets(gzfile, s, 256), "%d", &substationx[x]);
sscanf(gzgets(gzfile, s, 256), "%d", &substationy[x]);
}
prog_box("", 92);
sscanf(gzgets(gzfile, s, 256), "%d", &numof_substations);
if (ldsv_version <= MM_MS_C_VER)
i = OLD_MAX_NUMOF_MARKETS;
else
i = MAX_NUMOF_MARKETS;
for (x = 0; x < i; x++) {
sscanf(gzgets(gzfile, s, 256), "%d", &marketx[x]);
sscanf(gzgets(gzfile, s, 256), "%d", &markety[x]);
}
prog_box("", 94);
sscanf(gzgets(gzfile, s, 256), "%d", &numof_markets);
sscanf(gzgets(gzfile, s, 256), "%d", &people_pool);
sscanf(gzgets(gzfile, s, 256), "%d", &total_money);
sscanf(gzgets(gzfile, s, 256), "%d", &income_tax_rate);
sscanf(gzgets(gzfile, s, 256), "%d", &coal_tax_rate);
sscanf(gzgets(gzfile, s, 256), "%d", &dole_rate);
sscanf(gzgets(gzfile, s, 256), "%d", &transport_cost_rate);
sscanf(gzgets(gzfile, s, 256), "%d", &goods_tax_rate);
sscanf(gzgets(gzfile, s, 256), "%d", &export_tax);
sscanf(gzgets(gzfile, s, 256), "%d", &export_tax_rate);
sscanf(gzgets(gzfile, s, 256), "%d", &import_cost);
sscanf(gzgets(gzfile, s, 256), "%d", &import_cost_rate);
sscanf(gzgets(gzfile, s, 256), "%d", &tech_level);
if (tech_level > MODERN_WINDMILL_TECH)
modern_windmill_flag = 1;
sscanf(gzgets(gzfile, s, 256), "%d", &tpopulation);
sscanf(gzgets(gzfile, s, 256), "%d", &tstarving_population);
sscanf(gzgets(gzfile, s, 256), "%d", &tunemployed_population);
sscanf(gzgets(gzfile, s, 256), "%d", &x); /* waste_goods obsolete */
sscanf(gzgets(gzfile, s, 256), "%d", &power_made);
sscanf(gzgets(gzfile, s, 256), "%d", &power_used);
sscanf(gzgets(gzfile, s, 256), "%d", &coal_made);
sscanf(gzgets(gzfile, s, 256), "%d", &coal_used);
sscanf(gzgets(gzfile, s, 256), "%d", &goods_made);
sscanf(gzgets(gzfile, s, 256), "%d", &goods_used);
sscanf(gzgets(gzfile, s, 256), "%d", &ore_made);
sscanf(gzgets(gzfile, s, 256), "%d", &ore_used);
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &diff_old_population */
/* Update variables calculated from those above */
housed_population = tpopulation / NUMOF_DAYS_IN_MONTH;
prog_box("", 96);
/* Get size of monthgraph array */
if (ldsv_version <= MG_C_VER) {
i = 120;
} else {
sscanf(gzgets(gzfile, s, 256), "%d", &i);
}
for (x = 0; x < i; x++) {
/* If more entries in file than will fit on screen,
then we need to skip past them. */
if (x >= monthgraph_size) {
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &monthgraph_pop[x] */
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &monthgraph_starve[x] */
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &monthgraph_nojobs[x] */
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &monthgraph_ppool[x] */
} else {
sscanf(gzgets(gzfile, s, 256), "%d", &monthgraph_pop[x]);
sscanf(gzgets(gzfile, s, 256), "%d", &monthgraph_starve[x]);
sscanf(gzgets(gzfile, s, 256), "%d", &monthgraph_nojobs[x]);
sscanf(gzgets(gzfile, s, 256), "%d", &monthgraph_ppool[x]);
}
/* If our save file is old, skip past obsolete diffgraph entries */
if (ldsv_version <= MG_C_VER) {
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &diffgraph_power[x] */
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &diffgraph_coal[x] */
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &diffgraph_goods[x] */
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &diffgraph_ore[x] */
sscanf(gzgets(gzfile, s, 256), "%d", &dummy); /* &diffgraph_population[x] */
}
}
/* If screen bigger than number of entries in file, pad with zeroes */
while (x < monthgraph_size) {
monthgraph_pop[x] = 0;
monthgraph_starve[x] = 0;
monthgraph_nojobs[x] = 0;
monthgraph_ppool[x] = 0;
x++;
}
prog_box("", 98);
sscanf(gzgets(gzfile, s, 256), "%d", &rockets_launched);
sscanf(gzgets(gzfile, s, 256), "%d", &rockets_launched_success);
sscanf(gzgets(gzfile, s, 256), "%d", &coal_survey_done);
for (x = 0; x < pbar_data_size; x++) {
for (p = 0; p < num_pbars; p++) {
sscanf(gzgets(gzfile, s, 256), "%d", &(pbar_tmp));
update_pbar(p, pbar_tmp, 1);
/* sscanf( gzgets( gzfile, s, 256 ), "%d", &(pbars[p].data[x])); */
}
}
for (p = 0; p < num_pbars; p++)
pbars[p].data_size = pbar_data_size;
prog_box("", 99);
for (p = 0; p < num_pbars; p++) {
sscanf(gzgets(gzfile, s, 256), "%d", &(pbars[p].oldtot));
sscanf(gzgets(gzfile, s, 256), "%d", &(pbars[p].diff));
}
sscanf(gzgets(gzfile, s, 256), "%d", &cheat_flag);
sscanf(gzgets(gzfile, s, 256), "%d", &total_pollution_deaths);
sscanf(gzgets(gzfile, s, 256), "%f", &pollution_deaths_history);
sscanf(gzgets(gzfile, s, 256), "%d", &total_starve_deaths);
sscanf(gzgets(gzfile, s, 256), "%f", &starve_deaths_history);
sscanf(gzgets(gzfile, s, 256), "%d", &total_unemployed_years);
sscanf(gzgets(gzfile, s, 256), "%f", &unemployed_history);
sscanf(gzgets(gzfile, s, 256), "%d", &max_pop_ever);
sscanf(gzgets(gzfile, s, 256), "%d", &total_evacuated);
sscanf(gzgets(gzfile, s, 256), "%d", &total_births);
for (x = 0; x < NUMOF_MODULES; x++)
sscanf(gzgets(gzfile, s, 256), "%d", &(module_help_flag[x]));
sscanf(gzgets(gzfile, s, 256), "%d", &x); /* just dummy reads */
sscanf(gzgets(gzfile, s, 256), "%d", &x); /* for backwards compatibility. */
/* 10 dummy strings, for missed out things, have been put in save. */
/* Input from this point uses them. */
/* XXX: WCK: Huh? Missed out things? */
sscanf(gzgets(gzfile, s, 256), "%128s", given_scene);
if (strncmp(given_scene, "dummy", 5) == 0 || strlen(given_scene) < 3)
given_scene[0] = 0;
sscanf(gzgets(gzfile, s, 256), "%128s", s);
if (strncmp(given_scene, "dummy", 5) != 0)
sscanf(s, "%d", &highest_tech_level);
else
highest_tech_level = 0;
gzgets(gzfile, s, 200);
if (sscanf
(s, "sust %d %d %d %d %d %d %d %d %d %d", &sust_dig_ore_coal_count, &sust_port_count, &sust_old_money_count,
&sust_old_population_count, &sust_old_tech_count, &sust_fire_count, &sust_old_money, &sust_old_population,
&sust_old_tech, &sustain_flag) == 10) {
sust_dig_ore_coal_tip_flag = sust_port_flag = 1;
/* GCS FIX: Check after loading file if screen is drawn OK */
/* draw_sustainable_window (); */
} else
sustain_flag = sust_dig_ore_coal_count = sust_port_count
= sust_old_money_count = sust_old_population_count
= sust_old_tech_count = sust_fire_count = sust_old_money = sust_old_population = sust_old_tech = 0;
if (ldsv_version == WATERWELL_V2) {
gzgets(gzfile, s, 80);
sscanf(s, "arid %d %d", &global_aridity, &global_mountainity);
#ifdef DEBUG
fprintf(stderr," arid %d, mountain %d \n", global_aridity, global_mountainity);
#endif
for (x = 0; x < WORLD_SIDE_LEN; x++) {
for (y = 0; y < WORLD_SIDE_LEN; y++) {
gzgets(gzfile, s, 200);
sscanf(s,"%d %d %d %d %d %d %d %d %d %d %d %d",&(ground[x][y].altitude)
, &ground[x][y].ecotable
, &ground[x][y].wastes
, &ground[x][y].pollution
, &ground[x][y].water_alt
, &ground[x][y].water_pol
, &ground[x][y].water_wast
, &ground[x][y].water_next
, &ground[x][y].int1
, &ground[x][y].int2
, &ground[x][y].int3
, &ground[x][y].int4
);
#ifdef DEBUG
if (x == 10 && y == 10)
fprintf(stderr," alt %d, int4 %d \n", ground[x][y].altitude, ground[x][y].int4);
#endif
}
}
}
gzclose(gzfile);
numof_shanties = count_groups(GROUP_SHANTY);
numof_communes = count_groups(GROUP_COMMUNE);
prog_box("", 100);
/* set up the university intake. */
x = count_groups(GROUP_UNIVERSITY);
if (x > 0) {
university_intake_rate = (count_groups(GROUP_SCHOOL) * 20) / x;
if (university_intake_rate > 100)
university_intake_rate = 100;
} else
university_intake_rate = 50;
unhighlight_module_button(selected_module);
selected_module = sbut[7]; /* 7 is track. Watch out though! */
highlight_module_button(selected_module);
set_selected_module(CST_TRACK_LR);
print_total_money();
reset_animation_times();
/* kind upgrade of MP_TECH for old buildings, when we don't know
* eg light industries pollution depends on tech */
int tk = (3 * highest_tech_level) / 4;
if (tech_level >= tk)
tk = tech_level;
/* update tech dep */
for (x = 0; x < WORLD_SIDE_LEN; x++)
for (y = 0; y < WORLD_SIDE_LEN; y++) {
switch (MP_GROUP(x, y)) {
case (GROUP_WINDMILL):
MP_TECH(x,y) = MP_INFO(x, y).int_2;
MP_INFO(x, y).int_1 = (int)(WINDMILL_POWER + (((double)MP_TECH(x, y) * WINDMILL_POWER)
/ MAX_TECH_LEVEL));
break;
case (GROUP_COAL_POWER):
MP_TECH(x,y) = MP_INFO(x,y).int_4;
MP_INFO(x, y).int_1 = (int)(POWERS_COAL_OUTPUT + (((double)MP_TECH(x, y) * POWERS_COAL_OUTPUT)
/ MAX_TECH_LEVEL));
break;
case (GROUP_SOLAR_POWER):
{
float PSO = POWERS_SOLAR_OUTPUT;
float MT = MAX_TECH_LEVEL;
int t1, t2 , t3;
t1 = (int) (((MP_INFO(x,y).int_1 - PSO) * MT)/PSO);
t2 = MP_INFO(x,y).int_2;
t3 = (int) (((MP_INFO(x,y).int_3 - PSO) * MT)/PSO);
//because of bug introduced then fixed near 1207 1218 or in waterwell branch
if (MP_INFO(x,y).int_2 != 0) {
MP_TECH(x,y) = t2;
} else if ( MP_INFO(x,y).int_3 >=0 ) {
MP_TECH(x,y) = t3;
} else if (MP_INFO(x,y).int_1 != 0) {
MP_TECH(x,y) = t1;
} else {
fprintf(stderr," Error, unknown tech level for solar plant at x=%d, y=%d\n", x, y);
if (tk > GROUP_SOLAR_POWER_TECH)
MP_TECH(x,y) = tk;
else
MP_TECH(x,y) = GROUP_SOLAR_POWER_TECH;
}
//fprintf(stderr,"TECH %d, t1 %d, t2 %d, t3 %d, plant at x=%d, y=%d\n", MP_TECH(x,y), t1, t2, t3, x, y);
MP_INFO(x, y).int_1 = (int)(POWERS_SOLAR_OUTPUT + (((double)MP_TECH(x, y) * POWERS_SOLAR_OUTPUT)
/ MAX_TECH_LEVEL));
break;
}
case GROUP_ORGANIC_FARM:
MP_TECH(x,y) = MP_INFO(x,y).int_1;
break;
case GROUP_RECYCLE:
MP_TECH(x,y) = MP_INFO(x, y).int_4;
break;
case GROUP_INDUSTRY_L:
if ( MP_TECH(x,y) == 0 ){
if ( tk > GROUP_INDUSTRY_L_TECH ){
MP_TECH(x,y) = tk;
} else {
MP_TECH(x,y) = GROUP_INDUSTRY_L_TECH;
}
}
break;
}
}
map_power_grid(true); /* WCK: Is this safe to do here?
* AL1: No, in NG_1.1
* In case of error message with ok_dial_box
* the dialog cannot appear because the screen
* is not set up => crash.
* FIXME: move all initialisation elsewhere, in
* engine.cpp or simulate.cpp.
*/
upgrade_to_v2();
}
void reset_animation_times(void)
{
int x, y;
for (y = 0; y < WORLD_SIDE_LEN; y++)
for (x = 0; x < WORLD_SIDE_LEN; x++) {
MP_ANIM(x,y) = 0;
if (MP_GROUP(x, y) == GROUP_FIRE)
MP_INFO(x, y).int_3 = 0;
}
}
void check_endian(void)
{
static int flag = 0;
char *cs;
int t, x, y;
t = 0;
cs = (char *)&t;
*cs = 1;
if (t == 1) /* little endian */
return;
if (flag == 0) {
flag = 1;
}
for (y = 0; y < WORLD_SIDE_LEN; y++) {
for (x = 0; x < WORLD_SIDE_LEN; x++) {
eswap32(&(MP_INFO(x, y).population));
eswap32(&(MP_INFO(x, y).flags));
if (sizeof(short) == 2) {
eswap16(&(MP_INFO(x, y).coal_reserve));
eswap16(&(MP_INFO(x, y).ore_reserve));
} else if (sizeof(short) == 4) {
eswap32((int *)&(MP_INFO(x, y).coal_reserve));
eswap32((int *)&(MP_INFO(x, y).ore_reserve));
} else {
/* prevent gcc warning on amd64: argument 2 has type 'long unsigned int' !!! */
printf("Strange size (%d) for short, please mail me.\n", (int) sizeof(short));
}
eswap32(&(MP_INFO(x, y).int_1));
eswap32(&(MP_INFO(x, y).int_2));
eswap32(&(MP_INFO(x, y).int_3));
eswap32(&(MP_INFO(x, y).int_4));
eswap32(&(MP_INFO(x, y).int_5));
eswap32(&(MP_INFO(x, y).int_6));
eswap32(&(MP_INFO(x, y).int_7));
}
}
}
void eswap32(int *i)
{
char *cs, c1, c2, c3, c4;
cs = (char *)i;
c1 = *cs;
c2 = *(cs + 1);
c3 = *(cs + 2);
c4 = *(cs + 3);
*(cs++) = c4;
*(cs++) = c3;
*(cs++) = c2;
*cs = c1;
}
void eswap16(unsigned short *i)
{
char *cs, c1, c2;
cs = (char *)i;
c1 = *cs;
c2 = *(cs + 1);
*(cs++) = c2;
*cs = c1;
}
void upgrade_to_v2 (void)
{
// Follow order and logic of new_city
int x,y;
global_mountainity= 10 + rand () % 300;
// Grey border (not visible on the map, x = 0 , x = 99, y = 0, y = 99)
for (x = 0; x < WORLD_SIDE_LEN; x++)
for (y = 0; y < WORLD_SIDE_LEN; y++) {
ALT(x,y) = 0;
if ( !GROUP_IS_BARE(MP_GROUP(x, y)) ) {
/* be nice, put water under all existing builings / farms / parks ... */
/* This may change according to global_aridity and distance_to_river */
MP_INFO(x,y).flags |= FLAG_HAS_UNDERGROUND_WATER;
}
}
/* Let 10 years in game time to put waterwells where needed, then starvation will occur */
deadline=total_time + 1200 * 10;
flag_warning = true; // warn player.
/* TODO AL1 Upgrade ground[x][y].water_alt and .altitude
* TODO This not used yet, so just keep initialisation to zero, until something good is done
*/
setup_land();
}
|
javiercantero/lincity-ng
|
src/lincity/old_ldsvguts.cpp
|
C++
|
gpl-2.0
| 22,887
|
<?php
/* -----------------------------------------------------------------
* $Id: cross_selling.php 571 2013-08-21 16:02:17Z akausch $
* Copyright (c) 2011-2021 commerce:SEO by Webdesign Erfurt
* http://www.commerce-seo.de
* ------------------------------------------------------------------
* based on:
* (c) 2000-2001 The Exchange Project (earlier name of osCommerce)
* (c) 2002-2003 osCommerce - www.oscommerce.com
* (c) 2003 nextcommerce - www.nextcommerce.org
* (c) 2005 xt:Commerce - www.xt-commerce.com
* Released under the GNU General Public License
* --------------------------------------------------------------- */
$data = $product->getCrossSells();
if (!empty($data) && PRODUCT_DETAILS_TAB_CROSS_SELLING == 'true') {
$module_smarty = new Smarty;
$module_smarty->assign('language', $_SESSION['language']);
$module_smarty->assign('module_content', $data);
$module_smarty->assign('cross_selling', true);
$module_smarty->assign('tpl_path','templates/'.CURRENT_TEMPLATE.'/');
$module_smarty->assign('TITLE', CROSS_SELLING);
$module_smarty->assign('CLASS', 'cross_selling');
$module_smarty->assign('DEVMODE', USE_TEMPLATE_DEVMODE);
$module_smarty->caching = false;
$module = $module_smarty->fetch(cseo_get_usermod(CURRENT_TEMPLATE . '/module/product_listing/product_listings.html', USE_TEMPLATE_DEVMODE));
$info_smarty->assign('MODULE_cross_selling', $module);
}
if (ACTIVATE_REVERSE_CROSS_SELLING == 'true' && PRODUCT_DETAILS_TAB_REVERSE_CROSS_SELLING == 'true') {
$module_smarty = new Smarty;
$data = $product->getReverseCrossSells();
if (count($data) > 0) {
$module_smarty->assign('language', $_SESSION['language']);
$module_smarty->assign('module_content', $data);
$module_smarty->assign('reverse_cross_selling', true);
$module_smarty->assign('tpl_path','templates/'.CURRENT_TEMPLATE.'/');
$module_smarty->assign('TITLE', REVERSE_CROSS_SELLING);
$module_smarty->assign('CLASS', 'reverse_cross_selling');
$module_smarty->assign('DEVMODE', USE_TEMPLATE_DEVMODE);
$module_smarty->caching = false;
$module = $module_smarty->fetch(cseo_get_usermod(CURRENT_TEMPLATE . '/module/product_listing/product_listings.html', USE_TEMPLATE_DEVMODE));
$info_smarty->assign('MODULE_reverse_cross_selling', $module);
}
}
|
commerceseo/v2next
|
includes/modules/cross_selling.php
|
PHP
|
gpl-2.0
| 2,428
|
<?php if ($teaser): ?>
<!-- teaser template HTML here -->
<div class="object-teaser">
<div class="object-teaser-image"><a href="/<?php echo $node->path;?>"><?php echo $node->node_images;?></a></div>
<div class="object-teaser-text">
<h2><?php echo l($node->title, 'node/'. $node->nid, array('title' => t('View object')));?></h2>
<?php if ($node->content['body']['#value']) { echo '<p class="object-teaser-description">'. $node->content['body']['#value'] .'</p>'; } ?>
<?php if ($node->content['field_prijs']['#value']) { ?>
<p class="object-teaser-value"><?php echo t('Price'); ?><sup><a href="#"></a></sup>: <?php echo $node->field_prijs[0]['view'];?></p>
<?php } ?>
</div>
</div>
<?php else: ?>
<!-- regular node view template HTML here -->
<div class="content object">
<?php if ($node->content['body']['#value']) {
echo '<div class="object-description">'. $node->content['body']['#value'] .'</div>';
}
?>
<div class="object-content-images">
<?php echo $node->node_images;?> <br /><br />
<?php // echo l(t('View all images'), 'node/'.$node->nid.'/image_gallery');?>
</div>
<?php if ($node->content['body']['#value']) { ?>
<p>
<span class="object-label"><?php echo t('Price'); ?> :</span>
<span class="object-value"><?php echo $node->field_prijs[0]['view'];?></span>
</p>
<p class="tiny"><?php echo t('The prices shown on this website are indicative and may vary depending on the gold and silver price and your exact requirements. <a href="/en/prices">Learn more</a>'); ?>
</p>
<?php } ?>
<p>
<span class="object-label"><?php echo t('Weight'); ?> :</span>
<span class="object-value"><?php echo $node->field_gewicht[0]['view'];?></span>
</p>
<p>
<span class="object-label"><?php echo t('Article number'); ?> :</span>
<span class="object-value"><?php echo $node->nid;?></span>
</p>
<?php if ($taxonomy) { ?>
<div class="terms">
<p>
<span class="object-label"><?php echo t('Categories'); ?> :</span><br />
<span class="object-value">
<?php foreach($node->taxonomy as $tid => $taxo)
$taxo_links[] = l($taxo->name,"taxonomy/term/$taxo->tid", array('title' => $taxo->name));
print implode(', ',$taxo_links);
?></span>
</p>
<p class="form-link">
<a href="/content/contact-opnemen?artnr=<?php echo $node->nid;?>&artnaam=<?php echo urlencode($node->title);?>&subject=Vraag"><?php echo t('Ask question about product'); ?></a>
</p>
</div>
<?php } ?>
</div>
<div class="clear-block clear"></div>
<?php endif; ?>
|
batigolix/drupal6_a2h
|
sites/all/themes/mokumegatwee/node-object.tpl.php
|
PHP
|
gpl-2.0
| 2,935
|
/*********************************************************************
*
* Abstracts generic network device operation, and provide dummy
* stub here if required. Each driver implementation hooks to
* this interface
*
*********************************************************************/
#include "net_dev.h"
static net_dev_drv_t net_device_driver;
static net_dev_drv_t *net_device_driver_p = &net_device_driver;
static rt_err_t default_init (rt_device_t dev)
{
return RT_EOK;
}
static rt_err_t default_open (rt_device_t dev, rt_uint16_t oflag)
{
return RT_EOK;
}
static rt_err_t default_close (rt_device_t dev)
{
return RT_EOK;
}
static rt_size_t default_read (rt_device_t dev, rt_off_t pos, void* buffer,
rt_size_t size)
{
rt_set_errno(-RT_ENOSYS);
return RT_EOK;
}
static rt_size_t default_write (rt_device_t dev, rt_off_t pos, const void* buffer, rt_size_t size)
{
rt_set_errno(-RT_ENOSYS);
return RT_EOK;
}
static rt_err_t default_control(rt_device_t dev, rt_uint8_t cmd, void *args)
{
switch (cmd)
{
case NIOCTL_GADDR:
/* get mac address */
if (args) rt_memcpy(args, net_device_driver_p->dev_addr, ETH_ALEN);
else return -RT_ERROR;
break;
default :
break;
}
return RT_EOK;
}
/*
* Initialize file operations by specific driver implementation
* Parameters set to NULL means use the default defined in net_dev.c
*/
rt_err_t net_dev_drv_register_handler (net_dev_drv_init_func init,
net_dev_drv_open_func open,
net_dev_drv_close_func close,
net_dev_drv_read_func read,
net_dev_drv_write_func write,
net_dev_drv_control_func control,
net_dev_drv_rx_func rx,
net_dev_drv_tx_func tx)
{
/* do not allow multiple registry */
if (net_device_driver_p->parent.eth_rx ||
net_device_driver_p->parent.eth_tx ||
rx == NULL || tx == NULL) {
return -RT_ERROR;
}
/* dummy initialization */
net_device_driver_p->parent.parent.init = init ? init : default_init;
net_device_driver_p->parent.parent.open = open ? open : default_open;
net_device_driver_p->parent.parent.close = close ? close : default_close;
net_device_driver_p->parent.parent.read = read ? read : default_read;
net_device_driver_p->parent.parent.write = write ? write : default_write;
net_device_driver_p->parent.parent.control = control ? control : default_control;
net_device_driver_p->parent.eth_rx = rx;
net_device_driver_p->parent.eth_tx = tx;
return RT_EOK;
}
/*
* Initialize device MAC address by device driver implementation
*/
void net_dev_drv_set_dev_addr (rt_uint8_t *device_address)
{
rt_memcpy(net_device_driver_p->dev_addr, device_address, ETH_ALEN);
}
/*
* Hook this driver into lwIP
*/
rt_err_t net_dev_drv_init (void)
{
if (net_device_driver_p->parent.eth_rx == NULL ||
net_device_driver_p->parent.eth_tx == NULL) {
return -RT_ERROR;
}
/* Update MAC address */
if (1) {
net_device_driver_p->dev_addr[0] = 0x00;
net_device_driver_p->dev_addr[1] = 0x0B;
net_device_driver_p->dev_addr[2] = 0x6C;
net_device_driver_p->dev_addr[3] = 0x89;
net_device_driver_p->dev_addr[4] = 0xBD;
net_device_driver_p->dev_addr[5] = 0x60;
} else {
net_device_driver_p->dev_addr[0] = 0x00;
net_device_driver_p->dev_addr[1] = 0x0B;
net_device_driver_p->dev_addr[2] = 0x6C;
net_device_driver_p->dev_addr[3] = 0x89;
net_device_driver_p->dev_addr[4] = 0x5B;
net_device_driver_p->dev_addr[5] = 0x1E;
}
rt_sem_init(&net_device_driver_p->net_dev_sem, "net_dev_sem", 1,
RT_IPC_FLAG_FIFO);
net_device_driver_p->rx_pkt_pending = 0;
/* add device to rt_device list */
return eth_device_init(&(net_device_driver_p->parent), "e0");
}
rt_err_t net_dev_drv_notify_rx (void)
{
return eth_device_ready(&net_device_driver_p->parent);
}
/*
* Lock/unlock protecting against simultanous read and write
*/
rt_err_t net_dev_drv_lock (void)
{
return rt_sem_take(&net_device_driver_p->net_dev_sem, RT_WAITING_FOREVER);
}
void net_dev_drv_unlock (void)
{
rt_sem_release(&net_device_driver_p->net_dev_sem);
}
|
zhelezyaka/stm23f105-vcp
|
net/driver/net_dev.c
|
C
|
gpl-2.0
| 4,687
|
<!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 (version 1.7.0_75) on Sun Aug 23 10:55:35 SGT 2015 -->
<title>Class Hierarchy</title>
<meta name="date" content="2015-08-23">
<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="Class Hierarchy";
}
//-->
</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="tk/giesecke/weatherstation/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.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">
<h1 class="title">Hierarchy For All Packages</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="tk/giesecke/weatherstation/package-tree.html">tk.giesecke.weatherstation</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">android.content.BroadcastReceiver
<ul>
<li type="circle">android.appwidget.AppWidgetProvider
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/WidgetValues.html" title="class in tk.giesecke.weatherstation"><span class="strong">WidgetValues</span></a></li>
</ul>
</li>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/AutoStart.html" title="class in tk.giesecke.weatherstation"><span class="strong">AutoStart</span></a></li>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/ScreenReceiver.html" title="class in tk.giesecke.weatherstation"><span class="strong">ScreenReceiver</span></a></li>
</ul>
</li>
<li type="circle">android.content.Context
<ul>
<li type="circle">android.content.ContextWrapper
<ul>
<li type="circle">android.view.ContextThemeWrapper
<ul>
<li type="circle">android.app.Activity (implements android.content.ComponentCallbacks2, android.view.KeyEvent.Callback, android.view.LayoutInflater.Factory2, android.view.View.OnCreateContextMenuListener, android.view.Window.Callback, android.view.Window.OnWindowDismissedCallback)
<ul>
<li type="circle">android.support.v4.app.FragmentActivity
<ul>
<li type="circle">android.support.v7.app.AppCompatActivity (implements android.support.v7.app.ActionBarDrawerToggle.DelegateProvider, android.support.v7.app.AppCompatCallback, android.support.v4.app.TaskStackBuilder.SupportParentable)
<ul>
<li type="circle">android.support.v7.app.ActionBarActivity
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/WeatherStation.html" title="class in tk.giesecke.weatherstation"><span class="strong">WeatherStation</span></a> (implements android.widget.AdapterView.OnItemClickListener, android.hardware.SensorEventListener, android.view.View.OnClickListener)
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/Utils.html" title="class in tk.giesecke.weatherstation"><span class="strong">Utils</span></a> (implements android.widget.AdapterView.OnItemClickListener)</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/WidgetValuesConfigure.html" title="class in tk.giesecke.weatherstation"><span class="strong">WidgetValuesConfigure</span></a></li>
</ul>
</li>
</ul>
</li>
<li type="circle">android.app.Service (implements android.content.ComponentCallbacks2)
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/BGService.html" title="class in tk.giesecke.weatherstation"><span class="strong">BGService</span></a> (implements android.hardware.SensorEventListener)</li>
<li type="circle">android.app.IntentService
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/WidgetValuesService.html" title="class in tk.giesecke.weatherstation"><span class="strong">WidgetValuesService</span></a> (implements android.hardware.SensorEventListener)</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li type="circle">android.database.sqlite.SQLiteOpenHelper
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/WSDatabaseHelper.html" title="class in tk.giesecke.weatherstation"><span class="strong">WSDatabaseHelper</span></a></li>
</ul>
</li>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/SwipeDetector.html" title="class in tk.giesecke.weatherstation"><span class="strong">SwipeDetector</span></a> (implements android.view.View.OnTouchListener)</li>
<li type="circle">android.view.View (implements android.view.accessibility.AccessibilityEventSource, android.graphics.drawable.Drawable.Callback, android.view.KeyEvent.Callback)
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/GaugeView.html" title="class in tk.giesecke.weatherstation"><span class="strong">GaugeView</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/SwipeDetector.onSwipeEvent.html" title="interface in tk.giesecke.weatherstation"><span class="strong">SwipeDetector.onSwipeEvent</span></a></li>
</ul>
<h2 title="Enum Hierarchy">Enum Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)
<ul>
<li type="circle">tk.giesecke.weatherstation.<a href="tk/giesecke/weatherstation/SwipeDetector.SwipeTypeEnum.html" title="enum in tk.giesecke.weatherstation"><span class="strong">SwipeDetector.SwipeTypeEnum</span></a></li>
</ul>
</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="tk/giesecke/weatherstation/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.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 ======= -->
</body>
</html>
|
beegee-tokyo/WeatherStation
|
docs/overview-tree.html
|
HTML
|
gpl-2.0
| 8,206
|
/*
* @(#) IIRHighpassFilter.java
*
* Created on 09.01.2012 by Daniel Becker
*
*-----------------------------------------------------------------------
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*
* Source adopted from package com.db.media.audio.dsp.*;
*
* Copyright (c) 2000 Silvere Martin-Michiellot All Rights Reserved.
*
* Silvere Martin-Michiellot grants you ("Licensee") a non-exclusive,
* royalty free, license to use, modify and redistribute this
* software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Silvere Martin-Michiellot.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. Silvere Martin-Michiellot
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
* Silvere Martin-Michiellot OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF Silvere Martin-Michiellot HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*
*/
package de.quippy.javamod.mixer.dsp.iir.filter;
/**
* @author Daniel Becker
*/
public class IIRHighpassFilter extends IIRFilterBase
{
/**
* Default Constructor - to already set the GAIN
* @since 09.01.2012
*/
public IIRHighpassFilter()
{
super();
}
/**
* @param sampleRate
* @param channels
* @param frequency
* @param parameter
* @see de.quippy.javamod.mixer.dsp.iir.filter.IIRFilterBase#initialize(int, int, int, float)
* @since 09.01.2012
*/
@Override
public void initialize(final int sampleRate, final int channels, final int frequency, final float parameter)
{
super.initialize(sampleRate, channels, frequency, parameter);
// thetaZero = 2 * Pi * Freq * T or (2 * Pi * Freq) / sampleRate
// where Freq is cutoff frequency
float thetaZero = getThetaZero();
float theSin = parameter / (2.0f * (float)Math.sin(thetaZero));
// Beta relates gain to cutoff freq
beta = 0.5f * ((1.0f - theSin) / (1.0f + theSin));
// Final filter coefficient
gamma = (0.5f + beta) * (float)Math.cos(thetaZero);
// For unity gain
alpha = (0.5f + beta + gamma) / 4.0f;
// multiply by two to save time later
alpha *= 2f;
beta *= 2f;
gamma *= 2f;
}
/**
* @param sample
* @param channel
* @param iIndex
* @param jIndex
* @param kIndex
* @return
* @see de.quippy.javamod.mixer.dsp.iir.filter.IIRFilterBase#performFilterCalculation(float, int, int, int, int)
* @since 12.01.2012
*/
@Override
protected float performFilterCalculation(final float sample, final int channel, final int iIndex, final int jIndex, final int kIndex)
{
final float [] x = inArray[channel];
final float [] y = outArray[channel];
y[iIndex] = (alpha * ((x[iIndex] = sample) - (2.0f * x[kIndex]) + x[jIndex])) +
(gamma * y[kIndex]) -
(beta * y[jIndex]);
return y[iIndex];
}
}
|
jtrfp/javamod
|
src/main/java/de/quippy/javamod/mixer/dsp/iir/filter/IIRHighpassFilter.java
|
Java
|
gpl-2.0
| 4,625
|
/*
* Copyright (c) 2010 Sven Langkamp <sven.langkamp@gmail.com>
* Copyright (c) 2011 Jan Hambrecht <jaham@gmx.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.
*/
#include "kis_shape_selection.h"
#include <QPainter>
#include <QTimer>
#include <kundo2command.h>
#include <QMimeData>
#include <ktemporaryfile.h>
#include <KoShapeStroke.h>
#include <KoPathShape.h>
#include <KoShapeGroup.h>
#include <KoCompositeOp.h>
#include <KoShapeManager.h>
#include <KoDocument.h>
#include <KoEmbeddedDocumentSaver.h>
#include <KoGenStyle.h>
#include <KoOdfLoadingContext.h>
#include <KoOdfReadStore.h>
#include <KoOdfStylesReader.h>
#include <KoOdfWriteStore.h>
#include <KoXmlNS.h>
#include <KoShapeRegistry.h>
#include <KoShapeLoadingContext.h>
#include <KoXmlWriter.h>
#include <KoStore.h>
#include <KoShapeController.h>
#include <KoShapeSavingContext.h>
#include <KoStoreDevice.h>
#include <KoShapeTransformCommand.h>
#include <KoElementReference.h>
#include <kis_painter.h>
#include <kis_paint_device.h>
#include <kis_image.h>
#include <kis_iterator_ng.h>
#include <kis_selection.h>
#include "kis_shape_selection_model.h"
#include "kis_shape_selection_canvas.h"
#include "kis_shape_layer_paste.h"
#include "kis_take_all_shapes_command.h"
#include "kis_image_view_converter.h"
#include <kis_debug.h>
KisShapeSelection::KisShapeSelection(KisImageWSP image, KisSelectionWSP selection)
: KoShapeLayer(m_model = new KisShapeSelectionModel(image, selection, this))
, m_image(image)
{
Q_ASSERT(m_image);
setShapeId("KisShapeSelection");
setSelectable(false);
m_converter = new KisImageViewConverter(image);
m_canvas = new KisShapeSelectionCanvas();
m_canvas->shapeManager()->addShape(this);
m_model->moveToThread(image->thread());
m_canvas->moveToThread(image->thread());
}
KisShapeSelection::~KisShapeSelection()
{
m_model->setShapeSelection(0);
delete m_canvas;
delete m_converter;
}
KisShapeSelection::KisShapeSelection(const KisShapeSelection& rhs, KisSelection* selection)
: KoShapeLayer(m_model = new KisShapeSelectionModel(rhs.m_image, selection, this))
{
m_image = rhs.m_image;
m_converter = new KisImageViewConverter(m_image);
m_canvas = new KisShapeSelectionCanvas();
m_canvas->shapeManager()->addShape(this);
KoShapeOdfSaveHelper saveHelper(rhs.shapes());
KoDrag drag;
drag.setOdf(KoOdf::mimeType(KoOdf::Text), saveHelper);
QMimeData* mimeData = drag.mimeData();
Q_ASSERT(mimeData->hasFormat(KoOdf::mimeType(KoOdf::Text)));
KisShapeLayerShapePaste paste(this, 0);
bool success = paste.paste(KoOdf::Text, mimeData);
Q_ASSERT(success);
if (!success) {
warnUI << "Could not paste vector layer";
}
}
KisSelectionComponent* KisShapeSelection::clone(KisSelection* selection)
{
return new KisShapeSelection(*this, selection);
}
bool KisShapeSelection::saveSelection(KoStore * store) const
{
store->disallowNameExpansion();
KoOdfWriteStore odfStore(store);
KoXmlWriter* manifestWriter = odfStore.manifestWriter("application/vnd.oasis.opendocument.graphics");
KoEmbeddedDocumentSaver embeddedSaver;
KoDocument::SavingContext documentContext(odfStore, embeddedSaver);
if (!store->open("content.xml"))
return false;
KoStoreDevice storeDev(store);
KoXmlWriter * docWriter = KoOdfWriteStore::createOasisXmlWriter(&storeDev, "office:document-content");
// for office:master-styles
KTemporaryFile masterStyles;
masterStyles.open();
KoXmlWriter masterStylesTmpWriter(&masterStyles, 1);
KoPageLayout page;
page.format = KoPageFormat::defaultFormat();
QRectF rc = boundingRect();
page.width = rc.width();
page.height = rc.height();
if (page.width > page.height) {
page.orientation = KoPageFormat::Landscape;
} else {
page.orientation = KoPageFormat::Portrait;
}
KoGenStyles mainStyles;
KoGenStyle pageLayout = page.saveOdf();
QString layoutName = mainStyles.insert(pageLayout, "PL");
KoGenStyle masterPage(KoGenStyle::MasterPageStyle);
masterPage.addAttribute("style:page-layout-name", layoutName);
mainStyles.insert(masterPage, "Default", KoGenStyles::DontAddNumberToName);
KTemporaryFile contentTmpFile;
contentTmpFile.open();
KoXmlWriter contentTmpWriter(&contentTmpFile, 1);
contentTmpWriter.startElement("office:body");
contentTmpWriter.startElement("office:drawing");
KoShapeSavingContext shapeContext(contentTmpWriter, mainStyles, documentContext.embeddedSaver);
shapeContext.xmlWriter().startElement("draw:page");
shapeContext.xmlWriter().addAttribute("draw:name", "");
KoElementReference elementRef;
elementRef.saveOdf(&shapeContext.xmlWriter(), KoElementReference::DrawId);
shapeContext.xmlWriter().addAttribute("draw:master-page-name", "Default");
saveOdf(shapeContext);
shapeContext.xmlWriter().endElement(); // draw:page
contentTmpWriter.endElement(); // office:drawing
contentTmpWriter.endElement(); // office:body
mainStyles.saveOdfStyles(KoGenStyles::DocumentAutomaticStyles, docWriter);
// And now we can copy over the contents from the tempfile to the real one
contentTmpFile.seek(0);
docWriter->addCompleteElement(&contentTmpFile);
docWriter->endElement(); // Root element
docWriter->endDocument();
delete docWriter;
if (!store->close())
return false;
manifestWriter->addManifestEntry("content.xml", "text/xml");
if (! mainStyles.saveOdfStylesDotXml(store, manifestWriter)) {
return false;
}
manifestWriter->addManifestEntry("settings.xml", "text/xml");
if (! shapeContext.saveDataCenter(documentContext.odfStore.store(), documentContext.odfStore.manifestWriter()))
return false;
// Write out manifest file
if (!odfStore.closeManifestWriter()) {
dbgImage << "closing manifestWriter failed";
return false;
}
return true;
}
bool KisShapeSelection::loadSelection(KoStore* store)
{
KoOdfReadStore odfStore(store);
QString errorMessage;
odfStore.loadAndParse(errorMessage);
if (!errorMessage.isEmpty()) {
qDebug() << errorMessage;
return false;
}
KoXmlElement contents = odfStore.contentDoc().documentElement();
// qDebug() <<"Start loading OASIS document..." << contents.text();
// qDebug() <<"Start loading OASIS contents..." << contents.lastChild().localName();
// qDebug() <<"Start loading OASIS contents..." << contents.lastChild().namespaceURI();
// qDebug() <<"Start loading OASIS contents..." << contents.lastChild().isElement();
KoXmlElement body(KoXml::namedItemNS(contents, KoXmlNS::office, "body"));
if (body.isNull()) {
qDebug() << "No office:body found!";
//setErrorMessage( i18n( "Invalid OASIS document. No office:body tag found." ) );
return false;
}
body = KoXml::namedItemNS(body, KoXmlNS::office, "drawing");
if (body.isNull()) {
qDebug() << "No office:drawing found!";
//setErrorMessage( i18n( "Invalid OASIS document. No office:drawing tag found." ) );
return false;
}
KoXmlElement page(KoXml::namedItemNS(body, KoXmlNS::draw, "page"));
if (page.isNull()) {
qDebug() << "No office:drawing found!";
//setErrorMessage( i18n( "Invalid OASIS document. No draw:page tag found." ) );
return false;
}
KoXmlElement * master = 0;
if (odfStore.styles().masterPages().contains("Standard"))
master = odfStore.styles().masterPages().value("Standard");
else if (odfStore.styles().masterPages().contains("Default"))
master = odfStore.styles().masterPages().value("Default");
else if (! odfStore.styles().masterPages().empty())
master = odfStore.styles().masterPages().begin().value();
if (master) {
const KoXmlElement *style = odfStore.styles().findStyle(
master->attributeNS(KoXmlNS::style, "page-layout-name", QString()));
KoPageLayout pageLayout;
pageLayout.loadOdf(*style);
setSize(QSizeF(pageLayout.width, pageLayout.height));
} else {
kWarning() << "No master page found!";
return false;
}
KoOdfLoadingContext context(odfStore.styles(), odfStore.store());
KoShapeLoadingContext shapeContext(context, 0);
KoXmlElement layerElement;
forEachElement(layerElement, context.stylesReader().layerSet()) {
if (!loadOdf(layerElement, shapeContext)) {
kWarning() << "Could not load vector layer!";
return false;
}
}
KoXmlElement child;
forEachElement(child, page) {
KoShape * shape = KoShapeRegistry::instance()->createShapeFromOdf(child, shapeContext);
if (shape) {
addShape(shape);
}
}
return true;
}
void KisShapeSelection::setUpdatesEnabled(bool enabled)
{
m_model->setUpdatesEnabled(enabled);
}
bool KisShapeSelection::updatesEnabled() const
{
return m_model->updatesEnabled();
}
KUndo2Command* KisShapeSelection::resetToEmpty()
{
return new KisTakeAllShapesCommand(this, true);
}
bool KisShapeSelection::isEmpty() const
{
return !m_model->count();
}
QPainterPath KisShapeSelection::outlineCache() const
{
return m_outline;
}
bool KisShapeSelection::outlineCacheValid() const
{
return true;
}
void KisShapeSelection::recalculateOutlineCache()
{
QList<KoShape*> shapesList = shapes();
QPainterPath outline;
foreach(KoShape * shape, shapesList) {
QTransform shapeMatrix = shape->absoluteTransformation(0);
outline = outline.united(shapeMatrix.map(shape->outline()));
}
QTransform resolutionMatrix;
resolutionMatrix.scale(m_image->xRes(), m_image->yRes());
m_outline = resolutionMatrix.map(outline);
}
void KisShapeSelection::paintComponent(QPainter& painter, const KoViewConverter& converter, KoShapePaintingContext &)
{
Q_UNUSED(painter);
Q_UNUSED(converter);
}
void KisShapeSelection::renderToProjection(KisPaintDeviceSP projection)
{
Q_ASSERT(projection);
Q_ASSERT(m_image);
QRectF boundingRect = outlineCache().boundingRect();
renderSelection(projection, boundingRect.toAlignedRect());
}
void KisShapeSelection::renderToProjection(KisPaintDeviceSP projection, const QRect& r)
{
Q_ASSERT(projection);
renderSelection(projection, r);
}
void KisShapeSelection::renderSelection(KisPaintDeviceSP projection, const QRect& r)
{
Q_ASSERT(projection);
Q_ASSERT(m_image);
const qint32 MASK_IMAGE_WIDTH = 256;
const qint32 MASK_IMAGE_HEIGHT = 256;
QImage polygonMaskImage(MASK_IMAGE_WIDTH, MASK_IMAGE_HEIGHT, QImage::Format_ARGB32);
QPainter maskPainter(&polygonMaskImage);
maskPainter.setRenderHint(QPainter::Antialiasing, true);
// Break the mask up into chunks so we don't have to allocate a potentially very large QImage.
for (qint32 x = r.x(); x < r.x() + r.width(); x += MASK_IMAGE_WIDTH) {
for (qint32 y = r.y(); y < r.y() + r.height(); y += MASK_IMAGE_HEIGHT) {
maskPainter.fillRect(polygonMaskImage.rect(), Qt::black);
maskPainter.translate(-x, -y);
maskPainter.fillPath(outlineCache(), Qt::white);
maskPainter.translate(x, y);
qint32 rectWidth = qMin(r.x() + r.width() - x, MASK_IMAGE_WIDTH);
qint32 rectHeight = qMin(r.y() + r.height() - y, MASK_IMAGE_HEIGHT);
KisRectIteratorSP rectIt = projection->createRectIteratorNG(QRect(x, y, rectWidth, rectHeight));
do {
(*rectIt->rawData()) = qRed(polygonMaskImage.pixel(rectIt->x() - x, rectIt->y() - y));
} while (rectIt->nextPixel());
}
}
}
KoShapeManager* KisShapeSelection::shapeManager() const
{
return m_canvas->shapeManager();
}
KisShapeSelectionFactory::KisShapeSelectionFactory()
: KoShapeFactoryBase("KisShapeSelection", "selection shape container")
{
setHidden(true);
}
void KisShapeSelection::moveX(qint32 x)
{
foreach (KoShape* shape, shapeManager()->shapes()) {
if (shape != this) {
QPointF pos = shape->position();
shape->setPosition(QPointF(pos.x() + x/m_image->xRes(), pos.y()));
}
}
}
void KisShapeSelection::moveY(qint32 y)
{
foreach (KoShape* shape, shapeManager()->shapes()) {
if (shape != this) {
QPointF pos = shape->position();
shape->setPosition(QPointF(pos.x(), pos.y() + y/m_image->yRes()));
}
}
}
// TODO same code as in vector layer, refactor!
KUndo2Command* KisShapeSelection::transform(const QTransform &transform) {
QList<KoShape*> shapes = m_canvas->shapeManager()->shapes();
if(shapes.isEmpty()) return 0;
QTransform realTransform = m_converter->documentToView() *
transform * m_converter->viewToDocument();
QList<QTransform> oldTransformations;
QList<QTransform> newTransformations;
// this code won't work if there are shapes, that inherit the transformation from the parent container.
// the chart and tree shapes are examples for that, but they aren't used in krita and there are no other shapes like that.
foreach(const KoShape* shape, shapes) {
QTransform oldTransform = shape->transformation();
oldTransformations.append(oldTransform);
if (dynamic_cast<const KoShapeGroup*>(shape)) {
newTransformations.append(oldTransform);
} else {
QTransform globalTransform = shape->absoluteTransformation(0);
QTransform localTransform = globalTransform * realTransform * globalTransform.inverted();
newTransformations.append(localTransform*oldTransform);
}
}
return new KoShapeTransformCommand(shapes, oldTransformations, newTransformations);
}
|
yxl/emscripten-calligra-mobile
|
krita/ui/flake/kis_shape_selection.cpp
|
C++
|
gpl-2.0
| 14,572
|
/**
Native Code Examples
Copyright (C) 2014 Bassel Bakr
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.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
**/
#include "shuffle.h"
void myCallback(char *cc)
{
usleep(2500);
printf("%s\n", cc);
};
int main()
{
IResultListener *listener = calloc(1, sizeof(IResultListener));
listener->newResult = myCallback;
shuffle("10", 20, listener);
}
|
Bassel-Bakr/Native-Code-Samples
|
shuffle.c
|
C
|
gpl-2.0
| 2,480
|
/*
* display_gen.c
* Pi4U
*
* Created by Panagiotis Hadjidoukas on 1/1/14.
* Copyright 2014 ETH Zurich. All rights reserved.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "gnuplot_i.h"
int display = 1;
gnuplot_ctrl * g = NULL;
char *BASENAME;
// "curgen"
// "samples"
// "seeds"
void display_onegen_db_dim(int Gen, int Dim)
{
FILE *fp;
char fname[256];
static int once = 0;
sprintf(fname, "%s_%03d.txt", BASENAME, Gen);
fp = fopen(fname, "r");
if (fp == NULL) {
printf("No file %s\n", fname);
return;
}
fclose(fp);
// if (g != NULL) {
// gnuplot_close(g);
// }
// g = gnuplot_init();
if (!once) {
gnuplot_cmd(g, "set view map");
gnuplot_cmd(g, "set size ratio 1");
gnuplot_cmd(g, "set palette rgbformulae 22,13,-31");
gnuplot_cmd(g, "unset key");
//gnuplot_cmd(g, "set pointsize 2");
once = 1;
}
// set terminal x11 [reset] <n> [[no]enhanced] [font <fontspec>] [title "<string>"] [[no]persist] [[no]raise] [close]
if (!display) {
gnuplot_cmd(g, "set terminal png");
gnuplot_cmd(g, "set output \"%s.png\"", fname);
}
int i, j;
// gnuplot_cmd(g, "splot [-10:10][-10:10] \"%s\" using 2:3:4 with points pt 7 palette", fname);
// gnuplot_cmd(g, "splot \"%s\" using 3:2:4 with points pt 7 palette", fname);
for (i = 1; i <= Dim; i++) {
for (j = i+1; j <=Dim; j++) {
char using_str[64], title_str[64];
sprintf(using_str, "using %d:%d:%d ", i,j,Dim+1);
sprintf(title_str, "\"%d_%d_%d\"", Gen,i,j);
gnuplot_cmd(g, "set term x11 %d persist title %s", i*Dim+j, title_str);
#if 0
if ((i == 1)&&(j==2))
gnuplot_cmd(g, "splot [-20:0][-15:0] \"%s\" %s with points pt 7 palette", fname, using_str);
if ((i == 1)&&(j==3))
gnuplot_cmd(g, "splot [-20:0][-15:5] \"%s\" %s with points pt 7 palette", fname, using_str);
if ((i == 2)&&(j==3))
gnuplot_cmd(g, "splot [-15:0][-15:5] \"%s\" %s with points pt 7 palette", fname, using_str);
#else
gnuplot_cmd(g, "splot \"%s\" %s with points pt 7 palette", fname, using_str);
#endif
// gnuplot_cmd(g, "splot [-6:6][-6:6] \"%s\" %s with points pt 7 palette", fname, using_str);
// usleep(1000*500);
sleep(2);
}
}
// sleep(5);
}
void display_curgen_db(int Gen, int NGens)
{
FILE *fp;
char fname[256];
static int once = 0;
sprintf(fname, "%s_%03d.txt", BASENAME, Gen);
fp = fopen(fname, "r");
if (fp == NULL) {
printf("No file %s\n", fname);
return;
}
fclose(fp);
// if (g != NULL) {
// gnuplot_close(g);
// }
// g = gnuplot_init();
if (!once) {
gnuplot_cmd(g, "set view map");
gnuplot_cmd(g, "set size ratio 1");
gnuplot_cmd(g, "set palette rgbformulae 22,13,-31");
gnuplot_cmd(g, "unset key");
gnuplot_cmd(g, "set pointsize 1");
once = 1;
}
// set terminal x11 [reset] <n> [[no]enhanced] [font <fontspec>] [title "<string>"] [[no]persist] [[no]raise] [close]
/*
if ((Gen == 1) || (Gen == NGens))
gnuplot_cmd(g, "set term x11 %d persist", Gen);
else
gnuplot_cmd(g, "set term x11 %d", Gen);
if ((Gen > 2)
gnuplot_cmd(g, "set term x11 %d close", Gen-1);
gnuplot_cmd(g, "splot [-10:10][-10:10] \"%s\" with points pt 7 palette", fname);
usleep(1000*500);
*/
if (!display) {
gnuplot_cmd(g, "set terminal png");
gnuplot_cmd(g, "set output \"%s.png\"", fname);
}
if (Gen == 0) {
if (display) gnuplot_cmd(g, "set term x11 %d persist", Gen);
gnuplot_cmd(g, "splot [-10:10][-10:10] \"%s\" with points pt 7 palette", fname);
}
else if (Gen == 1) {
//if (display) gnuplot_cmd(g, "set term x11 %d persist", Gen);
gnuplot_cmd(g, "splot [-10:10][-10:10] \"%s\" with points pt 7 palette", fname);
} else {
gnuplot_cmd(g, "splot [-10:10][-10:10] \"%s\" with points pt 7 palette", fname);
}
usleep(1000*500);
// sleep(5);
}
void display_curgen_db_single(int Gen, int p1, int p2, int Dim, int NGens)
{
FILE *fp;
char fname[256];
static int once = 0;
sprintf(fname, "%s_%03d.txt", BASENAME, Gen);
fp = fopen(fname, "r");
if (fp == NULL) {
printf("No file %s\n", fname);
return;
}
fclose(fp);
if (!once) {
gnuplot_cmd(g, "set view map");
gnuplot_cmd(g, "set size ratio 1");
gnuplot_cmd(g, "set palette rgbformulae 22,13,-31");
gnuplot_cmd(g, "unset key");
gnuplot_cmd(g, "set pointsize 1");
once = 1;
// gnuplot_cmd(g, "set logscale y");
}
if (!display) {
gnuplot_cmd(g, "set terminal png");
gnuplot_cmd(g, "set output \"%s.png\"", fname);
}
int i = p1;
int j = p2;
{
char using_str[64], title_str[64];
sprintf(using_str, "using %d:%d:%d ", i,j,Dim+1);
sprintf(title_str, "\"%d_%d_%d\"", Gen,i,j);
#if 1
gnuplot_cmd(g, "set term x11 %d persist title %s", i*Dim+j, title_str);
#else
gnuplot_cmd(g, "set term x11 %d persist title %s", Gen, title_str);
#endif
// gnuplot_cmd(g, "splot [1e2:1e6][1e-6:1e-3]\"%s\" %s with points pt 7 palette", fname, using_str);
gnuplot_cmd(g, "splot \"%s\" %s with points pt 7 palette", fname, using_str);
// gnuplot_cmd(g, "splot [-6:6][-6:6]\"%s\" %s with points pt 7 palette", fname, using_str);
}
sleep(1);
}
int main(int argc, char *argv[])
{
int ngen = 0;
int dim = 2;
int p1 = 1, p2 = 2;
if (argc == 1) {
printf("usage: %s <basefilename> <ngen> <dim> [index i] [index j]\n", argv[0]);
exit(1);
}
BASENAME = argv[1];
if (argc >= 3) ngen = atoi(argv[2]);
if (argc >= 4) dim = atoi(argv[3]);
if (argc == 6) {
p1 = atoi(argv[4]);
p2 = atoi(argv[5]);
}
g = gnuplot_init();
#if 0
int i;
for (i = 0; i <= ngen; i++) {
// for (i = ngen; i <= ngen; i++) {
// display_curgen_db(i, ngen);
display_curgen_db_single(i, p1, p2, dim, ngen);
//sleep(5);
}
#else
display_onegen_db_dim(ngen, dim);
#endif
//sleep(100);
gnuplot_close(g);
return 0;
}
|
cselab/pi4u
|
inference/ABC_SubSim/display_gen.c
|
C
|
gpl-2.0
| 5,832
|
<?php
/**
* PESCMS for PHP 5.4+
*
* Copyright (c) 2014 PESCMS (http://www.pescms.com)
*
* For the full copyright and license information, please view
* the file LICENSE.md that was distributed with this source code.
*/
namespace Core\Slice;
/**
* 切片接口
* 定义规则,所有切片实现需要继承
* Interface interfaceSlice
* @package Slice
*/
interface interfaceSlice
{
public function before();
public function after();
}
|
lazyphp/PESCMS-TEAM
|
Core/Slice/interfaceSlice.php
|
PHP
|
gpl-2.0
| 457
|
cmd_sound/drivers/built-in.o := /home/flint/android/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.6/bin/arm-linux-androideabi-ld -EL -r -o sound/drivers/built-in.o sound/drivers/opl3/built-in.o sound/drivers/opl4/built-in.o sound/drivers/mpu401/built-in.o sound/drivers/vx/built-in.o sound/drivers/pcsp/built-in.o ; scripts/mod/modpost sound/drivers/built-in.o
|
lindsaytheflint/stone
|
sound/drivers/.built-in.o.cmd
|
Batchfile
|
gpl-2.0
| 371
|
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
DROP SCHEMA IF EXISTS `cunxiaoo_houtai` ;
CREATE SCHEMA IF NOT EXISTS `cunxiaoo_houtai` DEFAULT CHARACTER SET utf8 ;
USE `cunxiaoo_houtai` ;
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`addressdic`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`addressdic` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`addressdic` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`province` VARCHAR(45) NULL DEFAULT NULL,
`city` VARCHAR(45) NULL DEFAULT NULL,
`area` VARCHAR(45) NULL DEFAULT NULL,
`township` VARCHAR(45) NULL DEFAULT NULL,
`town` VARCHAR(45) NULL DEFAULT NULL,
`villiage` VARCHAR(45) NULL DEFAULT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`addressdic` (`id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`user` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`user` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '标识',
`sid` VARCHAR(200) NULL DEFAULT NULL COMMENT '证件号码',
`name` VARCHAR(45) NOT NULL,
`dob` DATE NULL DEFAULT NULL,
`status` VARCHAR(45) NULL DEFAULT NULL,
`contact_id` VARCHAR(45) NULL DEFAULT NULL,
`province` VARCHAR(45) NULL DEFAULT NULL,
`city` VARCHAR(45) NULL DEFAULT NULL,
`area` VARCHAR(45) NULL DEFAULT NULL,
`postcode` VARCHAR(45) NULL DEFAULT NULL,
`address` VARCHAR(200) NULL DEFAULT NULL,
`mobile` VARCHAR(45) NULL DEFAULT NULL,
`email` VARCHAR(45) NULL DEFAULT NULL,
`phone` VARCHAR(45) NULL DEFAULT NULL,
`webid1` VARCHAR(100) NULL DEFAULT NULL,
`webid2` VARCHAR(100) NULL DEFAULT NULL,
`webid3` VARCHAR(100) NULL DEFAULT NULL,
`nickname` VARCHAR(200) NULL DEFAULT NULL,
`remark` VARCHAR(500) NULL DEFAULT NULL,
`aboutme` VARCHAR(500) NULL DEFAULT NULL,
`photo` VARCHAR(200) NULL DEFAULT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`user` (`id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`auth`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`auth` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`auth` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NULL DEFAULT NULL,
`login_name` VARCHAR(50) NOT NULL,
`pwd` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `auth_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `cunxiaoo_houtai`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`auth` (`id` ASC);
CREATE UNIQUE INDEX `login_name_UNIQUE` ON `cunxiaoo_houtai`.`auth` (`login_name` ASC);
CREATE INDEX `user_id_idx` ON `cunxiaoo_houtai`.`auth` (`user_id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`bankact`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`bankact` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`bankact` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NULL DEFAULT NULL,
`type` CHAR(1) NULL DEFAULT NULL,
`account` VARCHAR(45) NULL DEFAULT NULL,
`account_name` VARCHAR(100) NULL DEFAULT NULL,
`account_remark` VARCHAR(100) NULL DEFAULT NULL,
`address` VARCHAR(45) NULL DEFAULT NULL,
`bank` VARCHAR(45) NULL DEFAULT NULL,
`school_id` VARCHAR(45) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `bankact_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `cunxiaoo_houtai`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`bankact` (`id` ASC);
CREATE INDEX `bankact_user_id_idx` ON `cunxiaoo_houtai`.`bankact` (`user_id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`contact`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`contact` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`contact` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NULL DEFAULT NULL,
`school_id` INT(11) NULL DEFAULT NULL,
`phone` VARCHAR(45) NULL DEFAULT NULL,
`contact` VARCHAR(45) NULL DEFAULT NULL,
`type` VARCHAR(45) NULL DEFAULT NULL COMMENT '描述与联系人关系 如 本人, 父亲,母亲,校长,姐姐',
`remark` VARCHAR(45) NULL DEFAULT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`contact` (`id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`school`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`school` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`school` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '标识',
`name` VARCHAR(45) NOT NULL,
`brief` TEXT NULL DEFAULT NULL COMMENT '学校介绍\n',
`address` VARCHAR(100) NULL DEFAULT NULL,
`bankact_address` VARCHAR(45) NULL DEFAULT NULL,
`province` VARCHAR(45) NULL DEFAULT NULL,
`city` VARCHAR(45) NULL DEFAULT NULL,
`area` VARCHAR(45) NULL DEFAULT NULL,
`main_contact` VARCHAR(100) NULL DEFAULT NULL,
`other_contact` VARCHAR(45) NULL DEFAULT NULL,
`cooperate` BIT(1) NOT NULL,
`facilities` VARCHAR(100) NULL DEFAULT NULL COMMENT '设施',
`size` VARCHAR(100) NULL DEFAULT NULL COMMENT '规模',
`comments` VARCHAR(500) NULL DEFAULT NULL COMMENT '评价',
`feedback_note` VARCHAR(50) NULL DEFAULT NULL,
`student_contact` VARCHAR(100) NULL DEFAULT NULL COMMENT '学生代表联系信息',
PRIMARY KEY (`id`, `name`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`school` (`id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`schoolsch`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`schoolsch` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`schoolsch` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`school_id` INT(11) NOT NULL,
`grade` VARCHAR(45) NOT NULL,
`semester` VARCHAR(45) NOT NULL,
`year` INT(11) NOT NULL,
`startdate` DATE NOT NULL,
`enddate` DATE NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `schsch_school_id`
FOREIGN KEY (`school_id`)
REFERENCES `cunxiaoo_houtai`.`school` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`schoolsch` (`id` ASC);
CREATE INDEX `schsch_school_id_idx` ON `cunxiaoo_houtai`.`schoolsch` (`school_id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`donation`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`donation` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`donation` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`student_id` INT(11) NOT NULL COMMENT 'userid',
`school_id` INT(11) NOT NULL,
`schoolsch_id` INT(11) NOT NULL,
`student_class` VARCHAR(45) NULL DEFAULT NULL,
`donator_id` INT(11) NOT NULL,
`status` CHAR(2) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `donation_schsch_id`
FOREIGN KEY (`schoolsch_id`)
REFERENCES `cunxiaoo_houtai`.`schoolsch` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `donation_sch_id`
FOREIGN KEY (`school_id`)
REFERENCES `cunxiaoo_houtai`.`school` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `donator_id`
FOREIGN KEY (`donator_id`)
REFERENCES `cunxiaoo_houtai`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `student_id`
FOREIGN KEY (`student_id`)
REFERENCES `cunxiaoo_houtai`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`donation` (`id` ASC);
CREATE INDEX `donation_sch_id_idx` ON `cunxiaoo_houtai`.`donation` (`school_id` ASC);
CREATE INDEX `donation_schsch_id_idx` ON `cunxiaoo_houtai`.`donation` (`schoolsch_id` ASC);
CREATE INDEX `student_id_idx` ON `cunxiaoo_houtai`.`donation` (`student_id` ASC);
CREATE INDEX `donator_id_idx` ON `cunxiaoo_houtai`.`donation` (`donator_id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`feedback`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`feedback` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`feedback` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`student_id` INT(11) NULL DEFAULT NULL COMMENT '关于学生的回访或来信',
`school_id` INT(11) NULL DEFAULT NULL COMMENT '关于学校的反馈记录\n',
`type` CHAR(1) NULL DEFAULT NULL COMMENT '来信或是回访',
`context` TEXT NOT NULL,
`brief` VARCHAR(100) NULL DEFAULT NULL,
`subject` VARCHAR(50) NULL DEFAULT NULL,
`status` CHAR(1) NULL DEFAULT NULL,
`author_id` INT(11) NULL DEFAULT NULL,
`submit_on` DATETIME NULL DEFAULT NULL,
`remark` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `feedback_author_id`
FOREIGN KEY (`author_id`)
REFERENCES `cunxiaoo_houtai`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`feedback` (`id` ASC);
CREATE INDEX `feedback_author_id_idx` ON `cunxiaoo_houtai`.`feedback` (`author_id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`feedback_reply`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`feedback_reply` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`feedback_reply` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`feedback_id` INT(11) NOT NULL,
`author_id` INT(11) NOT NULL,
`content` VARCHAR(100) NULL DEFAULT NULL,
`submiton` DATETIME NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fbreply_author_id`
FOREIGN KEY (`author_id`)
REFERENCES `cunxiaoo_houtai`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `feedback_id`
FOREIGN KEY (`feedback_id`)
REFERENCES `cunxiaoo_houtai`.`feedback` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`feedback_reply` (`id` ASC);
CREATE INDEX `feedback_id_idx` ON `cunxiaoo_houtai`.`feedback_reply` (`feedback_id` ASC);
CREATE INDEX `fbreply_author_id_idx` ON `cunxiaoo_houtai`.`feedback_reply` (`author_id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`log`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`log` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`log` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '标识',
`user_id` VARCHAR(200) NULL DEFAULT NULL COMMENT '证件号码',
`rec_id` INT(11) NULL DEFAULT NULL,
`action` VARCHAR(100) NOT NULL,
`message` TEXT NULL DEFAULT NULL,
`when` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`, `action`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`log` (`id` ASC);
-- -----------------------------------------------------
-- Table `cunxiaoo_houtai`.`user_role`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cunxiaoo_houtai`.`user_role` ;
CREATE TABLE IF NOT EXISTS `cunxiaoo_houtai`.`user_role` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT ' ',
`user_id` INT(11) NULL DEFAULT NULL,
`role` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `user_id`
FOREIGN KEY (`user_id`)
REFERENCES `cunxiaoo_houtai`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE UNIQUE INDEX `id_UNIQUE` ON `cunxiaoo_houtai`.`user_role` (`id` ASC);
CREATE INDEX `user_id_idx` ON `cunxiaoo_houtai`.`user_role` (`user_id` ASC);
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
huming0618/OneSchool
|
src/Setup/Create.sql
|
SQL
|
gpl-2.0
| 12,665
|
package es.uniovi.asw.persistence;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import com.mongodb.MongoTimeoutException;
import es.uniovi.asw.infraestructura.model.User;
public class UserDb {
private SortedMap<String, User> table = new TreeMap<String, User>();
private String[] usuarios = {"UO232346","UO227799","UO227982",
"UO227648","UO191154","UO229803",
"UO232334","UO224927","UO212948"};
PersistenceService service;
public UserDb() {
try {
service = FactoryService.getPersistenceService();
List<User> users = service.getUsuarios();
for(User u:users) {
table.put(u.getName(), u);
}
}
catch(MongoTimeoutException e) {
crearUsuariosNoBD();
}
}
private void crearUsuariosNoBD() {
User u = null;
for(int i=0; i<9; i++) {
u = new User(usuarios[i], usuarios[i]);
table.put(usuarios[i], u);
}
}
public void addUser(String name, String password) {
try {
service.saveUsuario(name, password, 0, 0, 0, 0, 0);
} catch (NullPointerException e) {
table.put(name, new User(name, password));
}
}
public Integer size() {
return table.size();
}
public User lookup(String name) {
try {
return service.findUserByLogin(name);
} catch (NullPointerException e) {
return table.get(name);
}
}
public Boolean login(String name, String password) {
User usuario;
try {
usuario = service.findUserByLogin(name);
} catch (NullPointerException e) {
usuario = lookup(name);
}
if (usuario!=null) {
return usuario.getPassword().equals(password);
} else
return false;
}
}
|
Arquisoft/Trivial1b
|
trivial1bWeb/app/es/uniovi/asw/persistence/UserDb.java
|
Java
|
gpl-2.0
| 1,698
|
showWord(["n. ","son moun fè lè li ap wonfle.<br>"])
|
georgejhunt/HaitiDictionary.activity
|
data/words/wonf.js
|
JavaScript
|
gpl-2.0
| 54
|
# MobileStreamer
|
seok0721/MobileStreamer
|
README.md
|
Markdown
|
gpl-2.0
| 17
|
<div>
<div>
<!--This doesn't properly select the active config-->
Active Config:
<select ng-init="vm.selectedConfig = vm.config_profiles[0]"
ng-model="vm.selectedConfig"
ng-options="x for x in vm.config_profiles"
ng-change="vm.load_fields()"
></select>
</div>
<div>
<table class="table table-striped">
<tr>
<td>ID</td>
<td><input ng-model="vm.config_setting.configuration_profile.id"></td>
</tr>
<tr>
<td>Recordings DB</td>
<td><input ng-model="vm.config_setting.configuration_profile.session_db_path"></td>
</tr>
<tr>
<td>Config Name</td>
<td><input ng-model="vm.config_setting.configuration_profile.name"></td>
</tr>
</table>
<input type="submit" ng-click="vm.save_fields()" value="Save"/>
</div>
</div>
|
donour/racepi
|
python/racepi_config_webapp/static/views/settings/settings.template.html
|
HTML
|
gpl-2.0
| 993
|
#include <FuegoHeatpumpIR.h>
FuegoHeatpumpIR::FuegoHeatpumpIR()
{
static const char PROGMEM model[] PROGMEM = "fuego";
static const char PROGMEM info[] PROGMEM = "{\"mdl\":\"fuego\",\"dn\":\"Fuego\",\"mT\":18,\"xT\":31,\"fs\":3}";
_model = model;
_info = info;
}
void FuegoHeatpumpIR::send(IRSender& IR, uint8_t powerModeCmd, uint8_t operatingModeCmd, uint8_t fanSpeedCmd, uint8_t temperatureCmd, uint8_t swingVCmd, uint8_t swingHCmd)
{
// Sensible defaults for the heat pump mode
uint8_t powerMode = FUEGO_AIRCON1_MODE_ON;
uint8_t operatingMode = FUEGO_AIRCON1_MODE_HEAT;
uint8_t fanSpeed = FUEGO_AIRCON1_FAN_AUTO;
uint8_t temperature = 23;
uint8_t swingV = FUEGO_AIRCON1_VS_SWING;
(void)swingHCmd;
if (powerModeCmd == POWER_OFF)
{
powerMode = FUEGO_AIRCON1_MODE_OFF;
swingVCmd = VDIR_MUP;
}
switch (operatingModeCmd)
{
case MODE_AUTO:
operatingMode = FUEGO_AIRCON1_MODE_AUTO;
break;
case MODE_COOL:
operatingMode = FUEGO_AIRCON1_MODE_COOL;
break;
case MODE_DRY:
operatingMode = FUEGO_AIRCON1_MODE_DRY;
break;
case MODE_FAN:
operatingMode = FUEGO_AIRCON1_MODE_FAN;
break;
}
switch (fanSpeedCmd)
{
case FAN_AUTO:
fanSpeed = FUEGO_AIRCON1_FAN_AUTO;
break;
case FAN_1:
fanSpeed = FUEGO_AIRCON1_FAN1;
break;
case FAN_2:
fanSpeed = FUEGO_AIRCON1_FAN2;
break;
case FAN_3:
fanSpeed = FUEGO_AIRCON1_FAN3;
break;
}
if ( temperatureCmd > 17 && temperatureCmd < 32)
{
temperature = temperatureCmd;
}
switch (swingVCmd)
{
case VDIR_AUTO:
swingV = FUEGO_AIRCON1_VS_AUTO;
break;
case VDIR_SWING:
swingV = FUEGO_AIRCON1_VS_SWING;
break;
case VDIR_UP:
swingV = FUEGO_AIRCON1_VS_UP;
break;
case VDIR_MUP:
swingV = FUEGO_AIRCON1_VS_MUP;
break;
case VDIR_MIDDLE:
swingV = FUEGO_AIRCON1_VS_MIDDLE;
break;
case VDIR_MDOWN:
swingV = FUEGO_AIRCON1_VS_MDOWN;
break;
case VDIR_DOWN:
swingV = FUEGO_AIRCON1_VS_DOWN;
break;
}
sendFuego(IR, powerMode, operatingMode, fanSpeed, temperature, swingV, 0);
}
void FuegoHeatpumpIR::sendFuego(IRSender& IR, uint8_t powerMode, uint8_t operatingMode, uint8_t fanSpeed, uint8_t temperature, uint8_t swingV, uint8_t swingH)
{
uint8_t FuegoTemplate[] = { 0x23, 0xCB, 0x26, 0x01, 0x80, 0x20, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00 };
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13
uint8_t checksum = 0x00;
(void)swingH;
// Set the operatingmode on the template message
FuegoTemplate[5] |= powerMode;
FuegoTemplate[6] |= operatingMode;
// Set the temperature on the template message
FuegoTemplate[7] |= 31 - temperature;
// Set the fan speed and vertical air direction on the template message
FuegoTemplate[8] |= fanSpeed | swingV;
// Calculate the checksum
for (unsigned int i=0; i < (sizeof(FuegoTemplate)-1); i++) {
checksum += FuegoTemplate[i];
}
FuegoTemplate[13] = checksum;
// 38 kHz PWM frequency
IR.setFrequency(38);
// Header
IR.mark(FUEGO_AIRCON1_HDR_MARK);
IR.space(FUEGO_AIRCON1_HDR_SPACE);
// Data
for (unsigned int i=0; i<sizeof(FuegoTemplate); i++) {
IR.sendIRbyte(FuegoTemplate[i], FUEGO_AIRCON1_BIT_MARK, FUEGO_AIRCON1_ZERO_SPACE, FUEGO_AIRCON1_ONE_SPACE);
}
// End mark
IR.mark(FUEGO_AIRCON1_BIT_MARK);
IR.space(0);
}
|
cosmopaco/arduino-heatpumpir
|
FuegoHeatpumpIR.cpp
|
C++
|
gpl-2.0
| 3,528
|
#include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
using namespace std;
typedef long long ll;
inline void calc(ll &N,ll &ret,ll zero,ll two,ll four){
ret -= min(zero,N) * 0LL;
N -= min(zero,N);
ret -= min(two,N) * 2LL;
N -= min(two,N);
ret -= min(four,N) * 4LL;
N -= min(four,N);
}
inline ll compute(ll len,ll N){
if( len & 1LL ){
ll ans = 0LL;
// Pattern 1
ll half = (len*len) / 2LL + 1LL;
if( half >= N ) return 4LL * N;
ll ret = 4LL * half;
N -= half;
ll N_tmp = N;
half--;
ll zero = 0LL;
ll two = ( ( len - 2LL ) / 2LL + 1LL) * 4LL;
ll four = half - ( zero + two );
calc(N,ret,zero,two,four);
ans = ret;
// Pattern 2
ret = 4LL * half;
half++;
N = N_tmp+1;
zero = 4LL;
two = ( ( len - 2LL ) / 2LL ) * 4LL;
four = half - ( zero + two );
calc(N,ret,zero,two,four);
ans = max(ans,ret);
return ans;
} else {
ll half = (len*len) / 2LL;
if( half >= N ) return 4LL * N;
ll ret = 4LL * half;
N -= half;
ll zero = 2LL;
ll two = ( ( len - 2LL ) / 2LL ) * 4LL;
ll four = half - ( zero + two );
calc(N,ret,zero,two,four);
return ret;
}
}
int main(){
ll L,N;
while( cin >> L >> N, L | N ) cout << compute(L,N) << endl;
return 0;
}
|
EndlessCheng/acm-icpc
|
UVa/12520.cpp
|
C++
|
gpl-2.0
| 1,326
|
package com.jeecms.common.web.freemarker;
import freemarker.template.TemplateModelException;
/**
* 非布尔参数异常
*/
@SuppressWarnings("serial")
public class MustDateException extends TemplateModelException {
public MustDateException(String paramName) {
super("The \"" + paramName + "\" parameter must be a date.");
}
}
|
caipiao/Lottery
|
src/com/jeecms/common/web/freemarker/MustDateException.java
|
Java
|
gpl-2.0
| 348
|
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../images/favicon.ico">
<title>メンテナンス</title>
<!-- Bootstrap core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../css/home.css" rel="stylesheet">
<link href="../css/input.css" rel="stylesheet">
<link href="../css/bootstrap-datepicker3.min.css" rel="stylesheet" type="text/css">
<link href="../css/bootstrap-select.css" rel="stylesheet" type="text/css">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="../assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">請求書作成</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="../home.html"><span class="glyphicon glyphicon-dashboard" aria-hidden="true"></span> ダッシュボード</a></li>
<li><a href="../bill/home.html">請求書</a></li>
<li><a href="../estimate/home.html">見積書</a></li>
<li><a href="../order/home.html">注文書</a></li>
<li><a href="../receipt/home.html">領収書</a></li>
<li><a href="../setting.html"><span class="glyphicon glyphicon-cog" aria-hidden="true"></span> 設定</a></li>
<li><a href="../profile.html"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> プロフィール</a></li>
<li><a href="../help.html"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span> ヘルプ</a></li>
<li><a href="../index.html"><span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> ログオフ</a></li>
</ul>
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search...">
</form>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<a href="./register.html" class="btn btn-primary btn-block">新規作成</a>
<ul class="nav nav-sidebar">
</ul>
<ul class="nav nav-sidebar">
<li><a href="./home.html"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> ホーム</a></li>
<li><a href="./created.html"><span class="glyphicon glyphicon-tasks" aria-hidden="true"></span> 作成済み <span class="badge">13</span></a></li>
<li><a href="./send.html"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span> 請求済み <span class="badge">4</span></a></li>
<li><a href="./search.html"><span class="glyphicon glyphicon-search" aria-hidden="true"></span> 請求書検索</a></li>
<li><a href="./export.html"><span class="glyphicon glyphicon-export" aria-hidden="true"></span> 請求書一覧の出力</a></li>
<li><a href="./draft.html"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> 下書き <span class="badge">7</span></a></li>
</ul>
<ul class="nav nav-sidebar">
<li class="active"><a href="#"><span class="glyphicon glyphicon-wrench" aria-hidden="true"></span> メンテナンス <span class="sr-only">(current)</span></a></li>
<li><a href="./template.html"><span class="glyphicon glyphicon-print" aria-hidden="true"></span> テンプレートの編集</a></li>
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h2 class="sub-header">メンテナンス</h2>
<form role="form" class="form-horizontal">
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">会社名</label>
<div class="col-sm-8 col-md-8">
<input type="text" class="form-control" id="subject" placeholder="会社名を入力してください。">
</div>
<div class="col-sm-c col-md-2">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">郵便番号</label>
<div class="col-sm-5 col-md-5 form-inline">
<input type="text" class="form-control" id="subject" placeholder="999" maxlength="3"> - <input type="text" class="form-control" id="subject" placeholder="9999" maxlength="4">
</div>
<div class="col-sm-5 col-md-5">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">都道府県</label>
<div class="col-sm-8 col-md-8">
<select name="prefecture" class="selectpicker">
<optgroup label="北海道・東北">
<option value="1">北海道</option>
<option value="2">青森県</option>
<option value="3">岩手県</option>
<option value="4">宮城県</option>
<option value="5">秋田県</option>
<option value="6">山形県</option>
<option value="7">福島県</option>
</optgroup>
<optgroup label="関東">
<option value="8">茨城県</option>
<option value="9">栃木県</option>
<option value="10">群馬県</option>
<option value="11">埼玉県</option>
<option value="12">千葉県</option>
<option value="13">東京都</option>
<option value="14">神奈川県</option>
</optgroup>
<optgroup label="甲信越・北陸">
<option value="15">新潟県</option>
<option value="16">富山県</option>
<option value="17">石川県</option>
<option value="18">福井県</option>
<option value="19">山梨県</option>
<option value="20">長野県</option>
</optgroup>
<optgroup label="東海">
<option value="21">岐阜県</option>
<option value="22">静岡県</option>
<option value="23">愛知県</option>
<option value="24">三重県</option>
</optgroup>
<optgroup label="関西">
<option value="25">滋賀県</option>
<option value="26">京都府</option>
<option value="27">大阪府</option>
<option value="28">兵庫県</option>
<option value="29">奈良県</option>
<option value="30">和歌山県</option>
</optgroup>
<optgroup label="中国">
<option value="31">鳥取県</option>
<option value="32">島根県</option>
<option value="33">岡山県</option>
<option value="34">広島県</option>
<option value="35">山口県</option>
</optgroup>
<optgroup label="四国">
<option value="36">徳島県</option>
<option value="37">香川県</option>
<option value="38">愛媛県</option>
<option value="39">高知県</option>
</optgroup>
<optgroup label="九州・沖縄">
<option value="40">福岡県</option>
<option value="41">佐賀県</option>
<option value="42">長崎県</option>
<option value="43">熊本県</option>
<option value="44">大分県</option>
<option value="45">宮崎県</option>
<option value="46">鹿児島県</option>
<option value="47">沖縄県</option>
</optgroup>
</select>
</div>
<div class="col-sm-c col-md-2">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">住所1</label>
<div class="col-sm-8 col-md-8">
<input type="text" class="form-control" id="subject" placeholder="住所を入力してください。">
</div>
<div class="col-sm-c col-md-2">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">住所2</label>
<div class="col-sm-8 col-md-8">
<input type="text" class="form-control" id="subject" placeholder="住所を入力してください。">
</div>
<div class="col-sm-c col-md-2">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">ビル・建物名</label>
<div class="col-sm-8 col-md-8">
<input type="text" class="form-control" id="subject" placeholder="住所を入力してください。">
</div>
<div class="col-sm-c col-md-2">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">電話番号</label>
<div class="col-sm-8 col-md-8">
<input type="text" class="form-control" id="subject" placeholder="000-0000-0000">
</div>
<div class="col-sm-c col-md-2">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">担当者</label>
<div class="col-sm-8 col-md-8">
<input type="text" class="form-control" id="subject" placeholder="担当者を入力してください。">
</div>
<div class="col-sm-c col-md-2">
</div>
</div>
<div class="form-group">
<label for="subject" class="col-sm-2 col-md-2 text-right control-label">振込口座</label>
<div class="col-sm-4 col-md-4 form-inline">
<input type="text" class="form-control" id="subject" placeholder="銀行名">
<input type="radio" value="1" name="gender" id="man">
<label for="man">普通</label>
<input type="radio" value="1" name="gender" id="man">
<label for="man">当座</label>
</div>
<div class="col-sm-4 col-md-4 text-left">
<input type="text" class="form-control" id="subject" placeholder="振込口座を入力してください。">
</div>
<div class="col-sm-2 col-md-2">
</div>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary">登録</button>
</div>
</form>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<!-- Just to make our placeholder images work. Don't actually copy the next line! -->
<script src="../assets/js/vendor/holder.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../assets/js/ie10-viewport-bug-workaround.js"></script>
<script src="../js/bootstrap-datepicker.js"></script>
<script src="../locales/bootstrap-datepicker.ja.min.js"></script>
<script src="../js/bootstrap-select.js"></script>
<script type="text/javascript">
$(function() {
$('.datepicker').datepicker({
format: 'yyyy/mm/dd'
, language: 'ja'
});
$('.selectpicker').selectpicker({
'selectedText': 'cat'
});
});
</script>
</body>
</html>
|
jwam/bill
|
bill/maintenance.html
|
HTML
|
gpl-2.0
| 13,680
|
/*****************************************************************************\
halftoner.cpp : Implimentation for the Halftoner class
Copyright (c) 1996 - 2001, Hewlett-Packard Co.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of Hewlett-Packard 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 AUTHOR "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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PATENT INFRINGEMENT; 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.
\*****************************************************************************/
//===========================================================================
//
// Filename : halftoner.cpp
//
// Module : Open Source Imaging
//
// Description : This file contains the constructor and destructor for
// the Halftoner class, which performs color-matching and
// halftoning.
//
// Detailed Description:
//
// The only member functions needed are Process(inputRaster)
// and Restart (used to skip white space and for new page).
//
// Configurability required in Slimhost driver is reflected in the
// parameters to the constructor:
// 1. SystemServices encapsulates memory management for platform-independence
// 2. PrintMode contains info on resolution and other properties
// 3. iInputWidth tells how many pixels input per plane
// 4. iNumRows is 1 except for mixed-resolution cases
// 5. HiResFactor is for boosting base resolution, e.g. 2 if 600 dpi grid
// (base res assumed to be 300)
//
// These structures, together with the variable StartPlane (designating
// K or C in the fixed ordering KCMY), are accessed by the Translator
// component of the driver, in order to properly package the data in
// the printer command language.
//============================================================================
#include "header.h"
#include "hptypes.h"
#include "halftoner.h"
APDK_BEGIN_NAMESPACE
Halftoner::Halftoner
(
SystemServices* pSys,
PrintMode* pPM,
unsigned int iInputWidth,
unsigned int iNumRows[],
unsigned int HiResFactor,
BOOL matrixbased
) : ColorPlaneCount(pPM->dyeCount),
InputWidth(iInputWidth),
ResBoost(HiResFactor),
pSS(pSys),
nNextRaster(0),
fBlackFEDResPtr(pPM->BlackFEDTable),
fColorFEDResPtr(pPM->ColorFEDTable),
iColor(0),
iRow(0),
iPlane(0),
tempBuffer(NULL),
tempBuffer2(NULL),
hold_random(0),
usematrix(matrixbased)
{
unsigned int i;
int j,k,PlaneSize;
constructor_error = NO_ERROR;
StartPlane = K; // most common case
if (ColorPlaneCount == 3) // CMY pen
{
StartPlane=C;
NumRows[K] = ColorDepth[K] = OutputWidth[K] = 0;
}
EndPlane=Y; // most common case
if (ColorPlaneCount == 6)
{
EndPlane = Mlight;
}
if (ColorPlaneCount == 1)
{
EndPlane = K;
}
AdjustedInputWidth = InputWidth;
if (AdjustedInputWidth % 8)
{
AdjustedInputWidth += 8 - (AdjustedInputWidth % 8);
}
// init arrays
for (i = StartPlane; i < (ColorPlaneCount + StartPlane); i++)
{
ColorDepth[i]= pPM->ColorDepth[i];
NumRows[i]=iNumRows[i];
OutputWidth[i] = AdjustedInputWidth * NumRows[i] * ResBoost;
}
for (;i < (unsigned)MAXCOLORPLANES; i++)
{
NumRows[i] = ColorDepth[i] = OutputWidth[i] = 0;
}
oddbits = AdjustedInputWidth - InputWidth;
///////////////////////////////////////////////////////////////////////////
for (i=0; i <= Mlight; i++)
{
ErrBuff[i]=NULL;
}
for (i=StartPlane; i <= EndPlane; i++)
{
ErrBuff[i] = (short*)pSS->AllocMem((OutputWidth[i] + 2) * sizeof(short));
if (ErrBuff[i] == NULL)
{
goto MemoryError;
}
}
if (OutputWidth[K] > AdjustedInputWidth)
// need to expand input data (easier than expanding bit-pixels after) on K row
{
tempBuffer = (BYTE*) pSS->AllocMem(OutputWidth[K]);
if (tempBuffer == NULL)
{
goto MemoryError;
}
if (EndPlane > Y)
{
tempBuffer2 = (BYTE*) pSS->AllocMem(OutputWidth[K]);
if (tempBuffer2 == NULL)
{
goto MemoryError;
}
}
}
Restart(); // this zeroes buffers and sets nextraster counter
// allocate output buffers
for (i = 0; i < (unsigned)MAXCOLORPLANES; i++)
{
for (j = 0; j < MAXCOLORROWS; j++)
{
for (k = 0; k < MAXCOLORDEPTH; k++)
{
ColorPlane[i][j][k] = NULL;
}
}
}
for (i=StartPlane; i < (ColorPlaneCount+StartPlane); i++)
{
for (j=0; j < NumRows[i]; j++)
{
for (k=0; k < ColorDepth[i]; k++)
{
PlaneSize= OutputWidth[i]/8 + // doublecheck ... should already be divisble by 8
((OutputWidth[i] % 8)!=0);
ColorPlane[i][j][k] = (BYTE*) pSS->AllocMem(PlaneSize);
if (ColorPlane[i][j] == NULL)
{
goto MemoryError;
}
memset(ColorPlane[i][j][k], 0, PlaneSize);
}
}
}
PlaneSize = (OutputWidth[0] + 7) / 8;
if (PlaneSize > 0)
{
originalKData = (BYTE*) pSS->AllocMem(PlaneSize);
if (originalKData == NULL)
{
goto MemoryError;
}
memset(originalKData, 0, PlaneSize);
}
return;
MemoryError:
constructor_error=ALLOCMEM_ERROR;
FreeBuffers();
for (i=0; i < ColorPlaneCount; i++)
{
for (j=0; j < NumRows[i]; j++)
{
for (k=0; k < ColorDepth[i]; k++)
{
if (ColorPlane[i][j][k])
{
pSS->FreeMemory(ColorPlane[i][j][k]);
}
}
}
}
if (originalKData)
{
pSS->FreeMemory(originalKData);
}
} //Halftoner
Halftoner::~Halftoner()
{
DBG1("destroying Halftoner \n");
FreeBuffers();
for (int i=0; i < MAXCOLORPLANES; i++)
{
for (int j=0; j < NumRows[i]; j++)
{
for (int k=0; k < ColorDepth[i]; k++)
{
if (ColorPlane[i][j][k])
{
pSS->FreeMemory(ColorPlane[i][j][k]);
}
}
}
}
if (originalKData)
{
pSS->FreeMemory(originalKData);
}
} //~Halftoner
void Halftoner::Restart()
{
nNextRaster = 0;
for (unsigned int i = StartPlane; i <= EndPlane; i++)
{
memset(ErrBuff[i], 0, (OutputWidth[i]+2) * sizeof(short));
}
started = FALSE;
} //Restart
void Halftoner::Flush()
{
if (!started)
{
return;
}
Restart();
} //Flush
void Halftoner::FreeBuffers()
{
for (unsigned int i = StartPlane; i <= EndPlane; i++)
{
pSS->FreeMemory(ErrBuff[i]);
}
if (tempBuffer)
{
pSS->FreeMemory(tempBuffer);
}
if (tempBuffer2)
{
pSS->FreeMemory(tempBuffer2);
}
} //FreeBuffers
// dumb horizontal doubling (tripling, etc.) for resolution-boost prior to halftoning
void Halftoner::PixelMultiply(unsigned char* buffer, unsigned int width, unsigned int factor)
{
if (factor == 1)
{
return;
}
for (int j = (int)(width-1); j >= 0; j--)
{
unsigned int iOffset = j * factor;
for (unsigned int k = 0; k < factor; k++)
{
buffer[iOffset + k] = buffer[j];
}
}
} //PixelMultiply
BYTE* Halftoner::NextOutputRaster(COLORTYPE rastercolor)
{
if (rastercolor == COLORTYPE_COLOR)
{
if (iRastersReady == 0)
{
return NULL;
}
if (iColor == (ColorPlaneCount+StartPlane))
{
return NULL;
}
if (iPlane == ColorDepth[iColor])
{
iPlane = 0;
iRow++;
return NextOutputRaster(rastercolor);
}
if (iRow == NumRows[iColor])
{
iRow = 0;
iColor++;
return NextOutputRaster(rastercolor);
}
iRastersDelivered++;
iRastersReady--;
return ColorPlane[iColor][iRow][iPlane++];
}
else
{
return NULL;
}
} //NextOutputRaster
BOOL Halftoner::LastPlane()
{
return ((iColor == (ColorPlaneCount+StartPlane-1)) &&
(iRow == (unsigned int)(NumRows[iColor] - 1)) &&
(iPlane == ColorDepth[iColor]) // was pre-incremented
);
} //LastPlane
BOOL Halftoner::FirstPlane()
{
return ((iColor == StartPlane) &&
(iRow == 0) &&
(iPlane == 1) // was pre-incremented
);
} //FirstPlane
unsigned int Halftoner::GetOutputWidth(COLORTYPE rastercolor)
// return size of data in the plane being delivered (depends on iRastersDelivered)
// (will be used in connection with compression seedrow)
{
if (rastercolor == COLORTYPE_COLOR)
{
unsigned int colorplane, tmp;
// figure out which colorplane we're on
unsigned int rasterd = iRastersDelivered;
// we come after increment of iRastersDelivered
if (rasterd>0)
{
rasterd--;
}
tmp = (unsigned int)(NumRows[0]*ColorDepth[0]);
if (rasterd < tmp)
{
colorplane = 0;
}
// have to count up to possible 6th plane;
// but we'll save code by assuming sizes of C,M,Y (Cl,Ml) are all same
else
{
colorplane = 1;
}
int temp = (OutputWidth[colorplane] + 7) / 8;
return temp;
}
else
{
return 0;
}
} //GetOutputWidth
unsigned int Halftoner::GetMaxOutputWidth(COLORTYPE rastercolor)
// This is needed by Configure, since the output-width for Halftoner is variable
// depending on the colorplane
{
if (rastercolor == COLORTYPE_COLOR)
{
unsigned int max=0;
for (unsigned int i=StartPlane; i <= EndPlane; i++)
{
if (OutputWidth[i] > max)
{
max = OutputWidth[i];
}
}
return (max / 8) + ((max % 8)!=0);
}
else
{
return 0;
}
} //GetMaxOutputWidth
unsigned int Halftoner::PlaneCount()
{
unsigned int count=0;
for (int i = 0; i < MAXCOLORPLANES; i++)
{
count += NumRows[i] * ColorDepth[i];
}
return count;
} //PlaneCount
void Halftoner::CleanOddBits(unsigned int iColor, unsigned int iRow)
{
int index = (OutputWidth[iColor]/8)-1;
for (int i=0; i < ColorDepth[iColor]; i++)
{
BYTE lastbyte0 = ColorPlane[iColor][iRow][i][index];
lastbyte0 = lastbyte0 >> oddbits;
lastbyte0 = lastbyte0 << oddbits;
ColorPlane[iColor][iRow][i][index] = lastbyte0;
}
} //CleanOddBits
APDK_END_NAMESPACE
|
matrumz/RPi_Custom_Files
|
Printing/hplip-3.15.2/prnt/hpijs/halftoner.cpp
|
C++
|
gpl-2.0
| 11,709
|
/* Copyright (c) 2014, The 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/kernel.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <linux/clk.h>
#include <linux/regulator/consumer.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/of.h>
#include <soc/qcom/clock-local2.h>
#include <soc/qcom/clock-pll.h>
#include <soc/qcom/clock-voter.h>
#include <linux/clk/msm-clock-generic.h>
#include <linux/regulator/rpm-smd-regulator.h>
#include <dt-bindings/clock/msm-clocks-8936.h>
#include "clock.h"
enum {
GCC_BASE,
APCS_C0_PLL_BASE,
APCS_C1_PLL_BASE,
APCS_CCI_PLL_BASE,
N_BASES,
};
static void __iomem *virt_bases[N_BASES];
static void __iomem *virt_dbgbase;
#define GCC_REG_BASE(x) (void __iomem *)(virt_bases[GCC_BASE] + (x))
#define GPLL0_MODE 0x21000
#define GPLL0_L_VAL 0x21004
#define GPLL0_M_VAL 0x21008
#define GPLL0_N_VAL 0x2100C
#define GPLL0_USER_CTL 0x21010
#define GPLL0_CONFIG_CTL 0x21014
#define GPLL0_STATUS 0x2101C
#define GPLL1_MODE 0x20000
#define GPLL1_L_VAL 0x20004
#define GPLL1_M_VAL 0x20008
#define GPLL1_N_VAL 0x2000C
#define GPLL1_USER_CTL 0x20010
#define GPLL1_CONFIG_CTL 0x20014
#define GPLL1_STATUS 0x2001C
#define GPLL2_MODE 0x4A000
#define GPLL2_L_VAL 0x4A004
#define GPLL2_M_VAL 0x4A008
#define GPLL2_N_VAL 0x4A00C
#define GPLL2_USER_CTL 0x4A010
#define GPLL2_CONFIG_CTL 0x4A014
#define GPLL2_STATUS 0x4A01C
#define GPLL3_MODE 0x22000
#define GPLL3_L_VAL 0x22004
#define GPLL3_M_VAL 0x22008
#define GPLL3_N_VAL 0x2200C
#define GPLL3_USER_CTL 0x22010
#define GPLL3_CONFIG_CTL 0x22014
#define GPLL3_STATUS 0x2201C
#define GPLL4_MODE 0x24000
#define GPLL4_L_VAL 0x24004
#define GPLL4_M_VAL 0x24008
#define GPLL4_N_VAL 0x2400C
#define GPLL4_USER_CTL 0x24010
#define GPLL4_CONFIG_CTL 0x24014
#define GPLL4_STATUS 0x2401C
#define GPLL6_MODE 0x37000
#define GPLL6_L_VAL 0x37004
#define GPLL6_M_VAL 0x37008
#define GPLL6_N_VAL 0x3700C
#define GPLL6_USER_CTL 0x37010
#define GPLL6_CONFIG_CTL 0x37014
#define GPLL6_STATUS 0x3701C
#define MSS_CFG_AHB_CBCR 0x49000
#define MSS_Q6_BIMC_AXI_CBCR 0x49004
#define USB_HS_BCR 0x41000
#define USB_HS_SYSTEM_CBCR 0x41004
#define USB_HS_AHB_CBCR 0x41008
#define USB_HS_SYSTEM_CMD_RCGR 0x41010
#define USB_FS_BCR 0x3F000
#define USB_FS_SYSTEM_CMD_RCGR 0x3F010
#define USB_FS_IC_CMD_RCGR 0x3F034
#define USB_FS_AHB_CBCR 0x3F008
#define USB_FS_IC_CBCR 0x3F030
#define USB_FS_SYSTEM_CBCR 0x3F004
#define USB2A_PHY_SLEEP_CBCR 0x4102C
#define SDCC1_APPS_CMD_RCGR 0x42004
#define SDCC1_APPS_CBCR 0x42018
#define SDCC1_AHB_CBCR 0x4201C
#define SDCC2_APPS_CMD_RCGR 0x43004
#define SDCC2_APPS_CBCR 0x43018
#define SDCC2_AHB_CBCR 0x4301C
#define BLSP1_AHB_CBCR 0x01008
#define BLSP1_QUP1_SPI_APPS_CBCR 0x02004
#define BLSP1_QUP1_I2C_APPS_CBCR 0x02008
#define BLSP1_QUP1_I2C_APPS_CMD_RCGR 0x0200C
#define BLSP1_QUP2_I2C_APPS_CMD_RCGR 0x03000
#define BLSP1_QUP3_I2C_APPS_CMD_RCGR 0x04000
#define BLSP1_QUP4_I2C_APPS_CMD_RCGR 0x05000
#define BLSP1_QUP5_I2C_APPS_CMD_RCGR 0x06000
#define BLSP1_QUP6_I2C_APPS_CMD_RCGR 0x07000
#define BLSP1_QUP1_SPI_APPS_CMD_RCGR 0x02024
#define BLSP1_UART1_APPS_CBCR 0x0203C
#define BLSP1_UART1_APPS_CMD_RCGR 0x02044
#define BLSP1_QUP2_SPI_APPS_CBCR 0x0300C
#define BLSP1_QUP2_I2C_APPS_CBCR 0x03010
#define BLSP1_QUP2_SPI_APPS_CMD_RCGR 0x03014
#define BLSP1_UART2_APPS_CBCR 0x0302C
#define BLSP1_UART2_APPS_CMD_RCGR 0x03034
#define BLSP1_QUP3_SPI_APPS_CBCR 0x0401C
#define BLSP1_QUP3_I2C_APPS_CBCR 0x04020
#define BLSP1_QUP3_SPI_APPS_CMD_RCGR 0x04024
#define BLSP1_QUP4_SPI_APPS_CBCR 0x0501C
#define BLSP1_QUP4_I2C_APPS_CBCR 0x05020
#define BLSP1_QUP4_SPI_APPS_CMD_RCGR 0x05024
#define BLSP1_QUP5_SPI_APPS_CBCR 0x0601C
#define BLSP1_QUP5_I2C_APPS_CBCR 0x06020
#define BLSP1_QUP5_SPI_APPS_CMD_RCGR 0x06024
#define BLSP1_QUP6_SPI_APPS_CBCR 0x0701C
#define BLSP1_QUP6_I2C_APPS_CBCR 0x07020
#define BLSP1_QUP6_SPI_APPS_CMD_RCGR 0x07024
#define PDM_AHB_CBCR 0x44004
#define PDM2_CBCR 0x4400C
#define PDM2_CMD_RCGR 0x44010
#define PRNG_AHB_CBCR 0x13004
#define BOOT_ROM_AHB_CBCR 0x1300C
#define CRYPTO_CMD_RCGR 0x16004
#define CRYPTO_CBCR 0x1601C
#define CRYPTO_AXI_CBCR 0x16020
#define CRYPTO_AHB_CBCR 0x16024
#define GCC_XO_DIV4_CBCR 0x30034
#define GFX_TBU_CBCR 0x12010
#define VENUS_TBU_CBCR 0x12014
#define MDP_TBU_CBCR 0x1201C
#define APSS_TCU_CBCR 0x12018
#define GFX_TCU_CBCR 0x12020
#define MSS_TBU_AXI_CBCR 0x12024
#define MSS_TBU_GSS_AXI_CBCR 0x12028
#define MSS_TBU_Q6_AXI_CBCR 0x1202C
#define JPEG_TBU_CBCR 0x12034
#define SMMU_CFG_CBCR 0x12038
#define VFE_TBU_CBCR 0x1203C
#define CPP_TBU_CBCR 0x12040
#define MDP_RT_TBU_CBCR 0x1204C
#define GTCU_AHB_CBCR 0x12044
#define GTCU_AHB_BRIDGE_CBCR 0x12094
#define APCS_GPLL_ENA_VOTE 0x45000
#define APCS_CLOCK_BRANCH_ENA_VOTE 0x45004
#define APCS_CLOCK_SLEEP_ENA_VOTE 0x45008
#define APCS_SMMU_CLOCK_BRANCH_ENA_VOTE 0x4500C
#define APSS_AHB_CMD_RCGR 0x46000
#define GCC_DEBUG_CLK_CTL 0x74000
#define CLOCK_FRQ_MEASURE_CTL 0x74004
#define CLOCK_FRQ_MEASURE_STATUS 0x74008
#define GCC_PLLTEST_PAD_CFG 0x7400C
#define GP1_CBCR 0x08000
#define GP1_CMD_RCGR 0x08004
#define GP2_CBCR 0x09000
#define GP2_CMD_RCGR 0x09004
#define GP3_CBCR 0x0A000
#define GP3_CMD_RCGR 0x0A004
#define SPDM_JPEG0_CBCR 0x2F028
#define SPDM_MDP_CBCR 0x2F02C
#define SPDM_VCODEC0_CBCR 0x2F034
#define SPDM_VFE0_CBCR 0x2F038
#define SPDM_GFX3D_CBCR 0x2F03C
#define SPDM_PCLK0_CBCR 0x2F044
#define SPDM_CSI0_CBCR 0x2F048
#define VCODEC0_CMD_RCGR 0x4C000
#define VENUS0_BCR 0x4C014
#define VENUS0_VCODEC0_CBCR 0x4C01C
#define VENUS0_AHB_CBCR 0x4C020
#define VENUS0_AXI_CBCR 0x4C024
#define VENUS0_CORE0_VCODEC0_CBCR 0x4C02C
#define VENUS0_CORE1_VCODEC0_CBCR 0x4C034
#define PCLK0_CMD_RCGR 0x4D000
#define PCLK1_CMD_RCGR 0x4D0B8
#define MDP_CMD_RCGR 0x4D014
#define VSYNC_CMD_RCGR 0x4D02C
#define BYTE0_CMD_RCGR 0x4D044
#define BYTE1_CMD_RCGR 0x4D0B0
#define ESC0_CMD_RCGR 0x4D05C
#define ESC1_CMD_RCGR 0x4D0A8
#define MDSS_BCR 0x4D074
#define MDSS_AHB_CBCR 0x4D07C
#define MDSS_AXI_CBCR 0x4D080
#define MDSS_PCLK0_CBCR 0x4D084
#define MDSS_PCLK1_CBCR 0x4D0A4
#define MDSS_MDP_CBCR 0x4D088
#define MDSS_VSYNC_CBCR 0x4D090
#define MDSS_BYTE0_CBCR 0x4D094
#define MDSS_BYTE1_CBCR 0x4D0A0
#define MDSS_ESC0_CBCR 0x4D098
#define MDSS_ESC1_CBCR 0x4D09C
#define CSI0PHYTIMER_CMD_RCGR 0x4E000
#define CAMSS_CSI0PHYTIMER_CBCR 0x4E01C
#define CSI1PHYTIMER_CMD_RCGR 0x4F000
#define CAMSS_CSI1PHYTIMER_CBCR 0x4F01C
#define CSI0_CMD_RCGR 0x4E020
#define CAMSS_CSI0_CBCR 0x4E03C
#define CAMSS_CSI0_AHB_CBCR 0x4E040
#define CAMSS_CSI0PHY_CBCR 0x4E048
#define CAMSS_CSI0RDI_CBCR 0x4E050
#define CAMSS_CSI0PIX_CBCR 0x4E058
#define CSI1_CMD_RCGR 0x4F020
#define CAMSS_CSI1_CBCR 0x4F03C
#define CAMSS_CSI1_AHB_CBCR 0x4F040
#define CAMSS_CSI1PHY_CBCR 0x4F048
#define CAMSS_CSI1RDI_CBCR 0x4F050
#define CAMSS_CSI1PIX_CBCR 0x4F058
#define CSI2_CMD_RCGR 0x3C020
#define CAMSS_CSI2_CBCR 0x3C03C
#define CAMSS_CSI2_AHB_CBCR 0x3C040
#define CAMSS_CSI2PHY_CBCR 0x3C048
#define CAMSS_CSI2RDI_CBCR 0x3C050
#define CAMSS_CSI2PIX_CBCR 0x3C058
#define CAMSS_ISPIF_AHB_CBCR 0x50004
#define CCI_CMD_RCGR 0x51000
#define CAMSS_CCI_CBCR 0x51018
#define CAMSS_CCI_AHB_CBCR 0x5101C
#define MCLK0_CMD_RCGR 0x52000
#define CAMSS_MCLK0_CBCR 0x52018
#define MCLK1_CMD_RCGR 0x53000
#define CAMSS_MCLK1_CBCR 0x53018
#define MCLK2_CMD_RCGR 0x5C000
#define CAMSS_MCLK2_CBCR 0x5C018
#define CAMSS_GP0_CMD_RCGR 0x54000
#define CAMSS_GP0_CBCR 0x54018
#define CAMSS_GP1_CMD_RCGR 0x55000
#define CAMSS_GP1_CBCR 0x55018
#define CAMSS_TOP_AHB_CBCR 0x5A014
#define CAMSS_AHB_CBCR 0x56004
#define CAMSS_MICRO_AHB_CBCR 0x5600C
#define CAMSS_MICRO_BCR 0x56008
#define JPEG0_CMD_RCGR 0x57000
#define CAMSS_JPEG0_BCR 0x57018
#define CAMSS_JPEG0_CBCR 0x57020
#define CAMSS_JPEG_AHB_CBCR 0x57024
#define CAMSS_JPEG_AXI_CBCR 0x57028
#define VFE0_CMD_RCGR 0x58000
#define CPP_CMD_RCGR 0x58018
#define CAMSS_VFE_BCR 0x58030
#define CAMSS_VFE0_CBCR 0x58038
#define CAMSS_CPP_CBCR 0x5803C
#define CAMSS_CPP_AHB_CBCR 0x58040
#define CAMSS_VFE_AHB_CBCR 0x58044
#define CAMSS_VFE_AXI_CBCR 0x58048
#define CAMSS_CSI_VFE0_BCR 0x5804C
#define CAMSS_CSI_VFE0_CBCR 0x58050
#define GFX3D_CMD_RCGR 0x59000
#define OXILI_GFX3D_CBCR 0x59020
#define OXILI_GMEM_CBCR 0x59024
#define OXILI_AHB_CBCR 0x59028
#define CAMSS_TOP_AHB_CMD_RCGR 0x5A000
#define BIMC_GFX_CBCR 0x31024
#define BIMC_GPU_CBCR 0x31040
#define APCS_CCI_PLL_MODE 0x00000
#define APCS_CCI_PLL_L_VAL 0x00004
#define APCS_CCI_PLL_M_VAL 0x00008
#define APCS_CCI_PLL_N_VAL 0x0000C
#define APCS_CCI_PLL_USER_CTL 0x00010
#define APCS_CCI_PLL_CONFIG_CTL 0x00014
#define APCS_CCI_PLL_STATUS 0x0001C
#define APCS_C0_PLL_MODE 0x00000
#define APCS_C0_PLL_L_VAL 0x00004
#define APCS_C0_PLL_M_VAL 0x00008
#define APCS_C0_PLL_N_VAL 0x0000C
#define APCS_C0_PLL_USER_CTL 0x00010
#define APCS_C0_PLL_CONFIG_CTL 0x00014
#define APCS_C0_PLL_STATUS 0x0001C
#define APCS_C1_PLL_MODE 0x00000
#define APCS_C1_PLL_L_VAL 0x00004
#define APCS_C1_PLL_M_VAL 0x00008
#define APCS_C1_PLL_N_VAL 0x0000C
#define APCS_C1_PLL_USER_CTL 0x00010
#define APCS_C1_PLL_CONFIG_CTL 0x00014
#define APCS_C1_PLL_STATUS 0x0001C
/* Mux source select values */
#define gcc_xo_source_val 0
#define xo_a_clk_source_val 0
#define gpll0_out_main_source_val 1
#define gpll0_out_aux_source_val 5
#define gpll0_misc_source_val 2
#define gpll1_out_main_source_val 1
#define gpll2_out_main_source_val 2
#define gpll2_out_aux_source_val 3
#define gpll2_gfx3d_source_val 4
#define gpll3_out_main_source_val 2
#define gpll3_out_aux_source_val 4
#define gpll4_out_main_source_val 2
#define gpll6_out_main_source_val 1
#define gpll6_mclk_source_val 3
#define dsi0_phypll_mm_source_val 1
#define FIXDIV(div) (div ? (2 * (div) - 1) : (0))
#define F(f, s, div, m, n) \
{ \
.freq_hz = (f), \
.src_clk = &s.c, \
.m_val = (m), \
.n_val = ~((n)-(m)) * !!(n), \
.d_val = ~(n),\
.div_src_val = BVAL(4, 0, (int)FIXDIV(div)) \
| BVAL(10, 8, s##_source_val), \
}
#define F_APCS_PLL(f, l, m, n, pre_div, post_div, vco) \
{ \
.freq_hz = (f), \
.l_val = (l), \
.m_val = (m), \
.n_val = (n), \
.pre_div_val = BVAL(12, 12, (pre_div)), \
.post_div_val = BVAL(9, 8, (post_div)), \
.vco_val = BVAL(29, 28, (vco)), \
}
#define F_MDSS(f, s, div, m, n) \
{ \
.freq_hz = (f), \
.m_val = (m), \
.n_val = ~((n)-(m)) * !!(n), \
.d_val = ~(n),\
.div_src_val = BVAL(4, 0, (int)FIXDIV(div)) \
| BVAL(10, 8, s##_mm_source_val), \
}
#define VDD_DIG_FMAX_MAP1(l1, f1) \
.vdd_class = &vdd_dig, \
.fmax = (unsigned long[VDD_DIG_NUM]) { \
[VDD_DIG_##l1] = (f1), \
}, \
.num_fmax = VDD_DIG_NUM
#define VDD_DIG_FMAX_MAP2(l1, f1, l2, f2) \
.vdd_class = &vdd_dig, \
.fmax = (unsigned long[VDD_DIG_NUM]) { \
[VDD_DIG_##l1] = (f1), \
[VDD_DIG_##l2] = (f2), \
}, \
.num_fmax = VDD_DIG_NUM
#define VDD_DIG_FMAX_MAP3(l1, f1, l2, f2, l3, f3) \
.vdd_class = &vdd_dig, \
.fmax = (unsigned long[VDD_DIG_NUM]) { \
[VDD_DIG_##l1] = (f1), \
[VDD_DIG_##l2] = (f2), \
[VDD_DIG_##l3] = (f3), \
}, \
.num_fmax = VDD_DIG_NUM
#define VDD_DIG_FMAX_MAP4(l1, f1, l2, f2, l3, f3, l4, f4) \
.vdd_class = &vdd_dig, \
.fmax = (unsigned long[VDD_DIG_NUM]) { \
[VDD_DIG_##l1] = (f1), \
[VDD_DIG_##l2] = (f2), \
[VDD_DIG_##l3] = (f3), \
[VDD_DIG_##l4] = (f4), \
}, \
.num_fmax = VDD_DIG_NUM
enum vdd_dig_levels {
VDD_DIG_NONE,
VDD_DIG_LOW,
VDD_DIG_NOMINAL,
VDD_DIG_NOMINAL_PLUS,
VDD_DIG_HIGH,
VDD_DIG_NUM
};
static int vdd_corner[] = {
RPM_REGULATOR_CORNER_NONE, /* VDD_DIG_NONE */
RPM_REGULATOR_CORNER_SVS_SOC, /* VDD_DIG_LOW */
RPM_REGULATOR_CORNER_NORMAL, /* VDD_DIG_NOMINAL */
RPM_REGULATOR_CORNER_TURBO, /* VDD_DIG_NOMINAL_PLUS */
RPM_REGULATOR_CORNER_SUPER_TURBO, /* VDD_DIG_HIGH */
};
static DEFINE_VDD_REGULATORS(vdd_dig, VDD_DIG_NUM, 1, vdd_corner, NULL);
DEFINE_EXT_CLK(gcc_xo, NULL);
DEFINE_EXT_CLK(xo_a_clk, NULL);
DEFINE_EXT_CLK(rpm_debug_clk, NULL);
DEFINE_CLK_DUMMY(wcnss_m_clk, 0);
enum vdd_sr2_pll_levels {
VDD_SR2_PLL_OFF,
VDD_SR2_PLL_SVS,
VDD_SR2_PLL_NOM,
VDD_SR2_PLL_TUR,
VDD_SR2_PLL_NUM,
};
static int vdd_sr2_levels[] = {
0, RPM_REGULATOR_CORNER_NONE, /* VDD_SR2_PLL_OFF */
1800000, RPM_REGULATOR_CORNER_SVS_SOC, /* VDD_SR2_PLL_SVS */
1800000, RPM_REGULATOR_CORNER_NORMAL, /* VDD_SR2_PLL_NOM */
1800000, RPM_REGULATOR_CORNER_SUPER_TURBO, /* VDD_SR2_PLL_TUR */
};
static DEFINE_VDD_REGULATORS(vdd_sr2_pll, VDD_SR2_PLL_NUM, 2,
vdd_sr2_levels, NULL);
enum vdd_hf_pll_levels {
VDD_HF_PLL_OFF,
VDD_HF_PLL_SVS,
VDD_HF_PLL_NOM,
VDD_HF_PLL_TUR,
VDD_HF_PLL_NUM,
};
static int vdd_hf_levels[] = {
0, RPM_REGULATOR_CORNER_NONE, /* VDD_HF_PLL_OFF */
1800000, RPM_REGULATOR_CORNER_SVS_SOC, /* VDD_HF_PLL_SVS */
1800000, RPM_REGULATOR_CORNER_NORMAL, /* VDD_HF_PLL_NOM */
1800000, RPM_REGULATOR_CORNER_SUPER_TURBO, /* VDD_HF_PLL_TUR */
};
static DEFINE_VDD_REGULATORS(vdd_hf_pll, VDD_HF_PLL_NUM, 2,
vdd_hf_levels, NULL);
static struct pll_freq_tbl apcs_cci_pll_freq[] = {
F_APCS_PLL(403200000, 21, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(595200000, 31, 0x0, 0x1, 0x0, 0x0, 0x0),
};
static struct pll_clk a53ss_cci_pll = {
.mode_reg = (void __iomem *)APCS_CCI_PLL_MODE,
.l_reg = (void __iomem *)APCS_CCI_PLL_L_VAL,
.m_reg = (void __iomem *)APCS_CCI_PLL_M_VAL,
.n_reg = (void __iomem *)APCS_CCI_PLL_N_VAL,
.config_reg = (void __iomem *)APCS_CCI_PLL_USER_CTL,
.status_reg = (void __iomem *)APCS_CCI_PLL_STATUS,
.freq_tbl = apcs_cci_pll_freq,
.masks = {
.vco_mask = BM(29, 28),
.pre_div_mask = BIT(12),
.post_div_mask = BM(9, 8),
.mn_en_mask = BIT(24),
.main_output_mask = BIT(0),
},
.base = &virt_bases[APCS_CCI_PLL_BASE],
.c = {
.parent = &xo_a_clk.c,
.dbg_name = "a53ss_cci_pll",
.ops = &clk_ops_sr2_pll,
.vdd_class = &vdd_sr2_pll,
.fmax = (unsigned long [VDD_SR2_PLL_NUM]) {
[VDD_SR2_PLL_SVS] = 1000000000,
[VDD_SR2_PLL_NOM] = 1900000000,
},
.num_fmax = VDD_SR2_PLL_NUM,
CLK_INIT(a53ss_cci_pll.c),
},
};
static struct pll_freq_tbl apcs_c0_pll_freq[] = {
F_APCS_PLL( 998400000, 52, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1113600000, 58, 0x0, 0x1, 0x0, 0x0, 0x0),
};
static struct pll_clk a53ss_c0_pll = {
.mode_reg = (void __iomem *)APCS_C0_PLL_MODE,
.l_reg = (void __iomem *)APCS_C0_PLL_L_VAL,
.m_reg = (void __iomem *)APCS_C0_PLL_M_VAL,
.n_reg = (void __iomem *)APCS_C0_PLL_N_VAL,
.config_reg = (void __iomem *)APCS_C0_PLL_USER_CTL,
.status_reg = (void __iomem *)APCS_C0_PLL_STATUS,
.freq_tbl = apcs_c0_pll_freq,
.masks = {
.vco_mask = BM(29, 28),
.pre_div_mask = BIT(12),
.post_div_mask = BM(9, 8),
.mn_en_mask = BIT(24),
.main_output_mask = BIT(0),
},
.base = &virt_bases[APCS_C0_PLL_BASE],
.c = {
.parent = &xo_a_clk.c,
.dbg_name = "a53ss_c0_pll",
.ops = &clk_ops_sr2_pll,
.vdd_class = &vdd_sr2_pll,
.fmax = (unsigned long [VDD_SR2_PLL_NUM]) {
[VDD_SR2_PLL_SVS] = 1000000000,
[VDD_SR2_PLL_NOM] = 1900000000,
},
.num_fmax = VDD_SR2_PLL_NUM,
CLK_INIT(a53ss_c0_pll.c),
},
};
static struct pll_freq_tbl apcs_c1_pll_freq[] = {
F_APCS_PLL( 652800000, 34, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL( 691200000, 36, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL( 729600000, 38, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL( 806400000, 42, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL( 844800000, 44, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL( 883200000, 46, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL( 960000000, 50, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL( 998400000, 52, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1036800000, 54, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1113600000, 58, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1190400000, 62, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1267200000, 66, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1344000000, 70, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1420800000, 74, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1497600000, 78, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1536000000, 80, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1574400000, 82, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1612800000, 84, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1632000000, 85, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1651200000, 86, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1689600000, 88, 0x0, 0x1, 0x0, 0x0, 0x0),
F_APCS_PLL(1708800000, 89, 0x0, 0x1, 0x0, 0x0, 0x0),
};
static struct pll_clk a53ss_c1_pll = {
.mode_reg = (void __iomem *)APCS_C1_PLL_MODE,
.l_reg = (void __iomem *)APCS_C1_PLL_L_VAL,
.m_reg = (void __iomem *)APCS_C1_PLL_M_VAL,
.n_reg = (void __iomem *)APCS_C1_PLL_N_VAL,
.config_reg = (void __iomem *)APCS_C1_PLL_USER_CTL,
.status_reg = (void __iomem *)APCS_C1_PLL_STATUS,
.freq_tbl = apcs_c1_pll_freq,
.masks = {
.vco_mask = BM(29, 28),
.pre_div_mask = BIT(12),
.post_div_mask = BM(9, 8),
.mn_en_mask = BIT(24),
.main_output_mask = BIT(0),
},
.base = &virt_bases[APCS_C1_PLL_BASE],
.c = {
.parent = &xo_a_clk.c,
.dbg_name = "a53ss_c1_pll",
.ops = &clk_ops_sr2_pll,
.vdd_class = &vdd_hf_pll,
.fmax = (unsigned long [VDD_HF_PLL_NUM]) {
[VDD_HF_PLL_SVS] = 1000000000,
[VDD_HF_PLL_NOM] = 2000000000,
},
.num_fmax = VDD_HF_PLL_NUM,
CLK_INIT(a53ss_c1_pll.c),
},
};
static unsigned int soft_vote_gpll0;
static struct pll_vote_clk gpll0 = {
.en_reg = (void __iomem *)APCS_GPLL_ENA_VOTE,
.en_mask = BIT(0),
.status_reg = (void __iomem *)GPLL0_STATUS,
.status_mask = BIT(17),
.soft_vote = &soft_vote_gpll0,
.soft_vote_mask = PLL_SOFT_VOTE_PRIMARY,
.base = &virt_bases[GCC_BASE],
.c = {
.parent = &gcc_xo.c,
.rate = 800000000,
.dbg_name = "gpll0",
.ops = &clk_ops_pll_acpu_vote,
CLK_INIT(gpll0.c),
},
};
/* Don't vote for xo if using this clock to allow xo shutdown */
static struct pll_vote_clk gpll0_ao = {
.en_reg = (void __iomem *)APCS_GPLL_ENA_VOTE,
.en_mask = BIT(0),
.status_reg = (void __iomem *)GPLL0_STATUS,
.status_mask = BIT(17),
.soft_vote = &soft_vote_gpll0,
.soft_vote_mask = PLL_SOFT_VOTE_ACPU,
.base = &virt_bases[GCC_BASE],
.c = {
.parent = &xo_a_clk.c,
.rate = 800000000,
.dbg_name = "gpll0_ao",
.ops = &clk_ops_pll_acpu_vote,
CLK_INIT(gpll0_ao.c),
},
};
DEFINE_EXT_CLK(gpll0_out_main, &gpll0.c);
DEFINE_EXT_CLK(gpll0_out_aux, &gpll0.c);
DEFINE_EXT_CLK(gpll0_misc, &gpll0.c);
static struct pll_vote_clk gpll1 = {
.en_reg = (void __iomem *)APCS_GPLL_ENA_VOTE,
.en_mask = BIT(1),
.status_reg = (void __iomem *)GPLL1_STATUS,
.status_mask = BIT(17),
.base = &virt_bases[GCC_BASE],
.c = {
.parent = &gcc_xo.c,
.rate = 614400000,
.dbg_name = "gpll1",
.ops = &clk_ops_pll_vote,
CLK_INIT(gpll1.c),
},
};
DEFINE_EXT_CLK(gpll1_out_main, &gpll1.c);
static struct pll_vote_clk gpll2 = {
.en_reg = (void __iomem *)APCS_GPLL_ENA_VOTE,
.en_mask = BIT(2),
.status_reg = (void __iomem *)GPLL2_STATUS,
.status_mask = BIT(17),
.base = &virt_bases[GCC_BASE],
.c = {
.parent = &gcc_xo.c,
.rate = 930000000,
.dbg_name = "gpll2",
.ops = &clk_ops_pll_vote,
CLK_INIT(gpll2.c),
},
};
DEFINE_EXT_CLK(gpll2_out_main, &gpll2.c);
DEFINE_EXT_CLK(gpll2_out_aux, &gpll2.c);
DEFINE_EXT_CLK(gpll2_gfx3d, &gpll2.c);
static struct pll_vote_clk gpll6 = {
.en_reg = (void __iomem *)APCS_GPLL_ENA_VOTE,
.en_mask = BIT(7),
.status_reg = (void __iomem *)GPLL6_STATUS,
.status_mask = BIT(17),
.base = &virt_bases[GCC_BASE],
.c = {
.parent = &gcc_xo.c,
.rate = 1080000000,
.dbg_name = "gpll6",
.ops = &clk_ops_pll_vote,
CLK_INIT(gpll6.c),
},
};
DEFINE_EXT_CLK(gpll6_out_main, &gpll6.c);
DEFINE_EXT_CLK(gpll6_mclk, &gpll6.c);
static struct pll_vote_clk gpll3 = {
.en_reg = (void __iomem *)APCS_GPLL_ENA_VOTE,
.en_mask = BIT(4),
.status_reg = (void __iomem *)GPLL3_STATUS,
.status_mask = BIT(17),
.base = &virt_bases[GCC_BASE],
.c = {
.parent = &gcc_xo.c,
.rate = 1100000000,
.dbg_name = "gpll3",
.ops = &clk_ops_pll_vote,
CLK_INIT(gpll3.c),
},
};
DEFINE_EXT_CLK(gpll3_out_main, &gpll3.c);
DEFINE_EXT_CLK(gpll3_out_aux, &gpll3.c);
static struct pll_vote_clk gpll4 = {
.en_reg = (void __iomem *)APCS_GPLL_ENA_VOTE,
.en_mask = BIT(5),
.status_reg = (void __iomem *)GPLL4_STATUS,
.status_mask = BIT(17),
.base = &virt_bases[GCC_BASE],
.c = {
.parent = &gcc_xo.c,
.rate = 1200000000,
.dbg_name = "gpll4",
.ops = &clk_ops_pll_vote,
CLK_INIT(gpll4.c),
},
};
DEFINE_EXT_CLK(gpll4_out_main, &gpll4.c);
static struct clk_freq_tbl ftbl_apss_ahb_clk[] = {
F( 19200000, xo_a_clk, 1, 0, 0),
F( 50000000, gpll0_out_main, 16, 0, 0),
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 133330000, gpll0_out_main, 6, 0, 0),
F_END
};
static struct rcg_clk apss_ahb_clk_src = {
.cmd_rcgr_reg = APSS_AHB_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_apss_ahb_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "apss_ahb_clk_src",
.ops = &clk_ops_rcg,
CLK_INIT(apss_ahb_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_top_ahb_clk[] = {
F( 40000000, gpll0_out_main, 10, 1, 2),
F( 80000000, gpll0_out_main, 10, 0, 0),
F_END
};
static struct rcg_clk camss_top_ahb_clk_src = {
.cmd_rcgr_reg = CAMSS_TOP_AHB_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_camss_top_ahb_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "camss_top_ahb_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 40000000, NOMINAL, 80000000),
CLK_INIT(camss_top_ahb_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_csi0_1_2_clk[] = {
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F_END
};
static struct rcg_clk csi0_clk_src = {
.cmd_rcgr_reg = CSI0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_csi0_1_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "csi0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi0_clk_src.c),
},
};
static struct rcg_clk csi1_clk_src = {
.cmd_rcgr_reg = CSI1_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_csi0_1_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "csi1_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi1_clk_src.c),
},
};
static struct rcg_clk csi2_clk_src = {
.cmd_rcgr_reg = CSI2_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_csi0_1_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "csi2_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi2_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_vfe0_clk[] = {
F( 50000000, gpll0_out_main, 16, 0, 0),
F( 80000000, gpll0_out_main, 10, 0, 0),
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 160000000, gpll0_out_main, 5, 0, 0),
F( 177780000, gpll0_out_main, 4.5, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F( 266670000, gpll0_out_main, 3, 0, 0),
F( 320000000, gpll0_out_main, 2.5, 0, 0),
F( 400000000, gpll0_out_main, 2, 0, 0),
F( 465000000, gpll2_out_aux, 2, 0, 0),
F( 480000000, gpll4_out_main, 2.5, 0, 0),
F( 600000000, gpll4_out_main, 2, 0, 0),
F_END
};
static struct rcg_clk vfe0_clk_src = {
.cmd_rcgr_reg = VFE0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_vfe0_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "vfe0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP4(LOW, 200000000, NOMINAL, 400000000, NOMINAL_PLUS, 480000000, HIGH,
600000000),
CLK_INIT(vfe0_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_oxili_gfx3d_clk[] = {
F( 19200000, gcc_xo, 1, 0, 0),
F( 50000000, gpll0_out_main, 16, 0, 0),
F( 80000000, gpll0_out_main, 10, 0, 0),
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 160000000, gpll0_out_main, 5, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F( 220000000, gpll3_out_main, 5, 0, 0),
F( 266670000, gpll0_out_main, 3, 0, 0),
F( 310000000, gpll2_gfx3d, 3, 0, 0),
F( 400000000, gpll0_out_main, 2, 0, 0),
F( 465000000, gpll2_gfx3d, 2, 0, 0),
F( 550000000, gpll3_out_main, 2, 0, 0),
F_END
};
static struct rcg_clk gfx3d_clk_src = {
.cmd_rcgr_reg = GFX3D_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_oxili_gfx3d_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gfx3d_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP4(LOW, 220000000, NOMINAL, 400000000, NOMINAL_PLUS, 465000000, HIGH,
550000000),
CLK_INIT(gfx3d_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_blsp1_qup1_6_i2c_apps_clk[] = {
F( 19200000, gcc_xo, 1, 0, 0),
F( 50000000, gpll0_out_main, 16, 0, 0),
F_END
};
static struct rcg_clk blsp1_qup1_i2c_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP1_I2C_APPS_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_i2c_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup1_i2c_apps_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 50000000),
CLK_INIT(blsp1_qup1_i2c_apps_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_blsp1_qup1_6_spi_apps_clk[] = {
F( 960000, gcc_xo, 10, 1, 2),
F( 4800000, gcc_xo, 4, 0, 0),
F( 9600000, gcc_xo, 2, 0, 0),
F( 16000000, gpll0_out_main, 10, 1, 5),
F( 19200000, gcc_xo, 1, 0, 0),
F( 25000000, gpll0_out_main, 16, 1, 2),
F( 50000000, gpll0_out_main, 16, 0, 0),
F_END
};
static struct rcg_clk blsp1_qup1_spi_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP1_SPI_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_spi_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup1_spi_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 25000000, NOMINAL, 50000000),
CLK_INIT(blsp1_qup1_spi_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup2_i2c_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP2_I2C_APPS_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_i2c_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup2_i2c_apps_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 50000000),
CLK_INIT(blsp1_qup2_i2c_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup2_spi_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP2_SPI_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_spi_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup2_spi_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 25000000, NOMINAL, 50000000),
CLK_INIT(blsp1_qup2_spi_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup3_i2c_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP3_I2C_APPS_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_i2c_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup3_i2c_apps_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 50000000),
CLK_INIT(blsp1_qup3_i2c_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup3_spi_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP3_SPI_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_spi_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup3_spi_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 25000000, NOMINAL, 50000000),
CLK_INIT(blsp1_qup3_spi_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup4_i2c_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP4_I2C_APPS_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_i2c_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup4_i2c_apps_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 50000000),
CLK_INIT(blsp1_qup4_i2c_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup4_spi_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP4_SPI_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_spi_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup4_spi_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 25000000, NOMINAL, 50000000),
CLK_INIT(blsp1_qup4_spi_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup5_i2c_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP5_I2C_APPS_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_i2c_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup5_i2c_apps_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 50000000),
CLK_INIT(blsp1_qup5_i2c_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup5_spi_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP5_SPI_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_spi_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup5_spi_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 25000000, NOMINAL, 50000000),
CLK_INIT(blsp1_qup5_spi_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup6_i2c_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP6_I2C_APPS_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_i2c_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup6_i2c_apps_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 50000000),
CLK_INIT(blsp1_qup6_i2c_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_qup6_spi_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_QUP6_SPI_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_qup1_6_spi_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_qup6_spi_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 25000000, NOMINAL, 50000000),
CLK_INIT(blsp1_qup6_spi_apps_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_blsp1_uart1_6_apps_clk[] = {
F( 3686400, gpll0_out_main, 1, 72, 15625),
F( 7372800, gpll0_out_main, 1, 144, 15625),
F( 14745600, gpll0_out_main, 1, 288, 15625),
F( 16000000, gpll0_out_main, 10, 1, 5),
F( 19200000, gcc_xo, 1, 0, 0),
F( 24000000, gpll0_out_main, 1, 3, 100),
F( 25000000, gpll0_out_main, 16, 1, 2),
F( 32000000, gpll0_out_main, 1, 1, 25),
F( 40000000, gpll0_out_main, 1, 1, 20),
F( 46400000, gpll0_out_main, 1, 29, 500),
F( 48000000, gpll0_out_main, 1, 3, 50),
F( 51200000, gpll0_out_main, 1, 8, 125),
F( 56000000, gpll0_out_main, 1, 7, 100),
F( 58982400, gpll0_out_main, 1, 1152, 15625),
F( 60000000, gpll0_out_main, 1, 3, 40),
F_END
};
static struct rcg_clk blsp1_uart1_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_UART1_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_uart1_6_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_uart1_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 32000000, NOMINAL, 64000000),
CLK_INIT(blsp1_uart1_apps_clk_src.c),
},
};
static struct rcg_clk blsp1_uart2_apps_clk_src = {
.cmd_rcgr_reg = BLSP1_UART2_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_blsp1_uart1_6_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "blsp1_uart2_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 32000000, NOMINAL, 64000000),
CLK_INIT(blsp1_uart2_apps_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_cci_clk[] = {
F( 19200000, gcc_xo, 1, 0, 0),
F( 37500000, gpll0_misc, 1, 3, 64),
F_END
};
static struct rcg_clk cci_clk_src = {
.cmd_rcgr_reg = CCI_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_camss_cci_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "cci_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 19200000, NOMINAL, 37500000),
CLK_INIT(cci_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_gp0_1_clk[] = {
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F_END
};
static struct rcg_clk camss_gp0_clk_src = {
.cmd_rcgr_reg = CAMSS_GP0_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_camss_gp0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "camss_gp0_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(camss_gp0_clk_src.c),
},
};
static struct rcg_clk camss_gp1_clk_src = {
.cmd_rcgr_reg = CAMSS_GP1_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_camss_gp0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "camss_gp1_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(camss_gp1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_jpeg0_clk[] = {
F( 133330000, gpll0_out_main, 6, 0, 0),
F( 266670000, gpll0_out_main, 3, 0, 0),
F( 320000000, gpll0_out_main, 2.5, 0, 0),
F_END
};
static struct rcg_clk jpeg0_clk_src = {
.cmd_rcgr_reg = JPEG0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_jpeg0_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "jpeg0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000, HIGH,
320000000),
CLK_INIT(jpeg0_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_mclk0_1_2_clk[] = {
F( 24000000, gpll6_mclk, 1, 1, 45),
F( 66670000, gpll0_out_main, 12, 0, 0),
F_END
};
static struct rcg_clk mclk0_clk_src = {
.cmd_rcgr_reg = MCLK0_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_camss_mclk0_1_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "mclk0_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 24000000, NOMINAL, 66670000),
CLK_INIT(mclk0_clk_src.c),
},
};
static struct rcg_clk mclk1_clk_src = {
.cmd_rcgr_reg = MCLK1_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_camss_mclk0_1_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "mclk1_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP1(LOW, 66670000),
CLK_INIT(mclk1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_mclk2_clk[] = {
F( 66670000, gpll0_out_main, 12, 0, 0),
F_END
};
static struct rcg_clk mclk2_clk_src = {
.cmd_rcgr_reg = MCLK2_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_camss_mclk2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "mclk2_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP1(LOW, 66670000),
CLK_INIT(mclk2_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_csi0_1phytimer_clk[] = {
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F_END
};
static struct rcg_clk csi0phytimer_clk_src = {
.cmd_rcgr_reg = CSI0PHYTIMER_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_csi0_1phytimer_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "csi0phytimer_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi0phytimer_clk_src.c),
},
};
static struct rcg_clk csi1phytimer_clk_src = {
.cmd_rcgr_reg = CSI1PHYTIMER_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_csi0_1phytimer_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "csi1phytimer_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi1phytimer_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_camss_cpp_clk[] = {
F( 160000000, gpll0_out_main, 5, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F( 228570000, gpll0_out_main, 3.5, 0, 0),
F( 266670000, gpll0_out_main, 3, 0, 0),
F( 320000000, gpll0_out_main, 2.5, 0, 0),
F( 465000000, gpll2_out_main, 2, 0, 0),
F_END
};
static struct rcg_clk cpp_clk_src = {
.cmd_rcgr_reg = CPP_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_camss_cpp_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "cpp_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 160000000, NOMINAL, 320000000, HIGH,
465000000),
CLK_INIT(cpp_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_gp1_3_clk[] = {
F( 19200000, gcc_xo, 1, 0, 0),
F_END
};
static struct rcg_clk gp1_clk_src = {
.cmd_rcgr_reg = GP1_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_gp1_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gp1_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(gp1_clk_src.c),
},
};
static struct rcg_clk gp2_clk_src = {
.cmd_rcgr_reg = GP2_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_gp1_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gp2_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(gp2_clk_src.c),
},
};
static struct rcg_clk gp3_clk_src = {
.cmd_rcgr_reg = GP3_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_gp1_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gp3_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(gp3_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_mdss_byte0_clk[] = {
{
.div_src_val = BVAL(10, 8, dsi0_phypll_mm_source_val),
},
F_END
};
static struct rcg_clk byte0_clk_src = {
.cmd_rcgr_reg = BYTE0_CMD_RCGR,
.current_freq = ftbl_gcc_mdss_byte0_clk,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "byte0_clk_src",
.ops = &clk_ops_byte,
VDD_DIG_FMAX_MAP2(LOW, 112500000, NOMINAL, 187500000),
CLK_INIT(byte0_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_mdss_byte1_clk[] = {
{
.div_src_val = BVAL(10, 8, dsi0_phypll_mm_source_val),
},
F_END
};
static struct rcg_clk byte1_clk_src = {
.cmd_rcgr_reg = BYTE1_CMD_RCGR,
.current_freq = ftbl_gcc_mdss_byte1_clk,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "byte1_clk_src",
.ops = &clk_ops_byte,
VDD_DIG_FMAX_MAP2(LOW, 112500000, NOMINAL, 187500000),
CLK_INIT(byte1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_mdss_esc0_1_clk[] = {
F( 19200000, gcc_xo, 1, 0, 0),
F_END
};
static struct rcg_clk esc0_clk_src = {
.cmd_rcgr_reg = ESC0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_mdss_esc0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "esc0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 19200000),
CLK_INIT(esc0_clk_src.c),
},
};
static struct rcg_clk esc1_clk_src = {
.cmd_rcgr_reg = ESC1_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_mdss_esc0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "esc1_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 19200000),
CLK_INIT(esc1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_mdss_mdp_clk[] = {
F( 50000000, gpll0_out_aux, 16, 0, 0),
F( 80000000, gpll0_out_aux, 10, 0, 0),
F( 100000000, gpll0_out_aux, 8, 0, 0),
F( 145500000, gpll0_out_aux, 5.5, 0, 0),
F( 153600000, gpll1_out_main, 4, 0, 0),
F( 160000000, gpll0_out_aux, 5, 0, 0),
F( 177780000, gpll0_out_aux, 4.5, 0, 0),
F( 200000000, gpll0_out_aux, 4, 0, 0),
F( 266670000, gpll0_out_aux, 3, 0, 0),
F( 307200000, gpll1_out_main, 2, 0, 0),
F( 366670000, gpll3_out_aux, 3, 0, 0),
F_END
};
static struct rcg_clk mdp_clk_src = {
.cmd_rcgr_reg = MDP_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_mdss_mdp_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "mdp_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 153600000, NOMINAL, 307200000, HIGH,
366670000),
CLK_INIT(mdp_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_mdss_pclk0_clk[] = {
{
.div_src_val = BVAL(10, 8, dsi0_phypll_mm_source_val)
| BVAL(4, 0, 0),
},
F_END
};
static struct rcg_clk pclk0_clk_src = {
.cmd_rcgr_reg = PCLK0_CMD_RCGR,
.current_freq = ftbl_gcc_mdss_pclk0_clk,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "pclk0_clk_src",
.ops = &clk_ops_pixel,
VDD_DIG_FMAX_MAP2(LOW, 150000000, NOMINAL, 250000000),
CLK_INIT(pclk0_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_mdss_pclk1_clk[] = {
{
.div_src_val = BVAL(10, 8, dsi0_phypll_mm_source_val)
| BVAL(4, 0, 0),
},
F_END
};
static struct rcg_clk pclk1_clk_src = {
.cmd_rcgr_reg = PCLK1_CMD_RCGR,
.current_freq = ftbl_gcc_mdss_pclk1_clk,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "pclk1_clk_src",
.ops = &clk_ops_pixel,
VDD_DIG_FMAX_MAP2(LOW, 150000000, NOMINAL, 250000000),
CLK_INIT(pclk1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_mdss_vsync_clk[] = {
F( 19200000, gcc_xo, 1, 0, 0),
F_END
};
static struct rcg_clk vsync_clk_src = {
.cmd_rcgr_reg = VSYNC_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_mdss_vsync_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "vsync_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 19200000),
CLK_INIT(vsync_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_pdm2_clk[] = {
F( 64000000, gpll0_out_main, 12.5, 0, 0),
F_END
};
static struct rcg_clk pdm2_clk_src = {
.cmd_rcgr_reg = PDM2_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_pdm2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "pdm2_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 64000000),
CLK_INIT(pdm2_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_sdcc1_2_apps_clk[] = {
F( 144000, gcc_xo, 16, 3, 25),
F( 400000, gcc_xo, 12, 1, 4),
F( 20000000, gpll0_out_main, 10, 1, 4),
F( 25000000, gpll0_out_main, 16, 1, 2),
F( 50000000, gpll0_out_main, 16, 0, 0),
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 177770000, gpll0_out_main, 4.5, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F_END
};
static struct rcg_clk sdcc1_apps_clk_src = {
.cmd_rcgr_reg = SDCC1_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_sdcc1_2_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "sdcc1_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 50000000, NOMINAL, 200000000),
CLK_INIT(sdcc1_apps_clk_src.c),
},
};
static struct rcg_clk sdcc2_apps_clk_src = {
.cmd_rcgr_reg = SDCC2_APPS_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_sdcc1_2_apps_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "sdcc2_apps_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 50000000, NOMINAL, 200000000),
CLK_INIT(sdcc2_apps_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_usb_hs_system_clk[] = {
F( 57140000, gpll0_out_main, 14, 0, 0),
F( 80000000, gpll0_out_main, 10, 0, 0),
F( 100000000, gpll0_out_main, 8, 0, 0),
F_END
};
static struct rcg_clk usb_hs_system_clk_src = {
.cmd_rcgr_reg = USB_HS_SYSTEM_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_usb_hs_system_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "usb_hs_system_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 57140000, NOMINAL, 100000000),
CLK_INIT(usb_hs_system_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_usb_ic_clk[] = {
F( 60000000, gpll6_out_main, 1, 1, 18),
F_END
};
static struct rcg_clk usb_fs_ic_clk_src = {
.cmd_rcgr_reg = USB_FS_IC_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_usb_ic_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "usb_fs_ic_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP1(LOW, 60000000),
CLK_INIT(usb_fs_ic_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_usb_fs_system_clk[] = {
F( 64000000, gpll0_misc, 12.5, 0, 0),
F_END
};
static struct rcg_clk usb_fs_system_clk_src = {
.cmd_rcgr_reg = USB_FS_SYSTEM_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_usb_fs_system_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "usb_fs_system_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP1(LOW, 64000000),
CLK_INIT(usb_fs_system_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_gcc_venus0_vcodec0_clk[] = {
F( 133330000, gpll0_out_main, 6, 0, 0),
F( 200000000, gpll0_out_main, 4, 0, 0),
F( 266670000, gpll0_out_main, 3, 0, 0),
F_END
};
static struct rcg_clk vcodec0_clk_src = {
.cmd_rcgr_reg = VCODEC0_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_gcc_venus0_vcodec0_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "vcodec0_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 200000000, HIGH,
266670000),
CLK_INIT(vcodec0_clk_src.c),
},
};
static struct local_vote_clk gcc_blsp1_ahb_clk = {
.cbcr_reg = BLSP1_AHB_CBCR,
.vote_reg = APCS_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(10),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_ahb_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_blsp1_ahb_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup1_i2c_apps_clk = {
.cbcr_reg = BLSP1_QUP1_I2C_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup1_i2c_apps_clk",
.parent = &blsp1_qup1_i2c_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup1_i2c_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup1_spi_apps_clk = {
.cbcr_reg = BLSP1_QUP1_SPI_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup1_spi_apps_clk",
.parent = &blsp1_qup1_spi_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup1_spi_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup2_i2c_apps_clk = {
.cbcr_reg = BLSP1_QUP2_I2C_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup2_i2c_apps_clk",
.parent = &blsp1_qup2_i2c_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup2_i2c_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup2_spi_apps_clk = {
.cbcr_reg = BLSP1_QUP2_SPI_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup2_spi_apps_clk",
.parent = &blsp1_qup2_spi_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup2_spi_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup3_i2c_apps_clk = {
.cbcr_reg = BLSP1_QUP3_I2C_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup3_i2c_apps_clk",
.parent = &blsp1_qup3_i2c_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup3_i2c_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup3_spi_apps_clk = {
.cbcr_reg = BLSP1_QUP3_SPI_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup3_spi_apps_clk",
.parent = &blsp1_qup3_spi_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup3_spi_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup4_i2c_apps_clk = {
.cbcr_reg = BLSP1_QUP4_I2C_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup4_i2c_apps_clk",
.parent = &blsp1_qup4_i2c_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup4_i2c_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup4_spi_apps_clk = {
.cbcr_reg = BLSP1_QUP4_SPI_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup4_spi_apps_clk",
.parent = &blsp1_qup4_spi_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup4_spi_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup5_i2c_apps_clk = {
.cbcr_reg = BLSP1_QUP5_I2C_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup5_i2c_apps_clk",
.parent = &blsp1_qup5_i2c_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup5_i2c_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup5_spi_apps_clk = {
.cbcr_reg = BLSP1_QUP5_SPI_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup5_spi_apps_clk",
.parent = &blsp1_qup5_spi_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup5_spi_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup6_i2c_apps_clk = {
.cbcr_reg = BLSP1_QUP6_I2C_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup6_i2c_apps_clk",
.parent = &blsp1_qup6_i2c_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup6_i2c_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_qup6_spi_apps_clk = {
.cbcr_reg = BLSP1_QUP6_SPI_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_qup6_spi_apps_clk",
.parent = &blsp1_qup6_spi_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_qup6_spi_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_uart1_apps_clk = {
.cbcr_reg = BLSP1_UART1_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_uart1_apps_clk",
.parent = &blsp1_uart1_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_uart1_apps_clk.c),
},
};
static struct branch_clk gcc_blsp1_uart2_apps_clk = {
.cbcr_reg = BLSP1_UART2_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_blsp1_uart2_apps_clk",
.parent = &blsp1_uart2_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_blsp1_uart2_apps_clk.c),
},
};
static struct local_vote_clk gcc_boot_rom_ahb_clk = {
.cbcr_reg = BOOT_ROM_AHB_CBCR,
.vote_reg = APCS_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(7),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_boot_rom_ahb_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_boot_rom_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_cci_ahb_clk = {
.cbcr_reg = CAMSS_CCI_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_cci_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_cci_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_cci_clk = {
.cbcr_reg = CAMSS_CCI_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_cci_clk",
.parent = &cci_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_cci_clk.c),
},
};
static struct branch_clk gcc_camss_csi0_ahb_clk = {
.cbcr_reg = CAMSS_CSI0_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi0_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi0_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_csi0_clk = {
.cbcr_reg = CAMSS_CSI0_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi0_clk",
.parent = &csi0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi0_clk.c),
},
};
static struct branch_clk gcc_camss_csi0phy_clk = {
.cbcr_reg = CAMSS_CSI0PHY_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi0phy_clk",
.parent = &csi0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi0phy_clk.c),
},
};
static struct branch_clk gcc_camss_csi0pix_clk = {
.cbcr_reg = CAMSS_CSI0PIX_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi0pix_clk",
.parent = &csi0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi0pix_clk.c),
},
};
static struct branch_clk gcc_camss_csi0rdi_clk = {
.cbcr_reg = CAMSS_CSI0RDI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi0rdi_clk",
.parent = &csi0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi0rdi_clk.c),
},
};
static struct branch_clk gcc_camss_csi1_ahb_clk = {
.cbcr_reg = CAMSS_CSI1_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi1_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi1_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_csi1_clk = {
.cbcr_reg = CAMSS_CSI1_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi1_clk",
.parent = &csi1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi1_clk.c),
},
};
static struct branch_clk gcc_camss_csi1phy_clk = {
.cbcr_reg = CAMSS_CSI1PHY_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi1phy_clk",
.parent = &csi1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi1phy_clk.c),
},
};
static struct branch_clk gcc_camss_csi1pix_clk = {
.cbcr_reg = CAMSS_CSI1PIX_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi1pix_clk",
.parent = &csi1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi1pix_clk.c),
},
};
static struct branch_clk gcc_camss_csi1rdi_clk = {
.cbcr_reg = CAMSS_CSI1RDI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi1rdi_clk",
.parent = &csi1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi1rdi_clk.c),
},
};
static struct branch_clk gcc_camss_csi2_ahb_clk = {
.cbcr_reg = CAMSS_CSI2_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi2_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi2_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_csi2_clk = {
.cbcr_reg = CAMSS_CSI2_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi2_clk",
.parent = &csi2_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi2_clk.c),
},
};
static struct branch_clk gcc_camss_csi2phy_clk = {
.cbcr_reg = CAMSS_CSI2PHY_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi2phy_clk",
.parent = &csi2_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi2phy_clk.c),
},
};
static struct branch_clk gcc_camss_csi2pix_clk = {
.cbcr_reg = CAMSS_CSI2PIX_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi2pix_clk",
.parent = &csi2_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi2pix_clk.c),
},
};
static struct branch_clk gcc_camss_csi2rdi_clk = {
.cbcr_reg = CAMSS_CSI2RDI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi2rdi_clk",
.parent = &csi2_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi2rdi_clk.c),
},
};
static struct branch_clk gcc_camss_csi_vfe0_clk = {
.cbcr_reg = CAMSS_CSI_VFE0_CBCR,
.bcr_reg = CAMSS_CSI_VFE0_BCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi_vfe0_clk",
.parent = &vfe0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi_vfe0_clk.c),
},
};
static struct branch_clk gcc_camss_gp0_clk = {
.cbcr_reg = CAMSS_GP0_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_gp0_clk",
.parent = &camss_gp0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_gp0_clk.c),
},
};
static struct branch_clk gcc_camss_gp1_clk = {
.cbcr_reg = CAMSS_GP1_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_gp1_clk",
.parent = &camss_gp1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_gp1_clk.c),
},
};
static struct branch_clk gcc_camss_ispif_ahb_clk = {
.cbcr_reg = CAMSS_ISPIF_AHB_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_ispif_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_ispif_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_jpeg0_clk = {
.cbcr_reg = CAMSS_JPEG0_CBCR,
.bcr_reg = CAMSS_JPEG0_BCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_jpeg0_clk",
.parent = &jpeg0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_jpeg0_clk.c),
},
};
static struct branch_clk gcc_camss_jpeg_ahb_clk = {
.cbcr_reg = CAMSS_JPEG_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_jpeg_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_jpeg_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_jpeg_axi_clk = {
.cbcr_reg = CAMSS_JPEG_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_jpeg_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_jpeg_axi_clk.c),
},
};
static struct branch_clk gcc_camss_mclk0_clk = {
.cbcr_reg = CAMSS_MCLK0_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_mclk0_clk",
.parent = &mclk0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_mclk0_clk.c),
},
};
static struct branch_clk gcc_camss_mclk1_clk = {
.cbcr_reg = CAMSS_MCLK1_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_mclk1_clk",
.parent = &mclk1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_mclk1_clk.c),
},
};
static struct branch_clk gcc_camss_mclk2_clk = {
.cbcr_reg = CAMSS_MCLK2_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_mclk2_clk",
.parent = &mclk2_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_mclk2_clk.c),
},
};
static struct branch_clk gcc_camss_micro_ahb_clk = {
.cbcr_reg = CAMSS_MICRO_AHB_CBCR,
.bcr_reg = CAMSS_MICRO_BCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_micro_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_micro_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_csi0phytimer_clk = {
.cbcr_reg = CAMSS_CSI0PHYTIMER_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi0phytimer_clk",
.parent = &csi0phytimer_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi0phytimer_clk.c),
},
};
static struct branch_clk gcc_camss_csi1phytimer_clk = {
.cbcr_reg = CAMSS_CSI1PHYTIMER_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_csi1phytimer_clk",
.parent = &csi1phytimer_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_csi1phytimer_clk.c),
},
};
static struct branch_clk gcc_camss_top_ahb_clk = {
.cbcr_reg = CAMSS_TOP_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_top_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_top_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_ahb_clk = {
.cbcr_reg = CAMSS_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_cpp_ahb_clk = {
.cbcr_reg = CAMSS_CPP_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_cpp_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_cpp_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_cpp_clk = {
.cbcr_reg = CAMSS_CPP_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_cpp_clk",
.parent = &cpp_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_cpp_clk.c),
},
};
static struct branch_clk gcc_camss_vfe0_clk = {
.cbcr_reg = CAMSS_VFE0_CBCR,
.bcr_reg = CAMSS_VFE_BCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_vfe0_clk",
.parent = &vfe0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_vfe0_clk.c),
},
};
static struct branch_clk gcc_camss_vfe_ahb_clk = {
.cbcr_reg = CAMSS_VFE_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_vfe_ahb_clk",
.parent = &camss_top_ahb_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_vfe_ahb_clk.c),
},
};
static struct branch_clk gcc_camss_vfe_axi_clk = {
.cbcr_reg = CAMSS_VFE_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_camss_vfe_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_camss_vfe_axi_clk.c),
},
};
static struct clk_freq_tbl ftbl_gcc_crypto_clk[] = {
F( 50000000, gpll0_out_main, 16, 0, 0),
F( 80000000, gpll0_out_main, 10, 0, 0),
F( 100000000, gpll0_out_main, 8, 0, 0),
F( 160000000, gpll0_out_main, 5, 0, 0),
F_END
};
static struct rcg_clk crypto_clk_src = {
.cmd_rcgr_reg = CRYPTO_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_gcc_crypto_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "crypto_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 80000000, NOMINAL, 160000000),
CLK_INIT(crypto_clk_src.c),
},
};
static struct local_vote_clk gcc_crypto_ahb_clk = {
.cbcr_reg = CRYPTO_AHB_CBCR,
.vote_reg = APCS_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(0),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_crypto_ahb_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_crypto_ahb_clk.c),
},
};
static struct local_vote_clk gcc_crypto_axi_clk = {
.cbcr_reg = CRYPTO_AXI_CBCR,
.vote_reg = APCS_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(1),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_crypto_axi_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_crypto_axi_clk.c),
},
};
static struct local_vote_clk gcc_crypto_clk = {
.cbcr_reg = CRYPTO_CBCR,
.vote_reg = APCS_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(2),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_crypto_clk",
.parent = &crypto_clk_src.c,
.ops = &clk_ops_vote,
CLK_INIT(gcc_crypto_clk.c),
},
};
static struct branch_clk gcc_oxili_gmem_clk = {
.cbcr_reg = OXILI_GMEM_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_oxili_gmem_clk",
.parent = &gfx3d_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_oxili_gmem_clk.c),
},
};
static struct local_vote_clk gcc_apss_tcu_clk;
static struct branch_clk gcc_bimc_gfx_clk = {
.cbcr_reg = BIMC_GFX_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_bimc_gfx_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_bimc_gfx_clk.c),
.depends = &gcc_apss_tcu_clk.c,
},
};
static struct branch_clk gcc_bimc_gpu_clk = {
.cbcr_reg = BIMC_GPU_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_bimc_gpu_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_bimc_gpu_clk.c),
},
};
static struct branch_clk gcc_gp1_clk = {
.cbcr_reg = GP1_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_gp1_clk",
.parent = &gp1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_gp1_clk.c),
},
};
static struct branch_clk gcc_gp2_clk = {
.cbcr_reg = GP2_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_gp2_clk",
.parent = &gp2_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_gp2_clk.c),
},
};
static struct branch_clk gcc_gp3_clk = {
.cbcr_reg = GP3_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_gp3_clk",
.parent = &gp3_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_gp3_clk.c),
},
};
static struct branch_clk gcc_mdss_ahb_clk = {
.cbcr_reg = MDSS_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_ahb_clk.c),
},
};
static struct branch_clk gcc_mdss_axi_clk = {
.cbcr_reg = MDSS_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_axi_clk.c),
},
};
static struct branch_clk gcc_mdss_byte0_clk = {
.cbcr_reg = MDSS_BYTE0_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_byte0_clk",
.parent = &byte0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_byte0_clk.c),
},
};
static struct branch_clk gcc_mdss_byte1_clk = {
.cbcr_reg = MDSS_BYTE1_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_byte1_clk",
.parent = &byte1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_byte1_clk.c),
},
};
static struct branch_clk gcc_mdss_esc0_clk = {
.cbcr_reg = MDSS_ESC0_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_esc0_clk",
.parent = &esc0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_esc0_clk.c),
},
};
static struct branch_clk gcc_mdss_esc1_clk = {
.cbcr_reg = MDSS_ESC1_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_esc1_clk",
.parent = &esc1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_esc1_clk.c),
},
};
static struct branch_clk gcc_mdss_mdp_clk = {
.cbcr_reg = MDSS_MDP_CBCR,
.bcr_reg = MDSS_BCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_mdp_clk",
.parent = &mdp_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_mdp_clk.c),
},
};
static struct branch_clk gcc_mdss_pclk0_clk = {
.cbcr_reg = MDSS_PCLK0_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_pclk0_clk",
.parent = &pclk0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_pclk0_clk.c),
},
};
static struct branch_clk gcc_mdss_pclk1_clk = {
.cbcr_reg = MDSS_PCLK1_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_pclk1_clk",
.parent = &pclk1_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_pclk1_clk.c),
},
};
static struct branch_clk gcc_mdss_vsync_clk = {
.cbcr_reg = MDSS_VSYNC_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdss_vsync_clk",
.parent = &vsync_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_mdss_vsync_clk.c),
},
};
static struct branch_clk gcc_mss_cfg_ahb_clk = {
.cbcr_reg = MSS_CFG_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mss_cfg_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_mss_cfg_ahb_clk.c),
},
};
static struct branch_clk gcc_mss_q6_bimc_axi_clk = {
.cbcr_reg = MSS_Q6_BIMC_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mss_q6_bimc_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_mss_q6_bimc_axi_clk.c),
},
};
static struct branch_clk gcc_oxili_ahb_clk = {
.cbcr_reg = OXILI_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_oxili_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_oxili_ahb_clk.c),
},
};
static struct branch_clk gcc_oxili_gfx3d_clk = {
.cbcr_reg = OXILI_GFX3D_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_oxili_gfx3d_clk",
.parent = &gfx3d_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_oxili_gfx3d_clk.c),
},
};
static struct branch_clk gcc_pdm2_clk = {
.cbcr_reg = PDM2_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_pdm2_clk",
.parent = &pdm2_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_pdm2_clk.c),
},
};
static struct branch_clk gcc_pdm_ahb_clk = {
.cbcr_reg = PDM_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_pdm_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_pdm_ahb_clk.c),
},
};
static struct local_vote_clk gcc_prng_ahb_clk = {
.cbcr_reg = PRNG_AHB_CBCR,
.vote_reg = APCS_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(8),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_prng_ahb_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_prng_ahb_clk.c),
},
};
static struct branch_clk gcc_sdcc1_ahb_clk = {
.cbcr_reg = SDCC1_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_sdcc1_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_sdcc1_ahb_clk.c),
},
};
static struct branch_clk gcc_sdcc1_apps_clk = {
.cbcr_reg = SDCC1_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_sdcc1_apps_clk",
.parent = &sdcc1_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_sdcc1_apps_clk.c),
},
};
static struct branch_clk gcc_sdcc2_ahb_clk = {
.cbcr_reg = SDCC2_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_sdcc2_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_sdcc2_ahb_clk.c),
},
};
static struct branch_clk gcc_sdcc2_apps_clk = {
.cbcr_reg = SDCC2_APPS_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_sdcc2_apps_clk",
.parent = &sdcc2_apps_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_sdcc2_apps_clk.c),
},
};
static struct local_vote_clk gcc_apss_tcu_clk = {
.cbcr_reg = APSS_TCU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(1),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_apss_tcu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_apss_tcu_clk.c),
},
};
static struct local_vote_clk gcc_gfx_tcu_clk = {
.cbcr_reg = GFX_TCU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(2),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_gfx_tcu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_gfx_tcu_clk.c),
},
};
static struct local_vote_clk gcc_gfx_tbu_clk = {
.cbcr_reg = GFX_TBU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(3),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_gfx_tbu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_gfx_tbu_clk.c),
},
};
static struct local_vote_clk gcc_mdp_tbu_clk = {
.cbcr_reg = MDP_TBU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(4),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdp_tbu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_mdp_tbu_clk.c),
},
};
static struct local_vote_clk gcc_venus_tbu_clk = {
.cbcr_reg = VENUS_TBU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(5),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_venus_tbu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_venus_tbu_clk.c),
},
};
static struct local_vote_clk gcc_vfe_tbu_clk = {
.cbcr_reg = VFE_TBU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(9),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_vfe_tbu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_vfe_tbu_clk.c),
},
};
static struct local_vote_clk gcc_jpeg_tbu_clk = {
.cbcr_reg = JPEG_TBU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(10),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_jpeg_tbu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_jpeg_tbu_clk.c),
},
};
static struct local_vote_clk gcc_smmu_cfg_clk = {
.cbcr_reg = SMMU_CFG_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(12),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_smmu_cfg_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_smmu_cfg_clk.c),
},
};
static struct local_vote_clk gcc_gtcu_ahb_clk = {
.cbcr_reg = GTCU_AHB_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(13),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_gtcu_ahb_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_gtcu_ahb_clk.c),
},
};
static struct local_vote_clk gcc_cpp_tbu_clk = {
.cbcr_reg = CPP_TBU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(14),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_cpp_tbu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_cpp_tbu_clk.c),
},
};
static struct local_vote_clk gcc_mdp_rt_tbu_clk = {
.cbcr_reg = MDP_TBU_CBCR,
.vote_reg = APCS_SMMU_CLOCK_BRANCH_ENA_VOTE,
.en_mask = BIT(15),
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_mdp_rt_tbu_clk",
.ops = &clk_ops_vote,
CLK_INIT(gcc_mdp_rt_tbu_clk.c),
},
};
static struct branch_clk gcc_usb2a_phy_sleep_clk = {
.cbcr_reg = USB2A_PHY_SLEEP_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_usb2a_phy_sleep_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_usb2a_phy_sleep_clk.c),
},
};
static struct branch_clk gcc_usb_fs_ahb_clk = {
.cbcr_reg = USB_FS_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_usb_fs_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_usb_fs_ahb_clk.c),
},
};
static struct branch_clk gcc_usb_fs_ic_clk = {
.cbcr_reg = USB_FS_IC_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_usb_fs_ic_clk",
.parent = &usb_fs_ic_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_usb_fs_ic_clk.c),
},
};
static struct branch_clk gcc_usb_fs_system_clk = {
.cbcr_reg = USB_FS_SYSTEM_CBCR,
.bcr_reg = USB_FS_BCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_usb_fs_system_clk",
.parent = &usb_fs_system_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_usb_fs_system_clk.c),
},
};
static struct branch_clk gcc_usb_hs_ahb_clk = {
.cbcr_reg = USB_HS_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_usb_hs_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_usb_hs_ahb_clk.c),
},
};
static struct branch_clk gcc_usb_hs_system_clk = {
.cbcr_reg = USB_HS_SYSTEM_CBCR,
.bcr_reg = USB_HS_BCR,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_usb_hs_system_clk",
.parent = &usb_hs_system_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_usb_hs_system_clk.c),
},
};
static struct branch_clk gcc_venus0_ahb_clk = {
.cbcr_reg = VENUS0_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_venus0_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_venus0_ahb_clk.c),
},
};
static struct branch_clk gcc_venus0_axi_clk = {
.cbcr_reg = VENUS0_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_venus0_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(gcc_venus0_axi_clk.c),
},
};
static struct branch_clk gcc_venus0_core0_vcodec0_clk = {
.cbcr_reg = VENUS0_CORE0_VCODEC0_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_venus0_core0_vcodec0_clk",
.parent = &vcodec0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_venus0_core0_vcodec0_clk.c),
},
};
static struct branch_clk gcc_venus0_core1_vcodec0_clk = {
.cbcr_reg = VENUS0_CORE1_VCODEC0_CBCR,
.has_sibling = 1,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_venus0_core1_vcodec0_clk",
.parent = &vcodec0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_venus0_core1_vcodec0_clk.c),
},
};
static struct branch_clk gcc_venus0_vcodec0_clk = {
.cbcr_reg = VENUS0_VCODEC0_CBCR,
.has_sibling = 0,
.base = &virt_bases[GCC_BASE],
.c = {
.dbg_name = "gcc_venus0_vcodec0_clk",
.parent = &vcodec0_clk_src.c,
.ops = &clk_ops_branch,
CLK_INIT(gcc_venus0_vcodec0_clk.c),
},
};
/* GPLL3 at 1100 MHz, main output enabled. */
static struct pll_config gpll3_config = {
.l = 57,
.m = 7,
.n = 24,
.vco_val = 0x0,
.vco_mask = BIT(20),
.pre_div_val = 0x0,
.pre_div_mask = BIT(12),
.post_div_val = 0x0,
.post_div_mask = BM(9, 8),
.mn_ena_val = BIT(24),
.mn_ena_mask = BIT(24),
.main_output_val = BIT(0),
.main_output_mask = BIT(0),
.aux_output_val = BIT(1),
.aux_output_mask = BIT(1),
};
static struct pll_config_regs gpll3_regs = {
.l_reg = (void __iomem *)GPLL3_L_VAL,
.m_reg = (void __iomem *)GPLL3_M_VAL,
.n_reg = (void __iomem *)GPLL3_N_VAL,
.config_reg = (void __iomem *)GPLL3_USER_CTL,
.mode_reg = (void __iomem *)GPLL3_MODE,
.base = &virt_bases[GCC_BASE],
};
/* GPLL4 at 1200 MHz, main output enabled. */
static struct pll_config gpll4_config = {
.l = 62,
.m = 1,
.n = 2,
.vco_val = 0x0,
.vco_mask = BIT(20),
.pre_div_val = 0x0,
.pre_div_mask = BIT(12),
.post_div_val = 0x0,
.post_div_mask = BM(9, 8),
.mn_ena_val = BIT(24),
.mn_ena_mask = BIT(24),
.main_output_val = BIT(0),
.main_output_mask = BIT(0),
};
static struct pll_config_regs gpll4_regs = {
.l_reg = (void __iomem *)GPLL4_L_VAL,
.m_reg = (void __iomem *)GPLL4_M_VAL,
.n_reg = (void __iomem *)GPLL4_N_VAL,
.config_reg = (void __iomem *)GPLL4_USER_CTL,
.mode_reg = (void __iomem *)GPLL4_MODE,
.base = &virt_bases[GCC_BASE],
};
static struct mux_clk gcc_debug_mux;
static struct clk_ops clk_ops_debug_mux;
static struct measure_clk_data debug_mux_priv = {
.cxo = &gcc_xo.c,
.plltest_reg = GCC_PLLTEST_PAD_CFG,
.plltest_val = 0x51A00,
.xo_div4_cbcr = GCC_XO_DIV4_CBCR,
.ctl_reg = CLOCK_FRQ_MEASURE_CTL,
.status_reg = CLOCK_FRQ_MEASURE_STATUS,
.base = &virt_bases[GCC_BASE],
};
static int gcc_set_mux_sel(struct mux_clk *clk, int sel)
{
u32 regval;
regval = readl_relaxed(GCC_REG_BASE(GCC_DEBUG_CLK_CTL));
regval &= 0x1FF;
writel_relaxed(regval, GCC_REG_BASE(GCC_DEBUG_CLK_CTL));
if (sel == 0xFFFF)
return 0;
mux_reg_ops.set_mux_sel(clk, sel);
return 0;
};
static struct clk_mux_ops gcc_debug_mux_ops;
static struct mux_clk gcc_debug_mux = {
.priv = &debug_mux_priv,
.ops = &gcc_debug_mux_ops,
.en_mask = BIT(16),
.mask = 0x1FF,
.base = &virt_dbgbase,
MUX_REC_SRC_LIST(
&rpm_debug_clk.c,
),
MUX_SRC_LIST(
{&rpm_debug_clk.c, 0xFFFF},
{&gcc_gp1_clk.c, 0x0010},
{&gcc_gp2_clk.c, 0x0011},
{&gcc_gp3_clk.c, 0x0012},
{&gcc_bimc_gfx_clk.c, 0x002d},
{&gcc_mss_cfg_ahb_clk.c, 0x0030},
{&gcc_mss_q6_bimc_axi_clk.c, 0x0031},
{&gcc_apss_tcu_clk.c, 0x0050},
{&gcc_mdp_tbu_clk.c, 0x0051},
{&gcc_gfx_tbu_clk.c, 0x0052},
{&gcc_gfx_tcu_clk.c, 0x0053},
{&gcc_venus_tbu_clk.c, 0x0054},
{&gcc_gtcu_ahb_clk.c, 0x0058},
{&gcc_vfe_tbu_clk.c, 0x005a},
{&gcc_smmu_cfg_clk.c, 0x005b},
{&gcc_jpeg_tbu_clk.c, 0x005c},
{&gcc_usb_hs_system_clk.c, 0x0060},
{&gcc_usb_hs_ahb_clk.c, 0x0061},
{&gcc_usb_fs_ahb_clk.c, 0x00f1},
{&gcc_usb_fs_ic_clk.c, 0x00f4},
{&gcc_usb2a_phy_sleep_clk.c, 0x0063},
{&gcc_sdcc1_apps_clk.c, 0x0068},
{&gcc_sdcc1_ahb_clk.c, 0x0069},
{&gcc_sdcc2_apps_clk.c, 0x0070},
{&gcc_sdcc2_ahb_clk.c, 0x0071},
{&gcc_blsp1_ahb_clk.c, 0x0088},
{&gcc_blsp1_qup1_spi_apps_clk.c, 0x008a},
{&gcc_blsp1_qup1_i2c_apps_clk.c, 0x008b},
{&gcc_blsp1_uart1_apps_clk.c, 0x008c},
{&gcc_blsp1_qup2_spi_apps_clk.c, 0x008e},
{&gcc_blsp1_qup2_i2c_apps_clk.c, 0x0090},
{&gcc_blsp1_uart2_apps_clk.c, 0x0091},
{&gcc_blsp1_qup3_spi_apps_clk.c, 0x0093},
{&gcc_blsp1_qup3_i2c_apps_clk.c, 0x0094},
{&gcc_blsp1_qup4_spi_apps_clk.c, 0x0098},
{&gcc_blsp1_qup4_i2c_apps_clk.c, 0x0099},
{&gcc_blsp1_qup5_spi_apps_clk.c, 0x009c},
{&gcc_blsp1_qup5_i2c_apps_clk.c, 0x009d},
{&gcc_blsp1_qup6_spi_apps_clk.c, 0x00a1},
{&gcc_blsp1_qup6_i2c_apps_clk.c, 0x00a2},
{&gcc_camss_ahb_clk.c, 0x00a8},
{&gcc_camss_top_ahb_clk.c, 0x00a9},
{&gcc_camss_micro_ahb_clk.c, 0x00aa},
{&gcc_camss_gp0_clk.c, 0x00ab},
{&gcc_camss_gp1_clk.c, 0x00ac},
{&gcc_camss_mclk0_clk.c, 0x00ad},
{&gcc_camss_mclk1_clk.c, 0x00ae},
{&gcc_camss_mclk2_clk.c, 0x01bd},
{&gcc_camss_cci_clk.c, 0x00af},
{&gcc_camss_cci_ahb_clk.c, 0x00b0},
{&gcc_camss_csi0phytimer_clk.c, 0x00b1},
{&gcc_camss_csi1phytimer_clk.c, 0x00b2},
{&gcc_camss_jpeg0_clk.c, 0x00b3},
{&gcc_camss_jpeg_ahb_clk.c, 0x00b4},
{&gcc_camss_jpeg_axi_clk.c, 0x00b5},
{&gcc_camss_vfe0_clk.c, 0x00b8},
{&gcc_camss_cpp_clk.c, 0x00b9},
{&gcc_camss_cpp_ahb_clk.c, 0x00ba},
{&gcc_camss_vfe_ahb_clk.c, 0x00bb},
{&gcc_camss_vfe_axi_clk.c, 0x00bc},
{&gcc_camss_csi_vfe0_clk.c, 0x00bf},
{&gcc_camss_csi0_clk.c, 0x00c0},
{&gcc_camss_csi0_ahb_clk.c, 0x00c1},
{&gcc_camss_csi0phy_clk.c, 0x00c2},
{&gcc_camss_csi0rdi_clk.c, 0x00c3},
{&gcc_camss_csi0pix_clk.c, 0x00c4},
{&gcc_camss_csi1_clk.c, 0x00c5},
{&gcc_camss_csi1_ahb_clk.c, 0x00c6},
{&gcc_camss_csi1phy_clk.c, 0x00c7},
{&gcc_camss_csi2_clk.c, 0x00e3},
{&gcc_camss_csi2_ahb_clk.c, 0x00e4},
{&gcc_camss_csi2phy_clk.c, 0x00e5},
{&gcc_camss_csi2rdi_clk.c, 0x00e6},
{&gcc_camss_csi2pix_clk.c, 0x00e7},
{&gcc_pdm_ahb_clk.c, 0x00d0},
{&gcc_pdm2_clk.c, 0x00d2},
{&gcc_prng_ahb_clk.c, 0x00d8},
{&gcc_camss_csi1rdi_clk.c, 0x00e0},
{&gcc_camss_csi1pix_clk.c, 0x00e1},
{&gcc_camss_ispif_ahb_clk.c, 0x00e2},
{&gcc_boot_rom_ahb_clk.c, 0x00f8},
{&gcc_crypto_clk.c, 0x0138},
{&gcc_crypto_axi_clk.c, 0x0139},
{&gcc_crypto_ahb_clk.c, 0x013a},
{&gcc_oxili_gfx3d_clk.c, 0x01ea},
{&gcc_oxili_ahb_clk.c, 0x01eb},
{&gcc_oxili_gmem_clk.c, 0x01f0},
{&gcc_venus0_vcodec0_clk.c, 0x01f1},
{&gcc_venus0_core0_vcodec0_clk.c, 0x01b8},
{&gcc_venus0_core1_vcodec0_clk.c, 0x01b9},
{&gcc_venus0_axi_clk.c, 0x01f2},
{&gcc_venus0_ahb_clk.c, 0x01f3},
{&gcc_mdss_ahb_clk.c, 0x01f6},
{&gcc_mdss_axi_clk.c, 0x01f7},
{&gcc_mdss_pclk0_clk.c, 0x01f8},
{&gcc_mdss_pclk1_clk.c, 0x01ba},
{&gcc_mdss_mdp_clk.c, 0x01f9},
{&gcc_mdss_vsync_clk.c, 0x01fb},
{&gcc_mdss_byte0_clk.c, 0x01fc},
{&gcc_mdss_byte1_clk.c, 0x01bb},
{&gcc_mdss_esc0_clk.c, 0x01fd},
{&gcc_mdss_esc1_clk.c, 0x01bc},
{&gcc_bimc_gpu_clk.c, 0x0157},
{&gcc_cpp_tbu_clk.c, 0x00e9},
{&gcc_mdp_rt_tbu_clk.c, 0x00ee},
{&wcnss_m_clk.c, 0x0198},
),
.c = {
.dbg_name = "gcc_debug_mux",
.ops = &clk_ops_debug_mux,
.flags = CLKFLAG_NO_RATE_CACHE | CLKFLAG_MEASURE,
CLK_INIT(gcc_debug_mux.c),
},
};
/* Clock lookup */
static struct clk_lookup msm_clocks_lookup[] = {
/* PLLs */
CLK_LIST(gcc_xo),
CLK_LIST(xo_a_clk),
CLK_LIST(gpll0),
CLK_LIST(gpll0_ao),
CLK_LIST(gpll0_out_main),
CLK_LIST(gpll0_out_aux),
CLK_LIST(gpll0_misc),
CLK_LIST(gpll1),
CLK_LIST(gpll1_out_main),
CLK_LIST(gpll2),
CLK_LIST(gpll2_out_main),
CLK_LIST(gpll2_out_aux),
CLK_LIST(gpll3),
CLK_LIST(gpll3_out_main),
CLK_LIST(gpll3_out_aux),
CLK_LIST(gpll4),
CLK_LIST(gpll4_out_main),
CLK_LIST(gpll6),
CLK_LIST(gpll6_out_main),
CLK_LIST(a53ss_c0_pll),
CLK_LIST(a53ss_c1_pll),
CLK_LIST(a53ss_cci_pll),
/* RCGs */
CLK_LIST(apss_ahb_clk_src),
CLK_LIST(camss_top_ahb_clk_src),
CLK_LIST(csi0_clk_src),
CLK_LIST(csi1_clk_src),
CLK_LIST(csi2_clk_src),
CLK_LIST(vfe0_clk_src),
CLK_LIST(mdp_clk_src),
CLK_LIST(gfx3d_clk_src),
CLK_LIST(blsp1_qup1_i2c_apps_clk_src),
CLK_LIST(blsp1_qup1_spi_apps_clk_src),
CLK_LIST(blsp1_qup2_i2c_apps_clk_src),
CLK_LIST(blsp1_qup2_spi_apps_clk_src),
CLK_LIST(blsp1_qup3_i2c_apps_clk_src),
CLK_LIST(blsp1_qup3_spi_apps_clk_src),
CLK_LIST(blsp1_qup4_i2c_apps_clk_src),
CLK_LIST(blsp1_qup4_spi_apps_clk_src),
CLK_LIST(blsp1_qup5_i2c_apps_clk_src),
CLK_LIST(blsp1_qup5_spi_apps_clk_src),
CLK_LIST(blsp1_qup6_i2c_apps_clk_src),
CLK_LIST(blsp1_qup6_spi_apps_clk_src),
CLK_LIST(blsp1_uart1_apps_clk_src),
CLK_LIST(blsp1_uart2_apps_clk_src),
CLK_LIST(cci_clk_src),
CLK_LIST(camss_gp0_clk_src),
CLK_LIST(camss_gp1_clk_src),
CLK_LIST(jpeg0_clk_src),
CLK_LIST(mclk0_clk_src),
CLK_LIST(mclk1_clk_src),
CLK_LIST(mclk2_clk_src),
CLK_LIST(csi0phytimer_clk_src),
CLK_LIST(csi1phytimer_clk_src),
CLK_LIST(cpp_clk_src),
CLK_LIST(gp1_clk_src),
CLK_LIST(gp2_clk_src),
CLK_LIST(gp3_clk_src),
CLK_LIST(esc0_clk_src),
CLK_LIST(esc1_clk_src),
CLK_LIST(vsync_clk_src),
CLK_LIST(pdm2_clk_src),
CLK_LIST(sdcc1_apps_clk_src),
CLK_LIST(sdcc2_apps_clk_src),
CLK_LIST(usb_hs_system_clk_src),
CLK_LIST(usb_fs_system_clk_src),
CLK_LIST(usb_fs_ic_clk_src),
CLK_LIST(vcodec0_clk_src),
/* Voteable Clocks */
CLK_LIST(gcc_blsp1_ahb_clk),
CLK_LIST(gcc_boot_rom_ahb_clk),
CLK_LIST(gcc_prng_ahb_clk),
CLK_LIST(gcc_apss_tcu_clk),
CLK_LIST(gcc_gfx_tbu_clk),
CLK_LIST(gcc_gfx_tcu_clk),
CLK_LIST(gcc_gtcu_ahb_clk),
CLK_LIST(gcc_jpeg_tbu_clk),
CLK_LIST(gcc_mdp_tbu_clk),
CLK_LIST(gcc_smmu_cfg_clk),
CLK_LIST(gcc_venus_tbu_clk),
CLK_LIST(gcc_vfe_tbu_clk),
CLK_LIST(gcc_cpp_tbu_clk),
CLK_LIST(gcc_mdp_rt_tbu_clk),
/* Branches */
CLK_LIST(gcc_blsp1_qup1_i2c_apps_clk),
CLK_LIST(gcc_blsp1_qup1_spi_apps_clk),
CLK_LIST(gcc_blsp1_qup2_i2c_apps_clk),
CLK_LIST(gcc_blsp1_qup2_spi_apps_clk),
CLK_LIST(gcc_blsp1_qup3_i2c_apps_clk),
CLK_LIST(gcc_blsp1_qup3_spi_apps_clk),
CLK_LIST(gcc_blsp1_qup4_i2c_apps_clk),
CLK_LIST(gcc_blsp1_qup4_spi_apps_clk),
CLK_LIST(gcc_blsp1_qup5_i2c_apps_clk),
CLK_LIST(gcc_blsp1_qup5_spi_apps_clk),
CLK_LIST(gcc_blsp1_qup6_i2c_apps_clk),
CLK_LIST(gcc_blsp1_qup6_spi_apps_clk),
CLK_LIST(gcc_blsp1_uart1_apps_clk),
CLK_LIST(gcc_blsp1_uart2_apps_clk),
CLK_LIST(gcc_camss_cci_ahb_clk),
CLK_LIST(gcc_camss_cci_clk),
CLK_LIST(gcc_camss_csi0_ahb_clk),
CLK_LIST(gcc_camss_csi0_clk),
CLK_LIST(gcc_camss_csi0phy_clk),
CLK_LIST(gcc_camss_csi0pix_clk),
CLK_LIST(gcc_camss_csi0rdi_clk),
CLK_LIST(gcc_camss_csi1_ahb_clk),
CLK_LIST(gcc_camss_csi1_clk),
CLK_LIST(gcc_camss_csi1phy_clk),
CLK_LIST(gcc_camss_csi1pix_clk),
CLK_LIST(gcc_camss_csi1rdi_clk),
CLK_LIST(gcc_camss_csi2_ahb_clk),
CLK_LIST(gcc_camss_csi2_clk),
CLK_LIST(gcc_camss_csi2phy_clk),
CLK_LIST(gcc_camss_csi2pix_clk),
CLK_LIST(gcc_camss_csi2rdi_clk),
CLK_LIST(gcc_camss_csi_vfe0_clk),
CLK_LIST(gcc_camss_gp0_clk),
CLK_LIST(gcc_camss_gp1_clk),
CLK_LIST(gcc_camss_ispif_ahb_clk),
CLK_LIST(gcc_camss_jpeg0_clk),
CLK_LIST(gcc_camss_jpeg_ahb_clk),
CLK_LIST(gcc_camss_jpeg_axi_clk),
CLK_LIST(gcc_camss_mclk0_clk),
CLK_LIST(gcc_camss_mclk1_clk),
CLK_LIST(gcc_camss_mclk2_clk),
CLK_LIST(gcc_camss_micro_ahb_clk),
CLK_LIST(gcc_camss_csi0phytimer_clk),
CLK_LIST(gcc_camss_csi1phytimer_clk),
CLK_LIST(gcc_camss_ahb_clk),
CLK_LIST(gcc_camss_top_ahb_clk),
CLK_LIST(gcc_camss_cpp_ahb_clk),
CLK_LIST(gcc_camss_cpp_clk),
CLK_LIST(gcc_camss_vfe0_clk),
CLK_LIST(gcc_camss_vfe_ahb_clk),
CLK_LIST(gcc_camss_vfe_axi_clk),
CLK_LIST(gcc_oxili_gmem_clk),
CLK_LIST(gcc_gp1_clk),
CLK_LIST(gcc_gp2_clk),
CLK_LIST(gcc_gp3_clk),
CLK_LIST(gcc_mdss_ahb_clk),
CLK_LIST(gcc_mdss_axi_clk),
CLK_LIST(gcc_mdss_esc0_clk),
CLK_LIST(gcc_mdss_esc1_clk),
CLK_LIST(gcc_mdss_mdp_clk),
CLK_LIST(gcc_mdss_vsync_clk),
CLK_LIST(gcc_mss_cfg_ahb_clk),
CLK_LIST(gcc_mss_q6_bimc_axi_clk),
CLK_LIST(gcc_oxili_ahb_clk),
CLK_LIST(gcc_oxili_gfx3d_clk),
CLK_LIST(gcc_pdm2_clk),
CLK_LIST(gcc_pdm_ahb_clk),
CLK_LIST(gcc_sdcc1_ahb_clk),
CLK_LIST(gcc_sdcc1_apps_clk),
CLK_LIST(gcc_sdcc2_ahb_clk),
CLK_LIST(gcc_sdcc2_apps_clk),
CLK_LIST(gcc_usb2a_phy_sleep_clk),
CLK_LIST(gcc_usb_hs_ahb_clk),
CLK_LIST(gcc_usb_hs_system_clk),
CLK_LIST(gcc_usb_fs_ahb_clk),
CLK_LIST(gcc_usb_fs_ic_clk),
CLK_LIST(gcc_usb_fs_system_clk),
CLK_LIST(gcc_venus0_ahb_clk),
CLK_LIST(gcc_venus0_axi_clk),
CLK_LIST(gcc_venus0_vcodec0_clk),
CLK_LIST(gcc_venus0_core0_vcodec0_clk),
CLK_LIST(gcc_venus0_core1_vcodec0_clk),
CLK_LIST(gcc_bimc_gfx_clk),
CLK_LIST(gcc_bimc_gpu_clk),
CLK_LIST(wcnss_m_clk),
};
static struct clk_lookup msm_clocks_gcc_8936_crypto[] = {
/* Crypto clocks */
CLK_LOOKUP_OF("core_clk", gcc_crypto_clk, "scm"),
CLK_LOOKUP_OF("iface_clk", gcc_crypto_ahb_clk, "scm"),
CLK_LOOKUP_OF("bus_clk", gcc_crypto_axi_clk, "scm"),
CLK_LOOKUP_OF("core_clk_src", crypto_clk_src, "scm"),
};
/* Please note that the order of reg-names is important */
static int get_memory(struct platform_device *pdev)
{
int i, count;
const char *str;
struct resource *res;
struct device *dev = &pdev->dev;
count = of_property_count_strings(dev->of_node, "reg-names");
if (count != N_BASES) {
dev_err(dev, "missing reg-names property, expected %d strings\n",
N_BASES);
return -EINVAL;
}
for (i = 0; i < count; i++) {
of_property_read_string_index(dev->of_node, "reg-names", i,
&str);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, str);
if (!res) {
dev_err(dev, "Unable to retrieve register base.\n");
return -ENOMEM;
}
virt_bases[i] = devm_ioremap(dev, res->start,
resource_size(res));
if (!virt_bases[i]) {
dev_err(dev, "Failed to map in CC registers.\n");
return -ENOMEM;
}
}
return 0;
}
static int msm_gcc_probe(struct platform_device *pdev)
{
struct clk *tmp_clk;
int ret;
u32 regval;
ret = get_memory(pdev);
if (ret)
return ret;
vdd_dig.regulator[0] = devm_regulator_get(&pdev->dev, "vdd_dig");
if (IS_ERR(vdd_dig.regulator[0])) {
if (PTR_ERR(vdd_dig.regulator[0]) != -EPROBE_DEFER)
dev_err(&pdev->dev,
"Unable to get vdd_dig regulator!!!\n");
return PTR_ERR(vdd_dig.regulator[0]);
}
vdd_sr2_pll.regulator[0] = devm_regulator_get(&pdev->dev,
"vdd_sr2_pll");
if (IS_ERR(vdd_sr2_pll.regulator[0])) {
if (PTR_ERR(vdd_sr2_pll.regulator[0]) != -EPROBE_DEFER)
dev_err(&pdev->dev,
"Unable to get vdd_sr2_pll regulator!!!\n");
return PTR_ERR(vdd_sr2_pll.regulator[0]);
}
vdd_sr2_pll.regulator[1] = devm_regulator_get(&pdev->dev,
"vdd_sr2_dig");
if (IS_ERR(vdd_sr2_pll.regulator[1])) {
if (PTR_ERR(vdd_sr2_pll.regulator[1]) != -EPROBE_DEFER)
dev_err(&pdev->dev,
"Unable to get vdd_sr2_dig regulator!!!\n");
return PTR_ERR(vdd_sr2_pll.regulator[1]);
}
vdd_hf_pll.regulator[0] = devm_regulator_get(&pdev->dev,
"vdd_hf_pll");
if (IS_ERR(vdd_hf_pll.regulator[0])) {
if (PTR_ERR(vdd_hf_pll.regulator[0]) != -EPROBE_DEFER)
dev_err(&pdev->dev,
"Unable to get vdd_sr2_pll regulator!!!\n");
return PTR_ERR(vdd_hf_pll.regulator[0]);
}
vdd_hf_pll.regulator[1] = devm_regulator_get(&pdev->dev,
"vdd_hf_dig");
if (IS_ERR(vdd_hf_pll.regulator[1])) {
if (PTR_ERR(vdd_hf_pll.regulator[1]) != -EPROBE_DEFER)
dev_err(&pdev->dev,
"Unable to get vdd_hf_dig regulator!!!\n");
return PTR_ERR(vdd_hf_pll.regulator[1]);
}
tmp_clk = gcc_xo.c.parent = devm_clk_get(&pdev->dev, "xo");
if (IS_ERR(tmp_clk)) {
if (PTR_ERR(tmp_clk) != -EPROBE_DEFER)
dev_err(&pdev->dev, "Unable to get xo clock!!!\n");
return PTR_ERR(tmp_clk);
}
tmp_clk = xo_a_clk.c.parent = devm_clk_get(&pdev->dev, "xo_a");
if (IS_ERR(tmp_clk)) {
if (PTR_ERR(tmp_clk) != -EPROBE_DEFER)
dev_err(&pdev->dev, "Unable to get xo_a clock!!!\n");
return PTR_ERR(tmp_clk);
}
/* Vote for GPLL0 to turn on. Needed by acpuclock. */
regval = readl_relaxed(GCC_REG_BASE(APCS_GPLL_ENA_VOTE));
regval |= BIT(0);
writel_relaxed(regval, GCC_REG_BASE(APCS_GPLL_ENA_VOTE));
configure_sr_hpm_lp_pll(&gpll3_config, &gpll3_regs, 1);
configure_sr_hpm_lp_pll(&gpll4_config, &gpll4_regs, 1);
ret = of_msm_clock_register(pdev->dev.of_node,
msm_clocks_lookup,
ARRAY_SIZE(msm_clocks_lookup));
if (ret)
return ret;
ret = of_msm_clock_register(pdev->dev.of_node,
msm_clocks_gcc_8936_crypto,
ARRAY_SIZE(msm_clocks_gcc_8936_crypto));
if (ret)
return ret;
clk_set_rate(&apss_ahb_clk_src.c, 19200000);
clk_prepare_enable(&apss_ahb_clk_src.c);
dev_info(&pdev->dev, "Registered GCC clocks\n");
return 0;
}
static struct of_device_id msm_clock_gcc_match_table[] = {
{ .compatible = "qcom,gcc-8936" },
{}
};
static struct platform_driver msm_clock_gcc_driver = {
.probe = msm_gcc_probe,
.driver = {
.name = "qcom,gcc-8936",
.of_match_table = msm_clock_gcc_match_table,
.owner = THIS_MODULE,
},
};
static int __init msm_gcc_init(void)
{
return platform_driver_register(&msm_clock_gcc_driver);
}
arch_initcall(msm_gcc_init);
static struct clk_lookup msm_clocks_measure[] = {
CLK_LOOKUP_OF("measure", gcc_debug_mux, "debug"),
};
static int msm_clock_debug_probe(struct platform_device *pdev)
{
struct resource *res;
int ret;
clk_ops_debug_mux = clk_ops_gen_mux;
clk_ops_debug_mux.get_rate = measure_get_rate;
gcc_debug_mux_ops = mux_reg_ops;
gcc_debug_mux_ops.set_mux_sel = gcc_set_mux_sel;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "cc_base");
if (!res) {
dev_err(&pdev->dev, "Failed to get CC base.\n");
return -EINVAL;
}
virt_dbgbase = devm_ioremap(&pdev->dev, res->start, resource_size(res));
if (!virt_dbgbase) {
dev_err(&pdev->dev, "Failed to map in CC registers.\n");
return -ENOMEM;
}
rpm_debug_clk.c.parent = clk_get(&pdev->dev, "rpm_debug_mux");
if (IS_ERR(rpm_debug_clk.c.parent)) {
dev_err(&pdev->dev, "Failed to get RPM debug Mux\n");
return PTR_ERR(rpm_debug_clk.c.parent);
}
ret = of_msm_clock_register(pdev->dev.of_node, msm_clocks_measure,
ARRAY_SIZE(msm_clocks_measure));
if (ret) {
dev_err(&pdev->dev, "Failed to register debug Mux\n");
return ret;
}
dev_info(&pdev->dev, "Registered Debug Mux successfully\n");
return ret;
}
static struct of_device_id msm_clock_debug_match_table[] = {
{ .compatible = "qcom,cc-debug-8936" },
{}
};
static struct platform_driver msm_clock_debug_driver = {
.probe = msm_clock_debug_probe,
.driver = {
.name = "qcom,cc-debug-8936",
.of_match_table = msm_clock_debug_match_table,
.owner = THIS_MODULE,
},
};
static int __init msm_clock_debug_init(void)
{
return platform_driver_register(&msm_clock_debug_driver);
}
late_initcall(msm_clock_debug_init);
/* MDSS DSI_PHY_PLL */
static struct clk_lookup msm_clocks_gcc_mdss[] = {
CLK_LIST(byte0_clk_src),
CLK_LIST(byte1_clk_src),
CLK_LIST(pclk0_clk_src),
CLK_LIST(pclk1_clk_src),
CLK_LIST(gcc_mdss_pclk0_clk),
CLK_LIST(gcc_mdss_pclk1_clk),
CLK_LIST(gcc_mdss_byte0_clk),
CLK_LIST(gcc_mdss_byte1_clk),
};
static int msm_gcc_mdss_probe(struct platform_device *pdev)
{
int counter = 0, ret = 0;
struct clk *curr_p;
curr_p = pclk0_clk_src.c.parent = devm_clk_get(&pdev->dev, "pclk0_src");
if (IS_ERR(curr_p)) {
dev_err(&pdev->dev, "Failed to get pclk0 source.\n");
return PTR_ERR(curr_p);
}
for (counter = 0; counter < (sizeof(ftbl_gcc_mdss_pclk0_clk)/
sizeof(struct clk_freq_tbl)); counter++)
ftbl_gcc_mdss_pclk0_clk[counter].src_clk = curr_p;
curr_p = pclk1_clk_src.c.parent = devm_clk_get(&pdev->dev, "pclk1_src");
if (IS_ERR(curr_p)) {
dev_err(&pdev->dev, "Failed to get pclk1 source.\n");
ret = PTR_ERR(curr_p);
goto pclk1_fail;
}
for (counter = 0; counter < (sizeof(ftbl_gcc_mdss_pclk1_clk)/
sizeof(struct clk_freq_tbl)); counter++)
ftbl_gcc_mdss_pclk1_clk[counter].src_clk = curr_p;
curr_p = byte0_clk_src.c.parent = devm_clk_get(&pdev->dev, "byte0_src");
if (IS_ERR(curr_p)) {
dev_err(&pdev->dev, "Failed to get byte0 source.\n");
ret = PTR_ERR(curr_p);
goto byte0_fail;
}
for (counter = 0; counter < (sizeof(ftbl_gcc_mdss_byte0_clk)/
sizeof(struct clk_freq_tbl)); counter++)
ftbl_gcc_mdss_byte0_clk[counter].src_clk = curr_p;
curr_p = byte1_clk_src.c.parent = devm_clk_get(&pdev->dev, "byte1_src");
if (IS_ERR(curr_p)) {
dev_err(&pdev->dev, "Failed to get byte1 source.\n");
ret = PTR_ERR(curr_p);
goto byte1_fail;
}
for (counter = 0; counter < (sizeof(ftbl_gcc_mdss_byte1_clk)/
sizeof(struct clk_freq_tbl)); counter++)
ftbl_gcc_mdss_byte1_clk[counter].src_clk = curr_p;
ret = of_msm_clock_register(pdev->dev.of_node, msm_clocks_gcc_mdss,
ARRAY_SIZE(msm_clocks_gcc_mdss));
if (ret)
goto fail;
dev_info(&pdev->dev, "Registered GCC MDSS clocks.\n");
return ret;
fail:
devm_clk_put(&pdev->dev, byte1_clk_src.c.parent);
byte1_fail:
devm_clk_put(&pdev->dev, byte0_clk_src.c.parent);
byte0_fail:
devm_clk_put(&pdev->dev, pclk1_clk_src.c.parent);
pclk1_fail:
devm_clk_put(&pdev->dev, pclk0_clk_src.c.parent);
return ret;
}
static struct of_device_id msm_clock_mdss_match_table[] = {
{ .compatible = "qcom,gcc-mdss-8936" },
{}
};
static struct platform_driver msm_clock_gcc_mdss_driver = {
.probe = msm_gcc_mdss_probe,
.driver = {
.name = "gcc-mdss-8936",
.of_match_table = msm_clock_mdss_match_table,
.owner = THIS_MODULE,
},
};
static int __init msm_gcc_mdss_init(void)
{
return platform_driver_register(&msm_clock_gcc_mdss_driver);
}
fs_initcall_sync(msm_gcc_mdss_init);
|
Hacker432-Y550/android_kernel_huawei_msm8916
|
drivers/clk/qcom/clock-gcc-8936.c
|
C
|
gpl-2.0
| 98,279
|
#ifndef __CONFIGURE_H__
#define __CONFIGURE_H__
#include <string>
#include <libconfig.h++>
using namespace libconfig;
std::map<std::string,std::string> getConfiguration();
#endif
|
orges/pgnosql
|
config/configure.h
|
C
|
gpl-2.0
| 182
|
<?php
/**
* Add body classes if certain regions have content.
*/
function bartik_preprocess_html(&$variables) {
if (!empty($variables['page']['featured'])) {
$variables['classes_array'][] = 'featured';
}
if (!empty($variables['page']['triptych_first'])
|| !empty($variables['page']['triptych_middle'])
|| !empty($variables['page']['triptych_last'])) {
$variables['classes_array'][] = 'triptych';
}
if (!empty($variables['page']['footer_firstcolumn'])
|| !empty($variables['page']['footer_secondcolumn'])
|| !empty($variables['page']['footer_thirdcolumn'])
|| !empty($variables['page']['footer_fourthcolumn'])) {
$variables['classes_array'][] = 'footer-columns';
}
// Add conditional stylesheets for IE
drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
}
/**
* Override or insert variables into the page template for HTML output.
*/
function bartik_process_html(&$variables) {
// Hook into color.module.
if (module_exists('color')) {
_color_html_alter($variables);
}
}
/**
* Override or insert variables into the page template.
*/
function bartik_process_page(&$variables) {
// Hook into color.module.
if (module_exists('color')) {
_color_page_alter($variables);
}
// Always print the site name and slogan, but if they are toggled off, we'll
// just hide them visually.
$variables['hide_site_name'] = theme_get_setting('toggle_name') ? FALSE : TRUE;
$variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
if ($variables['hide_site_name']) {
// If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
$variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
}
if ($variables['hide_site_slogan']) {
// If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
$variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
}
// Since the title and the shortcut link are both block level elements,
// positioning them next to each other is much simpler with a wrapper div.
if (!empty($variables['title_suffix']['add_or_remove_shortcut']) && $variables['title']) {
// Add a wrapper div using the title_prefix and title_suffix render elements.
$variables['title_prefix']['shortcut_wrapper'] = array(
'#markup' => '<div class="shortcut-wrapper clearfix">',
'#weight' => 100,
);
$variables['title_suffix']['shortcut_wrapper'] = array(
'#markup' => '</div>',
'#weight' => -99,
);
// Make sure the shortcut link is the first item in title_suffix.
$variables['title_suffix']['add_or_remove_shortcut']['#weight'] = -100;
}
}
/**
* Implements hook_preprocess_maintenance_page().
*/
function bartik_preprocess_maintenance_page(&$variables) {
// By default, site_name is set to Drupal if no db connection is available
// or during site installation. Setting site_name to an empty string makes
// the site and update pages look cleaner.
// @see template_preprocess_maintenance_page
if (!$variables['db_is_active']) {
$variables['site_name'] = '';
}
drupal_add_css(drupal_get_path('theme', 'bartik') . '/css/maintenance-page.css');
}
/**
* Override or insert variables into the maintenance page template.
*/
function bartik_process_maintenance_page(&$variables) {
// Always print the site name and slogan, but if they are toggled off, we'll
// just hide them visually.
$variables['hide_site_name'] = theme_get_setting('toggle_name') ? FALSE : TRUE;
$variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
if ($variables['hide_site_name']) {
// If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
$variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
}
if ($variables['hide_site_slogan']) {
// If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
$variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
}
}
/**
* Override or insert variables into the node template.
*/
function bartik_preprocess_node(&$variables) {
if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
$variables['classes_array'][] = 'node-full';
}
}
/**
* Override or insert variables into the block template.
*/
function bartik_preprocess_block(&$variables) {
// In the header region visually hide block titles.
if ($variables['block']->region == 'header') {
$variables['title_attributes_array']['class'][] = 'element-invisible';
}
}
/**
* Implements theme_menu_tree().
*/
function bartik_menu_tree($variables) {
return '<ul class="menu clearfix">' . $variables['tree'] . '</ul>';
}
/**
* Implements theme_field__field_type().
*/
function bartik_field__taxonomy_term_reference($variables) {
$output = '';
// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
$output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
}
// Render the items.
$output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
foreach ($variables['items'] as $delta => $item) {
$output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
}
$output .= '</ul>';
// Render the top-level DIV.
$output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '"' . $variables['attributes'] .'>' . $output . '</div>';
return $output;
}
|
lukeberry99/infonow
|
themes/bartik/template.php
|
PHP
|
gpl-2.0
| 6,197
|
package mx.edukweb.tortuaak;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
private ProgressDialog pDialog;
// Clase JSONParser
JSONParser jsonParser = new JSONParser();
// si trabajan de manera local "localhost" :
// En windows tienen que ir, run CMD > ipconfig
// buscar su IP
// y poner de la siguiente manera
// "http://xxx.xxx.x.x:1234/cas/login.php";
// private static final String LOGIN_URL = "http://sislinkit.com/users/login2.php";
//http://basededatosremotas.meximas.com/cas/login.php
// http://edukwebmti.esy.es/login.php
private static final String LOGIN_URL = "http://chipvis.com/users/login2.php";
//private static final String LOGIN_URL = "http://basededatosremotas.meximas.com/cas/login.php";
// La respuesta del JSON es
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
// setup buttons
mSubmit = (Button) findViewById(R.id.login);
//mRegister = (Button) findViewById(R.id.register);
mSubmit.setOnClickListener(this);
// register listeners
// mRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
if(user.getText().toString().equals("") || pass.getText().toString().equals(""))
{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Información");
alertDialog.setMessage("El Usuario y Contraseña no pueden estar en blanco");
alertDialog.setButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// aquí puedes añadir funciones
}
});
//alertDialog.setIcon(R.drawable.icon);
alertDialog.show();
}
else
new AttemptLogin().execute();
break;
/* case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
*/
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Enviando información de login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
// cript(username);
// username=getCifrado(username, "SHA1");
password=getCifrado(password,"SHA1" );
//cript(password);
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("checar el cifrado!", password);
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("datos del json que descarga", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i = new Intent(Login.this, menusliding.class); //("la clase nada más"), existe una clase especial que te da cuales procesos aun estan activadas
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
public class SHA1 {
private MessageDigest md;
private byte[] buffer, digest;
private String hash = "";
public String getHash(String message) throws NoSuchAlgorithmException {
buffer = message.getBytes();
md = MessageDigest.getInstance("SHA1");
md.update(buffer);
digest = md.digest();
for(byte aux : digest) {
int b = aux & 0xff;
if (Integer.toHexString(b).length() == 1) hash += "0";
hash += Integer.toHexString(b);
}
return hash;}
}
public String cript(String pass){
SHA1 s = new SHA1();
//String basura="rwr24t5yt25y543td32ty6";
try {
// return s.getHash(s.getHash(pass+basura)+basura);
return s.getHash(s.getHash(pass));
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "0";}
private String getCifrado(String texto, String hashType) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
byte[] array = md.digest(texto.getBytes());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
System.err.println("Error "+e.getMessage());
}
return "";
}
}//Fin de clase
|
leonelpacheco/TortuAak
|
app/src/main/java/mx/edukweb/tortuaak/Login.java
|
Java
|
gpl-2.0
| 8,273
|
#!/usr/bin/perl -w
#
# used to test all mysql test suite cases.
#
my $test_log = "test_log";
if( -e $test_log){
print " $test_log exists, neednot make it again\n";
}else{
mkdir $test_log;
}
my @suites = ('main','innodb','binlog','engines','funcs_1','funcs_2','federated','jp','rpl','sys_vars','stress','parts','perfschema','perfschema_stress','manual','gcs');
#test each suite one by one,and log to the test_log/ dir as SUITE_NAME.LOG
foreach my $st (@suites){
print "start to test '${st}'\n";
if($st eq "engines"){
`perl ./mysql-test-run.pl --suite=engines/funcs --mysqld=--default-storage-engine=innodb --force >${test_log}/${st}_funcs.test.log 2>&1`;
`perl ./mysql-test-run.pl --suite=engines/iuds --mysqld=--default-storage-engine=innodb --force >${test_log}/${st}_iuds.test.log 2>&1`;
}else{
`perl mysql-test-run.pl --suite=$st --max-test-fail=100 --force >${test_log}/${st}.test.log 2>&1`;
}
print "finished test $st\n";
}
#`chmod +x ./suite/engines/rr_trx/run_stress_tx_rr.pl`;
#`./suite/engines/rr_trx/run_stress_tx_rr.pl --engine=InnoDB > run_stress_tx_rr.log 2>&1`;
#`./mtr --force --suite=extra/binlog_tests >${test_log}/extra_binlog.test.log 2>&1`;
#`./mtr --force --suite=extra/rpl_tests >${test_log}/extra_rpl_tests.test.log 2>&1`;
# `./mtr --force --suite=large_tests --big-test --suite-timeout=6360 --testcase-timeout=795 > ${test_log}/large_tests.test.log 2>&1`;
|
H0bby/GCS-SQL
|
mysql-test/test_mysql_suite.pl
|
Perl
|
gpl-2.0
| 1,462
|
# arduino-2009-projects
At the top level, this is a repo for projects I worked on in 2009 which used the Arduino.
|
ams0026/arduino-2009-projects
|
README.md
|
Markdown
|
gpl-2.0
| 116
|
<div class="wrap">
<h2><?php _e('Easy Wizard settings','wdeb'); ?></h2>
<?php if (defined('WP_NETWORK_ADMIN') && WP_NETWORK_ADMIN) { ?>
<form action="settings.php" method="post" enctype="multipart/form-data">
<?php } else { ?>
<form action="options.php" method="post" enctype="multipart/form-data">
<?php } ?>
<?php settings_fields('wdeb_wizard'); ?>
<?php do_settings_sections('wdeb_wizard'); ?>
<p class="submit">
<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
</p>
</form>
</div>
<div id="wdeb_step_edit_dialog" style="display:none">
<p>
<label><?php _e("Title", 'wdeb'); ?></label>
<input class="widefat" id="wdeb_step_edit_dialog_title" />
</p>
<p>
<label><?php _e("URL", 'wdeb'); ?></label>
<input class="widefat" id="wdeb_step_edit_dialog_url" />
</p>
<p>
<label><?php _e("Help", 'wdeb'); ?></label>
<textarea class="widefat" id="wdeb_step_edit_dialog_help"></textarea>
</p>
</div>
<style type="text/css">
.wdeb_step {
width: 400px;
height: 50px;
background: #eee;
margin-bottom: 1em;
cursor: move;
}
.wdeb_step h4 {
margin: 0;
float: left;
}
.wdeb_step .wdeb_step_actions {
float: right;
}
#wdeb_step_edit_dialog {
padding: 10px 20px;
}
</style>
<script type="text/javascript">
(function ($) {
$(function () {
function updateUrlPreview () {
var type = "<?php echo site_url(); ?>" + $("#wdeb_last_wizard_step_url_type").val();
var url = $("#wdeb_last_wizard_step_url").val();
var preview = type + url;
$("#wdeb_url_preview code").text(preview);
return true;
}
if (typeof $("#wdeb_steps").sortable != "undefined") {
$("#wdeb_steps")
.sortable({
"update": function () {
$("#wdeb_steps li").each(function (idx) {
$(this).find('h4 .wdeb_step_count').html(idx+1);
});
}
})
.disableSelection()
;
}
$(".wdeb_step_delete").click(function () {
$(this).parents('li.wdeb_step').remove();
return false;
});
$("#wdeb_last_wizard_step_url_type").change(updateUrlPreview);
$("#wdeb_last_wizard_step_url").keyup(updateUrlPreview);
$(".wdeb_step_edit").click(function () {
var $parent = $(this).parents('li.wdeb_step');
var $url = $parent.find('input:hidden.wdeb_step_url');
var $title = $parent.find('input:hidden.wdeb_step_title');
var $help = $parent.find('input:hidden.wdeb_step_help');
var $titleSpan = $parent.find('h4 .wdeb_step_title');
$("#wdeb_step_edit_dialog_title").val($title.val());
$("#wdeb_step_edit_dialog_url").val($url.val());
$("#wdeb_step_edit_dialog_help").val($help.val());
$("#wdeb_step_edit_dialog").dialog({
"dialogClass": "wp-dialog",
"title": $title.val(),
"modal": true,
"width": 600,
"close": function () {
$title.val($("#wdeb_step_edit_dialog_title").val());
$titleSpan.html($("#wdeb_step_edit_dialog_title").val());
$url.val($("#wdeb_step_edit_dialog_url").val());
$help.val($("#wdeb_step_edit_dialog_help").val());
}
});
return false;
});
updateUrlPreview();
});
})(jQuery);
</script>
|
olenk915/bersity
|
wp-content/plugins/easyblogging/lib/forms/wizard_settings.php
|
PHP
|
gpl-2.0
| 2,994
|
<!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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>My Project: ff_collections.zz_ChangeKey.Cmp Class Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">My Project
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.7 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="../../index.html"><span>Main Page</span></a></li>
<li><a href="../../namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="../../annotated.html"><span>Classes</span></a></li>
<li><a href="../../files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="../../search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="../../search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="../../annotated.html"><span>Class List</span></a></li>
<li><a href="../../classes.html"><span>Class Index</span></a></li>
<li><a href="../../hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="../../functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Variables</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="../../dc/d8f/namespaceff__collections.html">ff_collections</a></li><li class="navelem"><a class="el" href="../../dd/da4/namespaceff__collections_1_1zz___change_key.html">zz_ChangeKey</a></li><li class="navelem"><a class="el" href="../../d9/dd7/classff__collections_1_1zz___change_key_1_1_cmp.html">Cmp</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="../../de/d7b/classff__collections_1_1zz___change_key_1_1_cmp-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">ff_collections.zz_ChangeKey.Cmp Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="dynheader">
Inheritance diagram for ff_collections.zz_ChangeKey.Cmp:</div>
<div class="dyncontent">
<div class="center"><iframe scrolling="no" frameborder="0" src="../../d6/d04/classff__collections_1_1zz___change_key_1_1_cmp__inherit__graph.svg" width="182" height="228"><p><b>This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.</b></p></iframe>
</div>
</div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:ac9e4584d074c08c51f54feef241ba4dd"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d9/dd7/classff__collections_1_1zz___change_key_1_1_cmp.html#ac9e4584d074c08c51f54feef241ba4dd">compare</a> (Object o1, Object o2)</td></tr>
<tr class="separator:ac9e4584d074c08c51f54feef241ba4dd"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock">
<p>Definition at line <a class="el" href="../../db/d10/_cmp_8java_source.html#l00004">4</a> of file <a class="el" href="../../db/d10/_cmp_8java_source.html">Cmp.java</a>.</p>
</div><h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="ac9e4584d074c08c51f54feef241ba4dd"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int ff_collections.zz_ChangeKey.Cmp.compare </td>
<td>(</td>
<td class="paramtype">Object </td>
<td class="paramname"><em>o1</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">Object </td>
<td class="paramname"><em>o2</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../db/d10/_cmp_8java_source.html#l00005">5</a> of file <a class="el" href="../../db/d10/_cmp_8java_source.html">Cmp.java</a>.</p>
<div class="fragment"><div class="line"><a name="l00005"></a><span class="lineno"> 5</span>  {</div>
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span>  Agent a1 = (Agent) o1 ;</div>
<div class="line"><a name="l00007"></a><span class="lineno"> 7</span>  Agent a2 = (Agent) o2 ;</div>
<div class="line"><a name="l00008"></a><span class="lineno"> 8</span>  <span class="keywordflow">if</span> ( a1.getAge() > a2.getAge() ) {</div>
<div class="line"><a name="l00009"></a><span class="lineno"> 9</span>  <span class="keywordflow">return</span> 1 ;</div>
<div class="line"><a name="l00010"></a><span class="lineno"> 10</span>  } <span class="keywordflow">else</span> <span class="keywordflow">if</span> ( a1.getAge() == a2.getAge() ) {</div>
<div class="line"><a name="l00011"></a><span class="lineno"> 11</span>  <span class="keywordflow">return</span> 0 ;</div>
<div class="line"><a name="l00012"></a><span class="lineno"> 12</span>  } <span class="keywordflow">else</span> {</div>
<div class="line"><a name="l00013"></a><span class="lineno"> 13</span>  <span class="keywordflow">return</span> -1 ;</div>
<div class="line"><a name="l00014"></a><span class="lineno"> 14</span>  }</div>
<div class="line"><a name="l00015"></a><span class="lineno"> 15</span>  }</div>
</div><!-- fragment -->
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="../../db/d10/_cmp_8java_source.html">Cmp.java</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Dec 6 2016 10:08:52 for My Project by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.7
</small></address>
</body>
</html>
|
kainagel/teach-oop
|
html/d9/dd7/classff__collections_1_1zz___change_key_1_1_cmp.html
|
HTML
|
gpl-2.0
| 9,296
|
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
'SwebSocialAuth\Module' => __DIR__ . '/Module.php',
'SwebSocialAuth\Controller\SocialController' => __DIR__ . '/src/SwebSocialAuth/Controller/SocialController.php',
'SocialAuther\Adapter\AbstractAdapter' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/AbstractAdapter.php',
'SocialAuther\Adapter\AdapterInterface' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/AdapterInterface.php',
'SocialAuther\Adapter\Exception\ExceptionInterface' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Exception/ExceptionInterface.php',
'SocialAuther\Adapter\Exception\InvalidArgumentException' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Exception/InvalidArgumentException.php',
'SocialAuther\Adapter\Facebook' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Facebook.php',
'SocialAuther\Adapter\Google' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Google.php',
'SocialAuther\Adapter\Mailru' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Mailru.php',
'SocialAuther\Adapter\Odnoklassniki' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Odnoklassniki.php',
'SocialAuther\Adapter\Vk' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Vk.php',
'SocialAuther\Adapter\Yandex' => __DIR__ . '/src/SwebSocialAuth/Service/Adapter/Yandex.php',
'SocialAuther\Exception\ExceptionInterface' => __DIR__ . '/src/SwebSocialAuth/Service/Exception/ExceptionInterface.php',
'SocialAuther\Exception\InvalidArgumentException' => __DIR__ . '/src/SwebSocialAuth/Service/Exception/InvalidArgumentException.php',
'SocialAuther\SocialAuther' => __DIR__ . '/src/SwebSocialAuth/Service/SocialAuther.php',
'SwebSocialAuth\View\Helper\SocialAuth' => __DIR__ . '/src/SwebSocialAuth/View/Helper/SocialAuth.php',
);
|
stanislav-web/Social-Mobile
|
vendor/SwebSocialAuth/autoload_classmap.php
|
PHP
|
gpl-2.0
| 2,118
|
<?php
add_filter( 'manage_' . APPTHEMES_ORDER_PTYPE . '_posts_columns', 'appthemes_order_manage_columns' );
add_filter( 'manage_edit-' . APPTHEMES_ORDER_PTYPE . '_sortable_columns', 'appthemes_order_manage_sortable_columns' );
add_action( 'manage_' . APPTHEMES_ORDER_PTYPE . '_posts_custom_column', 'appthemes_order_add_column_data', 10, 2 );
add_action( 'admin_print_styles', 'appthemes_order_table_hide_elements' );
add_action( 'admin_init', 'appthemes_disable_post_new_order_page' );
/**
* Sets the columns for the orders page
* @param array $columns Currently available columns
* @return array New column order
*/
function appthemes_order_manage_columns( $columns ) {
$columns['order'] = __( 'Order', APP_TD );
$columns['order_author'] = __( 'Author', APP_TD );
$columns['item'] = __( 'Item', APP_TD );
$columns['price'] = __( 'Price', APP_TD );
$columns['order_date'] = __( 'Date', APP_TD );
$columns['payment'] = __( 'Payment', APP_TD );
unset( $columns['cb'] );
unset( $columns['title'] );
unset( $columns['author'] );
unset( $columns['date'] );
return $columns;
}
/**
* Sets the columns for the orders page
* @param array $columns Currently available columns
* @return array New column order
*/
function appthemes_order_manage_sortable_columns( $columns ) {
$columns['order'] = 'ID';
$columns['order_date'] = 'post_date';
$columns['order_author'] = 'author';
$columns['price'] = 'price';
$columns['payment'] = 'gateway';
return $columns;
}
/**
* Outputs column data for orders
* @param string $column_index Name of the column being processed
* @param int $post_id ID of order being dispalyed
* @return void
*/
function appthemes_order_add_column_data( $column_index, $post_id ) {
$order = appthemes_get_order( $post_id );
switch( $column_index ){
case 'order' :
echo '<a href="' . get_edit_post_link( $post_id ) . '">' . $order->get_ID() . '</a>';
break;
case 'order_author':
$user = get_userdata( $order->get_author() );
echo $user->display_name;
echo '<br>';
echo $order->get_ip_address();
break;
case 'item' :
$count = count( $order->get_items() );
$string = _n( 'Purchased %s item', 'Purchased %s items', $count, APP_TD );
printf( $string, $count );
break;
case 'price':
$currency = $order->get_currency();
if( !empty( $currency ) ){
echo appthemes_get_price( $order->get_total(), $order->get_currency() );
}else{
echo appthemes_get_price( $order->get_total() );
}
break;
case 'payment':
$gateway_id = $order->get_gateway();
if ( !empty( $gateway_id ) ) {
$gateway = APP_Gateway_Registry::get_gateway( $gateway_id );
if( $gateway ){
echo $gateway->display_name( 'admin' );
}else{
_e( 'Unknown', APP_TD );
}
}else{
_e( 'Undecided', APP_TD );
}
echo '</br>';
$status = $order->get_display_status();
if( $order->get_status() == APPTHEMES_ORDER_PENDING ){
echo '<strong>' . ucfirst( $status ) . '</strong>';
}else{
echo ucfirst( $status );
}
break;
case 'status':
echo ucfirst( $order->get_status() );
break;
case 'order_date':
$order_post = get_post( $order->get_ID() );
if ( '0000-00-00 00:00:00' == $order_post->post_date ) {
$t_time = $h_time = __( 'Unpublished', APP_TD );
$time_diff = 0;
} else {
$t_time = get_the_time( _x( 'Y/m/d g:i:s A', 'Order Date Format', APP_TD ) );
$m_time = $order_post->post_date;
$time = get_post_time( 'G', true, $order_post );
$time_diff = time() - $time;
if ( $time_diff > 0 && $time_diff < 24*60*60 )
$h_time = sprintf( __( '%s ago', APP_TD ), human_time_diff( $time ) );
else
$h_time = mysql2date( _x( 'Y/m/d', 'Order Date Format', APP_TD ), $m_time );
}
echo '<abbr title="' . $t_time . '">' . $h_time . '</abbr>';
break;
}
}
/**
* Hides elements of listing page
* @return void
*/
function appthemes_order_table_hide_elements() {
?>
<style type="text/css">
.post-type-transaction .top .actions:first-child,
.post-type-transaction .bottom .actions:first-child,
.post-type-transaction .wrap .add-new-h2 {
display: none;
}
</style>
<?php
}
/**
* Disables 'post new order' page
* @return void
*/
function appthemes_disable_post_new_order_page() {
if ( 'post-new.php' == $GLOBALS['pagenow'] && isset( $_GET['post_type'] ) && $_GET['post_type'] == APPTHEMES_ORDER_PTYPE ) {
wp_redirect( add_query_arg( 'post_type', APPTHEMES_ORDER_PTYPE, 'edit.php' ) );
exit;
}
}
|
dakshatechnologies/renovize
|
wp-content/themes/renovizenew/includes/payments/admin/order-list.php
|
PHP
|
gpl-2.0
| 4,583
|
/* Copyright (C) 2001-2004 Kenichi Suto
*
* 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.
*/
#include "defs.h"
#include "global.h"
#include "eb.h"
#include "selection.h"
#include "preference.h"
#include "headword.h"
#include "mainwindow.h"
static GtkWidget *fontsel_dlg;
static GtkWidget *entry_normal;
static GtkWidget *entry_bold;
static GtkWidget *entry_italic;
static GtkWidget *entry_super;
static gint font_no;
static void ok_fontsel(GtkWidget *widget,gpointer *data){
gchar *fontname;
LOG(LOG_DEBUG, "IN : ok_fontsel()");
fontname = gtk_font_selection_dialog_get_font_name(GTK_FONT_SELECTION_DIALOG(fontsel_dlg));
LOG(LOG_DEBUG, "fontname = %s", fontname);
switch(font_no){
case 0:
gtk_entry_set_text(GTK_ENTRY(entry_normal), fontname);
break;
case 1:
gtk_entry_set_text(GTK_ENTRY(entry_bold), fontname);
break;
case 2:
gtk_entry_set_text(GTK_ENTRY(entry_italic), fontname);
break;
case 3:
gtk_entry_set_text(GTK_ENTRY(entry_super), fontname);
break;
}
gtk_grab_remove(fontsel_dlg);
gtk_widget_destroy(fontsel_dlg);
LOG(LOG_DEBUG, "OUT : ok_fontsel()");
}
static void delete_fontsel( GtkWidget *widget,
GdkEvent *event,
gpointer data )
{
LOG(LOG_DEBUG, "IN : delete_fontsel()");
ok_fontsel(NULL, NULL);
LOG(LOG_DEBUG, "OUT : delete_fontsel()");
}
static void show_fontsel(GtkWidget *widget,gpointer *data){
const gchar *fontname=NULL;
LOG(LOG_DEBUG, "IN : show_fontsel()");
font_no = GPOINTER_TO_INT(data);
fontsel_dlg = gtk_font_selection_dialog_new("Please select font");
g_signal_connect(G_OBJECT (fontsel_dlg), "delete_event",
G_CALLBACK(delete_fontsel), NULL);
g_signal_connect(G_OBJECT(GTK_FONT_SELECTION_DIALOG (fontsel_dlg)->ok_button), "clicked",
G_CALLBACK(ok_fontsel), NULL);
g_signal_connect_swapped(G_OBJECT(GTK_FONT_SELECTION_DIALOG (fontsel_dlg)->cancel_button), "clicked",
G_CALLBACK(gtk_widget_destroy), (gpointer)fontsel_dlg);
gtk_widget_destroy(GTK_FONT_SELECTION_DIALOG (fontsel_dlg)->apply_button);
switch(font_no){
case 0:
fontname = gtk_entry_get_text(GTK_ENTRY(entry_normal));
break;
case 1:
fontname = gtk_entry_get_text(GTK_ENTRY(entry_bold));
break;
case 2:
fontname = gtk_entry_get_text(GTK_ENTRY(entry_italic));
break;
case 3:
fontname = gtk_entry_get_text(GTK_ENTRY(entry_super));
break;
}
gtk_font_selection_dialog_set_font_name(GTK_FONT_SELECTION_DIALOG(fontsel_dlg), fontname);
gtk_widget_show_all(fontsel_dlg);
gtk_grab_add(fontsel_dlg);
LOG(LOG_DEBUG, "OUT : show_fontsel()");
}
gboolean pref_end_font()
{
const gchar *fontname;
LOG(LOG_DEBUG, "IN : pref_end_font()");
// Program aborts if you unload. Why ?
//unload_font();
fontname = gtk_entry_get_text(GTK_ENTRY(entry_normal));
free(fontset_normal);
fontset_normal = strdup(fontname);
fontname = gtk_entry_get_text(GTK_ENTRY(entry_bold));
free(fontset_bold);
fontset_bold = strdup(fontname);
fontname = gtk_entry_get_text(GTK_ENTRY(entry_italic));
free(fontset_italic);
fontset_italic = strdup(fontname);
fontname = gtk_entry_get_text(GTK_ENTRY(entry_super));
free(fontset_superscript);
fontset_superscript = strdup(fontname);
return(TRUE);
LOG(LOG_DEBUG, "OUT : pref_end_font()");
}
GtkWidget *pref_start_font(){
GtkWidget *vbox;
GtkWidget *button;
GtkWidget *table;
GtkWidget *label;
GtkAttachOptions xoption=0, yoption=0;
LOG(LOG_DEBUG, "IN : pref_start_font()");
vbox = gtk_vbox_new(FALSE, 0);
table = gtk_table_new(3, 5, FALSE);
gtk_box_pack_start (GTK_BOX(vbox)
, table,FALSE, FALSE, 0);
label = gtk_label_new(_("Normal"));
gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1,
xoption, yoption, 10, 10);
entry_normal = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(entry_normal), fontset_normal);
gtk_widget_set_size_request(entry_normal,200,20);
gtk_table_attach(GTK_TABLE(table), entry_normal, 1, 2, 0, 1,
xoption, yoption, 10, 10);
button = gtk_button_new_with_label(_("Choose"));
g_signal_connect(G_OBJECT (button), "clicked",
G_CALLBACK(show_fontsel), (gpointer)0);
gtk_table_attach(GTK_TABLE(table), button, 2, 3, 0, 1,
xoption, yoption, 10, 10);
label = gtk_label_new(_("Bold"));
gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
xoption, yoption, 10, 10);
entry_bold = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(entry_bold), fontset_bold);
gtk_widget_set_size_request(entry_bold,200,20);
gtk_table_attach(GTK_TABLE(table), entry_bold, 1, 2, 1, 2,
xoption, yoption, 10, 10);
button = gtk_button_new_with_label(_("Choose"));
g_signal_connect(G_OBJECT (button), "clicked",
G_CALLBACK(show_fontsel), (gpointer)1);
gtk_table_attach(GTK_TABLE(table), button, 2, 3, 1, 2,
xoption, yoption, 10, 10);
label = gtk_label_new(_("Italic"));
gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3,
xoption, yoption, 10, 10);
entry_italic = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(entry_italic), fontset_italic);
gtk_widget_set_size_request(entry_italic,200,20);
gtk_table_attach(GTK_TABLE(table), entry_italic, 1, 2, 2, 3,
xoption, yoption, 10, 10);
button = gtk_button_new_with_label(_("Choose"));
g_signal_connect(G_OBJECT (button), "clicked",
G_CALLBACK(show_fontsel), (gpointer)2);
gtk_table_attach(GTK_TABLE(table), button, 2, 3, 2, 3,
xoption, yoption, 10, 10);
label = gtk_label_new(_("Superscript"));
gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4,
xoption, yoption, 10, 10);
entry_super = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(entry_super), fontset_superscript);
gtk_widget_set_size_request(entry_super,200,20);
gtk_table_attach(GTK_TABLE(table), entry_super, 1, 2, 3, 4,
xoption, yoption, 10, 10);
button = gtk_button_new_with_label(_("Choose"));
g_signal_connect(G_OBJECT (button), "clicked",
G_CALLBACK(show_fontsel), (gpointer)3);
gtk_table_attach(GTK_TABLE(table), button, 2, 3, 3, 4,
xoption, yoption, 10, 10);
LOG(LOG_DEBUG, "OUT : pref_start_font()");
return(vbox);
}
|
fujii/ebview
|
src/pref_font.c
|
C
|
gpl-2.0
| 6,696
|
# Copyright (C) 2013-2021 Roland Lutz
#
# 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.
import xorn.storage
rev = xorn.storage.Revision()
ob0 = rev.add_object(xorn.storage.Line())
ob1, = rev.get_objects()
ob2 = rev.add_object(xorn.storage.Line())
assert ob0 is not ob1
assert ob0 == ob1
assert hash(ob0) == hash(ob1)
assert ob0 is not ob2
assert ob0 != ob2
assert hash(ob0) != hash(ob2)
assert ob1 is not ob2
assert ob1 != ob2
assert hash(ob1) != hash(ob2)
|
rlutz/xorn
|
tests/cpython/storage/ob_equality.py
|
Python
|
gpl-2.0
| 1,119
|
<?php
class PoP_UserCommunities_ModuleProcessor_AuthorSectionBlocks extends PoP_Module_Processor_AuthorTabPanelSectionBlocksBase
{
public const MODULE_BLOCK_TABPANEL_AUTHORCOMMUNITYMEMBERS = 'block-tabpanel-authorcommunitymembers';
public function getModulesToProcess(): array
{
return array(
[self::class, self::MODULE_BLOCK_TABPANEL_AUTHORCOMMUNITYMEMBERS],
);
}
public function getInnerSubmodules(array $module): array
{
$ret = parent::getInnerSubmodules($module);
$inners = array(
self::MODULE_BLOCK_TABPANEL_AUTHORCOMMUNITYMEMBERS => [PoP_UserCommunities_ModuleProcessor_AuthorSectionTabPanelComponents::class, PoP_UserCommunities_ModuleProcessor_AuthorSectionTabPanelComponents::MODULE_TABPANEL_AUTHORCOMMUNITYMEMBERS],
);
if ($inner = $inners[$module[1]] ?? null) {
$ret[] = $inner;
}
return $ret;
}
public function getDelegatorfilterSubmodule(array $module)
{
switch ($module[1]) {
case self::MODULE_BLOCK_TABPANEL_AUTHORCOMMUNITYMEMBERS:
return [PoP_Module_Processor_CustomFilters::class, PoP_Module_Processor_CustomFilters::MODULE_FILTER_AUTHORCOMMUNITYMEMBERS];
}
return parent::getDelegatorfilterSubmodule($module);
}
}
|
leoloso/PoP
|
layers/Legacy/Schema/packages/migrate-everythingelse/migrate/plugins/pop-usercommunities-processors/plugins/pop-application-processors/plugins/pop-bootstrap-processors/library/processors/blocks/tabpanels-authorsections.php
|
PHP
|
gpl-2.0
| 1,332
|
/**
* External dependencies
*/
import Dispatcher from 'dispatcher';
const wpcom = require( 'lib/wp' ).undocumented();
/**
* Internal dependencies
*/
import { actionTypes } from './constants';
import { toApi } from './common';
export function cancelImport( importerId ) {
Dispatcher.handleViewAction( {
type: actionTypes.CANCEL_IMPORT,
importerId
} );
}
export function failUpload( importerId, error ) {
Dispatcher.handleViewAction( {
type: actionTypes.FAIL_UPLOAD,
importerId,
error
} );
}
export function finishUpload( importerId, importerStatus ) {
Dispatcher.handleViewAction( {
type: actionTypes.FINISH_UPLOAD,
importerId, importerStatus
} );
}
export function mapAuthor( importerId, sourceAuthor, targetAuthor ) {
Dispatcher.handleViewAction( {
type: actionTypes.MAP_AUTHORS,
importerId,
sourceAuthor,
targetAuthor
} );
}
export function resetImport( importerId ) {
Dispatcher.handleViewAction( {
type: actionTypes.RESET_IMPORT,
importerId
} );
}
// Use when developing to force a new state into the store
export function setState( newState ) {
Dispatcher.handleViewAction( {
type: actionTypes.DEV_SET_STATE,
newState
} );
}
export function startMappingAuthors( importerId ) {
Dispatcher.handleViewAction( {
type: actionTypes.START_MAPPING_AUTHORS,
importerId
} );
}
export function setUploadProgress( importerId, data ) {
Dispatcher.handleViewAction( {
type: actionTypes.SET_UPLOAD_PROGRESS,
uploadLoaded: data.uploadLoaded,
uploadTotal: data.uploadTotal,
importerId
} );
}
export function startImport( importerType ) {
// Dev-only: this will come from an API call
let importerId = `${ Math.round( Math.random() * 10000 ) }`;
Dispatcher.handleViewAction( {
type: actionTypes.START_IMPORT,
importerId,
importerType
} );
}
export function startImporting( importerStatus ) {
const { importerId, site: { ID: siteId } } = importerStatus;
Dispatcher.handleViewAction( {
type: actionTypes.START_IMPORTING,
importerId
} );
wpcom.updateImporter( siteId, toApi( importerStatus ) );
}
export function startUpload( importerStatus, file ) {
let { id: importerId, site: { ID: siteId } } = importerStatus;
Dispatcher.handleViewAction( {
type: actionTypes.START_UPLOAD,
filename: file.name,
importerId
} );
wpcom.uploadExportFile( siteId, {
importStatus: toApi( importerStatus ),
file,
onload: ( error, data ) => {
if ( ! error ) {
return finishUpload( importerId, data );
}
failUpload( importerId, error.message );
},
onprogress: event => {
setUploadProgress( importerId, {
uploadLoaded: event.loaded,
uploadTotal: event.total
} );
},
onabort: () => cancelImport( importerId )
} );
}
|
ironmanLee/my_calypso
|
client/lib/importer/actions.js
|
JavaScript
|
gpl-2.0
| 2,728
|
<?php
/**
* Widget Wrangler Sidebar Widget class.
* This class handles everything that needs to be handled with the widget:
* the settings, form, display, and update. Nice!
*
* @since 0.1
*/
class WidgetWrangler_Widget_Widget extends WP_Widget {
/**
* Widget setup.
*/
function __construct()
{
// Widget settings.
$widget_ops = array( 'classname' => 'widget-wrangler-widget-widget-classname', 'description' => __('A single Widget Wrangler Widget', 'widgetwrangler') );
// Widget control settings.
$control_ops = array( 'id_base' => 'widget-wrangler-widget');
// Create the widget.
$this->WP_Widget( 'widget-wrangler-widget', __('Widget Wrangler - Widget', 'widgetwrangler'), $widget_ops, $control_ops );
global $widget_wrangler;
$this->ww = $widget_wrangler;
}
/**
* How to display the widget on the screen.
*/
function widget( $args, $instance )
{
if ($widget = $this->ww->get_single_widget($instance['post_id'])){
print $this->ww->display->theme_single_widget($instance['post_id'], $args);
}
}
/**
* Update the widget settings.
*/
function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['post_id'] = $new_instance['post_id'];
return $instance;
}
/**
* Displays the widget settings controls on the widget panel.
* Make use of the get_field_id() and get_field_name() function
* when creating your form elements. This handles the confusing stuff.
*/
function form( $instance )
{
// Set up some default widget settings.
$defaults = array( 'title' => __('Widget Wrangler Corral', 'widgetwrangler'), 'post_id' => '' );
$instance = wp_parse_args( (array) $instance, $defaults );
$widgets = $this->ww->get_all_widgets(array('publish', 'draft'));
?>
<?php // Widget Title: Hidden Input ?>
<input type="hidden" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $sidebars[$instance['sidebar']]; ?>" style="width:100%;" />
<?php // Sidebar: Select Box ?>
<p>
<label for="<?php echo $this->get_field_id( 'post_id' ); ?>"><?php _e('Widget:', 'widgetwrangler'); ?></label>
<select id="<?php echo $this->get_field_id( 'post_id' ); ?>" name="<?php echo $this->get_field_name( 'post_id' ); ?>" class="widefat" style="width:100%;">
<?php
foreach($widgets as $widget)
{
?>
<option <?php if ($instance['post_id'] == $widget->ID){ print 'selected="selected"'; }?> value="<?php print $widget->ID; ?>"><?php print $widget->post_title. ($widget->post_status == "draft") ? " - <em>(draft)</em>" : ""; ?></option>
<?php
}
?>
</select>
</p>
<?php
}
}
|
truedaz/rockvegas
|
wp-content/plugins/widget-wrangler/common/wp-widget-ww-widget.php
|
PHP
|
gpl-2.0
| 2,943
|
// printf関数、及びscanf関数を使用するために必要
#include <stdio.h>
// int型を返すmain関数の宣言
int main() {
// 変数の宣言
// 配列の宣言は name[size] で行う。添字は0〜(size-1)まで占有している。
int i;
int a[11];
float tmp;
// 入力
for (i = 0; i <= 10; i++) {
// scanf関数。標準入力から入力を取得する。
// scanfには変数のアドレスを渡すため、& を語頭に付与する。
// scanf(フォーマット指定子, 変数)
scanf("%d", &a[i]);
}
// 計算
tmp = a[10];
for (i = 10; i >= 1; i--) {
tmp = a[i-1] + (1 / tmp);
}
// printf関数。フォーマット指定子に従って標準出力に出力する。
// printf(フォーマット指定子, 変数)
printf("%f\n", tmp);
// main関数の正常終了
return 0;
}
|
conao/develop
|
c/pj/6/kadai6-3.c
|
C
|
gpl-2.0
| 939
|
/****************************************************************************
** $Id: qt/canvas.cpp 3.3.8 edited Jan 11 14:37 $
**
** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include "canvas.h"
#include <qapplication.h>
#include <qpainter.h>
#include <qevent.h>
#include <qrect.h>
const bool no_writing = FALSE;
Canvas::Canvas( QWidget *parent, const char *name, WFlags fl )
: QWidget( parent, name, WStaticContents | fl ),
pen( Qt::red, 3 ), polyline(3),
mousePressed( FALSE ), oldPressure( 0 ), saveColor( red ),
buffer( width(), height() )
{
if ((qApp->argc() > 0) && !buffer.load(qApp->argv()[1]))
buffer.fill( colorGroup().base() );
setBackgroundMode( QWidget::PaletteBase );
#ifndef QT_NO_CURSOR
setCursor( Qt::crossCursor );
#endif
}
void Canvas::save( const QString &filename, const QString &format )
{
if ( !no_writing )
buffer.save( filename, format.upper() );
}
void Canvas::clearScreen()
{
buffer.fill( colorGroup().base() );
repaint( FALSE );
}
void Canvas::mousePressEvent( QMouseEvent *e )
{
mousePressed = TRUE;
polyline[2] = polyline[1] = polyline[0] = e->pos();
}
void Canvas::mouseReleaseEvent( QMouseEvent * )
{
mousePressed = FALSE;
}
void Canvas::mouseMoveEvent( QMouseEvent *e )
{
if ( mousePressed ) {
QPainter painter;
painter.begin( &buffer );
painter.setPen( pen );
polyline[2] = polyline[1];
polyline[1] = polyline[0];
polyline[0] = e->pos();
painter.drawPolyline( polyline );
painter.end();
QRect r = polyline.boundingRect();
r = r.normalize();
r.setLeft( r.left() - penWidth() );
r.setTop( r.top() - penWidth() );
r.setRight( r.right() + penWidth() );
r.setBottom( r.bottom() + penWidth() );
bitBlt( this, r.x(), r.y(), &buffer, r.x(), r.y(), r.width(), r.height() );
}
}
void Canvas::tabletEvent( QTabletEvent *e )
{
e->accept();
// change the width based on range of pressure
if ( e->device() == QTabletEvent::Stylus ) {
if ( e->pressure() >= 0 && e->pressure() <= 32 )
pen.setColor( saveColor.light(175) );
else if ( e->pressure() > 32 && e->pressure() <= 64 )
pen.setColor( saveColor.light(150) );
else if ( e->pressure() > 64 && e->pressure() <= 96 )
pen.setColor( saveColor.light(125) );
else if ( e->pressure() > 96 && e->pressure() <= 128 )
pen.setColor( saveColor );
else if ( e->pressure() > 128 && e->pressure() <= 160 )
pen.setColor( saveColor.dark(150) );
else if ( e->pressure() > 160 && e->pressure() <= 192 )
pen.setColor( saveColor.dark(200) );
else if ( e->pressure() > 192 && e->pressure() <= 224 )
pen.setColor( saveColor.dark(250) );
else // pressure > 224
pen.setColor( saveColor.dark(300) );
} else if ( e->device() == QTabletEvent::Eraser
&& pen.color() != backgroundColor() ) {
pen.setColor( backgroundColor() );
}
int xt = e->xTilt();
int yt = e->yTilt();
if ( ( xt > -15 && xt < 15 ) && ( yt > -15 && yt < 15 ) )
pen.setWidth( 3 );
else if ( ((xt < -15 && xt > -30) || (xt > 15 && xt < 30)) &&
((yt < -15 && yt > -30) || (yt > 15 && yt < 30 )) )
pen.setWidth( 6 );
else if ( ((xt < -30 && xt > -45) || (xt > 30 && xt < 45)) &&
((yt < -30 && yt > -45) || (yt > 30 && yt < 45)) )
pen.setWidth( 9 );
else if ( (xt < -45 || xt > 45 ) && ( yt < -45 || yt > 45 ) )
pen.setWidth( 12 );
switch ( e->type() ) {
case QEvent::TabletPress:
mousePressed = TRUE;
polyline[2] = polyline[1] = polyline[0] = e->pos();
break;
case QEvent::TabletRelease:
mousePressed = FALSE;
break;
case QEvent::TabletMove:
if ( mousePressed ) {
QPainter painter;
painter.begin( &buffer );
painter.setPen( pen );
polyline[2] = polyline[1];
polyline[1] = polyline[0];
polyline[0] = e->pos();
painter.drawPolyline( polyline );
painter.end();
QRect r = polyline.boundingRect();
r = r.normalize();
r.setLeft( r.left() - penWidth() );
r.setTop( r.top() - penWidth() );
r.setRight( r.right() + penWidth() );
r.setBottom( r.bottom() + penWidth() );
bitBlt( this, r.x(), r.y(), &buffer, r.x(), r.y(), r.width(),
r.height() );
}
break;
default:
break;
}
}
void Canvas::resizeEvent( QResizeEvent *e )
{
QWidget::resizeEvent( e );
int w = width() > buffer.width() ?
width() : buffer.width();
int h = height() > buffer.height() ?
height() : buffer.height();
QPixmap tmp( buffer );
buffer.resize( w, h );
buffer.fill( colorGroup().base() );
bitBlt( &buffer, 0, 0, &tmp, 0, 0, tmp.width(), tmp.height() );
}
void Canvas::paintEvent( QPaintEvent *e )
{
QWidget::paintEvent( e );
QMemArray<QRect> rects = e->region().rects();
for ( uint i = 0; i < rects.count(); i++ ) {
QRect r = rects[(int)i];
bitBlt( this, r.x(), r.y(), &buffer, r.x(), r.y(), r.width(), r.height() );
}
}
|
epatel/qt-mac-free-3.3.8
|
examples/tablet/canvas.cpp
|
C++
|
gpl-2.0
| 5,117
|
<!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' xml:lang='en' lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>row</title>
<link href='reno.css' type='text/css' rel='stylesheet'/>
</head>
<body>
<div class="body-0">
<div class="body-1">
<div class="body-2">
<div>
<h1>QVM: Quaternions, Vectors, Matrices</h1>
</div>
<!-- Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc. -->
<!-- Distributed under the Boost Software License, Version 1.0. (See accompanying -->
<!-- file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -->
<div class="RenoIncludeDIV"><div class="RenoAutoDIV"><h3>row</h3>
</div>
<div class="RenoIncludeDIV"><p><span class="RenoEscape">#<!--<wiki>`#</wiki>--></span>include <<span class="RenoLink"><a href="boost_qvm_map_mat_vec_hpp.html">boost/qvm/map_mat_vec.hpp</a></span>></p>
<pre>namespace boost
{
namespace <span class="RenoLink"><a href="qvm.html">qvm</a></span>
{
<span class="RenoIncludeSPAN"> //Only <span class="RenoLink"><a href="SFINAE_enable_if.html">enabled if</a></span>: <span class="RenoLink"><a href="is_mat.html">is_mat</a></span><A>::value
template <int C,class A>
-unspecified-return-type- <span class="RenoLink">row</span>( A & a );</span>
}
}</pre>
</div><p>The expression <i><span class="RenoLink">row</span><R>(m)</i> returns a <span class="RenoLink"><a href="view_proxy.html">view proxy</a></span> that accesses row <i>R</i> of the matrix <i>m</i> as a vector.</p>
</div><div class="RenoAutoDIV"><div class="RenoHR"><hr/></div>
See also: <span class="RenoPageList"><a href="boost_qvm_map_mat_vec_hpp.html">boost/qvm/map_mat_vec.hpp</a></span>
</div>
<!-- Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc. -->
<!-- Distributed under the Boost Software License, Version 1.0. (See accompanying -->
<!-- file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -->
<div id="footer">
<p>
<a class="logo" href="http://jigsaw.w3.org/css-validator/check/referer"><img class="logo_pic" src="valid-css.png" alt="Valid CSS" height="31" width="88"/></a>
<a class="logo" href="http://validator.w3.org/check?uri=referer"><img class="logo_pic" src="valid-xhtml.png" alt="Valid XHTML 1.0" height="31" width="88"/></a>
<small>Copyright (c) 2008-2016 by Emil Dotchevski and Reverge Studios, Inc.<br/>
Distributed under the <a href="http://www.boost.org/LICENSE_1_0.txt">Boost Software License, Version 1.0</a>.</small>
</p>
</div>
</div>
</div>
</div>
</body>
</html>
|
FFMG/myoddweb.piger
|
myodd/boost/libs/qvm/doc/row.html
|
HTML
|
gpl-2.0
| 2,680
|
package pt.c02oo.s12interface.s01pessoa;
public interface Alguem
{
public String getNome();
}
|
santanche/java2learn
|
src/java/src/pt/c02oo/s12interface/s01pessoa/Alguem.java
|
Java
|
gpl-2.0
| 105
|
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'cweagans\\Composer\\' => array($vendorDir . '/cweagans/composer-patches/src'),
'Zumba\\Mink\\Driver\\' => array($vendorDir . '/jcalderonzumba/mink-phantomjs-driver/src'),
'Zumba\\GastonJS\\' => array($vendorDir . '/jcalderonzumba/gastonjs/src'),
'Zend\\Stdlib\\' => array($vendorDir . '/zendframework/zend-stdlib/src'),
'Zend\\Feed\\' => array($vendorDir . '/zendframework/zend-feed/src'),
'Zend\\Escaper\\' => array($vendorDir . '/zendframework/zend-escaper/src'),
'Zend\\Diactoros\\' => array($vendorDir . '/zendframework/zend-diactoros/src'),
'XdgBaseDir\\' => array($vendorDir . '/dnoegel/php-xdg-base-dir/src'),
'Webmozart\\PathUtil\\' => array($vendorDir . '/webmozart/path-util/src'),
'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'),
'Twig\\' => array($vendorDir . '/twig/twig/src'),
'Symfony\\Polyfill\\Php55\\' => array($vendorDir . '/symfony/polyfill-php55'),
'Symfony\\Polyfill\\Php54\\' => array($vendorDir . '/symfony/polyfill-php54'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Iconv\\' => array($vendorDir . '/symfony/polyfill-iconv'),
'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'),
'Symfony\\Component\\VarDumper\\' => array($vendorDir . '/symfony/var-dumper'),
'Symfony\\Component\\Validator\\' => array($vendorDir . '/symfony/validator'),
'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
'Symfony\\Component\\Serializer\\' => array($vendorDir . '/symfony/serializer'),
'Symfony\\Component\\Routing\\' => array($vendorDir . '/symfony/routing'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\HttpKernel\\' => array($vendorDir . '/symfony/http-kernel'),
'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'),
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'),
'Symfony\\Component\\ExpressionLanguage\\' => array($vendorDir . '/symfony/expression-language'),
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\DomCrawler\\' => array($vendorDir . '/symfony/dom-crawler'),
'Symfony\\Component\\DependencyInjection\\' => array($vendorDir . '/symfony/dependency-injection'),
'Symfony\\Component\\Debug\\' => array($vendorDir . '/symfony/debug'),
'Symfony\\Component\\CssSelector\\' => array($vendorDir . '/symfony/css-selector'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Symfony\\Component\\Config\\' => array($vendorDir . '/symfony/config'),
'Symfony\\Component\\ClassLoader\\' => array($vendorDir . '/symfony/class-loader'),
'Symfony\\Component\\BrowserKit\\' => array($vendorDir . '/symfony/browser-kit'),
'Symfony\\Cmf\\Component\\Routing\\' => array($vendorDir . '/symfony-cmf/routing'),
'Symfony\\Bridge\\PsrHttpMessage\\' => array($vendorDir . '/symfony/psr-http-message-bridge'),
'Stecman\\Component\\Symfony\\Console\\BashCompletion\\' => array($vendorDir . '/stecman/symfony-console-completion/src'),
'Relaxed\\Replicator\\' => array($vendorDir . '/relaxedws/replicator/src'),
'Relaxed\\LCA\\' => array($vendorDir . '/relaxedws/lca/src'),
'RedBeanPHP\\' => array($vendorDir . '/gabordemooij/redbean/RedBeanPHP'),
'Psy\\' => array($vendorDir . '/psy/psysh/src/Psy'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'PhpParser\\' => array($vendorDir . '/nikic/php-parser/lib/PhpParser'),
'Masterminds\\' => array($vendorDir . '/masterminds/html5/src'),
'Interop\\Container\\' => array($vendorDir . '/container-interop/container-interop/src/Interop/Container'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
'Graphp\\Algorithms\\' => array($vendorDir . '/graphp/algorithms/src'),
'Goutte\\' => array($vendorDir . '/fabpot/goutte/Goutte'),
'Fhaculty\\Graph\\' => array($vendorDir . '/clue/graph/src'),
'Facebook\\InstantArticles\\' => array($vendorDir . '/facebook/facebook-instant-articles-sdk-php/src/Facebook/InstantArticles'),
'Facebook\\' => array($vendorDir . '/facebook/graph-sdk/src/Facebook'),
'Drupal\\Driver\\' => array($baseDir . '/web/drivers/lib/Drupal/Driver'),
'Drupal\\Core\\' => array($baseDir . '/web/core/lib/Drupal/Core'),
'Drupal\\Console\\Dotenv\\' => array($vendorDir . '/drupal/console-dotenv/src'),
'Drupal\\Console\\Core\\' => array($vendorDir . '/drupal/console-core/src'),
'Drupal\\Console\\Composer\\Plugin\\' => array($vendorDir . '/drupal/console-extend-plugin/src'),
'Drupal\\Console\\' => array($vendorDir . '/drupal/console/src'),
'Drupal\\Component\\' => array($baseDir . '/web/core/lib/Drupal/Component'),
'DrupalComposer\\DrupalScaffold\\' => array($vendorDir . '/drupal-composer/drupal-scaffold/src'),
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
'Doctrine\\Common\\Cache\\' => array($vendorDir . '/doctrine/cache/lib/Doctrine/Common/Cache'),
'Doctrine\\Common\\' => array($vendorDir . '/doctrine/common/lib/Doctrine/Common'),
'Consolidation\\OutputFormatters\\' => array($vendorDir . '/consolidation/output-formatters/src'),
'Consolidation\\AnnotatedCommand\\' => array($vendorDir . '/consolidation/annotated-command/src'),
'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'),
'Composer\\Installers\\' => array($vendorDir . '/composer/installers/src/Composer/Installers'),
'Behat\\Mink\\Driver\\' => array($vendorDir . '/behat/mink-browserkit-driver/src', $vendorDir . '/behat/mink-goutte-driver/src', $vendorDir . '/behat/mink-selenium2-driver/src'),
'Behat\\Mink\\' => array($vendorDir . '/behat/mink/src'),
'Asm89\\Stack\\' => array($vendorDir . '/asm89/stack-cors/src/Asm89/Stack'),
'Alchemy\\Zippy\\' => array($vendorDir . '/alchemy/zippy/src'),
);
|
jeromewiley/supermag
|
vendor/composer/autoload_psr4.php
|
PHP
|
gpl-2.0
| 6,618
|
//
// Copyright (C) 2006-2017 Christoph Sommer <sommer@ccs-labs.org>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// 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
//
//
// Veins Mobility module for the INET Framework (i.e., implementing inet::IMobility)
// Based on inet::MobilityBase of INET Framework v3.4.0
//
#undef INET_IMPORT
#include "inet/common/INETMath.h"
#include "veins_inet/VeinsInetMobility.h"
#include "inet/visualizer/mobility/MobilityCanvasVisualizer.h"
namespace Veins {
using inet::Coord;
Register_Class(VeinsInetMobility);
//
// Public, lifecycle
//
VeinsInetMobility::VeinsInetMobility() :
visualRepresentation(nullptr),
constraintAreaMin(Coord::ZERO),
constraintAreaMax(Coord::ZERO),
lastPosition(Coord::ZERO),
lastSpeed(Coord::ZERO),
lastOrientation(inet::EulerAngles::ZERO) {
}
//
// Public, called from manager
//
void VeinsInetMobility::preInitialize(std::string external_id, const inet::Coord& position, std::string road_id, double speed, double angle) {
Enter_Method_Silent();
lastPosition = position;
lastSpeed = Coord(cos(angle), -sin(angle));
lastOrientation.alpha = -angle;
}
void VeinsInetMobility::nextPosition(const inet::Coord& position, std::string road_id, double speed, double angle) {
Enter_Method_Silent();
lastPosition = position;
lastSpeed = Coord(cos(angle), -sin(angle));
lastOrientation.alpha = -angle;
emitMobilityStateChangedSignal();
updateVisualRepresentation();
}
//
// Public, implementing IMobility interface
//
double VeinsInetMobility::getMaxSpeed() const {
return NaN;
}
Coord VeinsInetMobility::getCurrentPosition() {
return lastPosition;
}
Coord VeinsInetMobility::getCurrentSpeed() {
return lastSpeed;
}
inet::EulerAngles VeinsInetMobility::getCurrentAngularPosition() {
return lastOrientation;
}
//
// Protected
//
void VeinsInetMobility::initialize(int stage) {
cSimpleModule::initialize(stage);
//EV_TRACE << "initializing VeinsInetMobility stage " << stage << endl;
if (stage == inet::INITSTAGE_LOCAL) {
constraintAreaMin.x = par("constraintAreaMinX");
constraintAreaMin.y = par("constraintAreaMinY");
constraintAreaMin.z = par("constraintAreaMinZ");
constraintAreaMax.x = par("constraintAreaMaxX");
constraintAreaMax.y = par("constraintAreaMaxY");
constraintAreaMax.z = par("constraintAreaMaxZ");
bool visualizeMobility = par("visualizeMobility");
if (visualizeMobility) {
visualRepresentation = inet::getModuleFromPar<cModule>(par("visualRepresentation"), this);
}
WATCH(constraintAreaMin);
WATCH(constraintAreaMax);
WATCH(lastPosition);
WATCH(lastSpeed);
WATCH(lastOrientation);
}
else if (stage == inet::INITSTAGE_PHYSICAL_ENVIRONMENT_2) {
if (visualRepresentation != nullptr) {
auto visualizationTarget = visualRepresentation->getParentModule();
canvasProjection = inet::CanvasProjection::getCanvasProjection(visualizationTarget->getCanvas());
}
emitMobilityStateChangedSignal();
updateVisualRepresentation();
}
}
void VeinsInetMobility::handleMessage(cMessage *message) {
throw cRuntimeError("This module does not handle messages");
}
void VeinsInetMobility::updateVisualRepresentation() {
EV_DEBUG << "current position = " << lastPosition << endl;
if (hasGUI() && visualRepresentation != nullptr) {
inet::visualizer::MobilityCanvasVisualizer::setPosition(visualRepresentation, canvasProjection->computeCanvasPoint(getCurrentPosition()));
}
}
void VeinsInetMobility::emitMobilityStateChangedSignal() {
emit(mobilityStateChangedSignal, this);
}
} // namespace veins
|
namnatulco/veins
|
subprojects/veins_inet/src/veins_inet/VeinsInetMobility.cc
|
C++
|
gpl-2.0
| 4,227
|
<?php
/*
* Copyright (C) Vulcan Inc.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
/**
* @file
* @ingroup WebAdmin
*
* @defgroup WebAdmin Web-administration tool
* @ingroup DeployFramework
*
* Installation tool.
*
* @author: Kai Kühn
*
*/
// uncomment the lines to get detailed error information
// DO NOT use error reporting in production use.
// error_reporting(E_ALL);
// ini_set('display_errors', "On");
session_start();
$hostname = $_SERVER['HTTP_HOST'];
$path = dirname($_SERVER['PHP_SELF']);
$proto = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != '' ? "https" : "http";
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
if (!empty($_GET["rs"]) || !empty($_POST["rs"])) {
// ajax call but no session, deny
echo "session: time-out";
exit;
} else {
header('Location: '.$proto.'://'.$hostname.($path == '/' ? '' : $path).'/login.php');
exit;
}
}
define("DF_WEBADMIN_TOOL", 1);
define("DF_WEBADMIN_TOOL_VERSION", '{{$VERSION}}');
define("DF_WEBADMIN_TOOL_VERSION_AND_BUILD", '{{$VERSION}} [B${env.BUILD_NUMBER}]');
$rootDir = dirname(__FILE__);
$rootDir = str_replace("\\", "/", $rootDir);
$rootDir = realpath($rootDir."/../../");
$mwrootDir = dirname(__FILE__);
$mwrootDir = str_replace("\\", "/", $mwrootDir);
$mwrootDir = realpath($mwrootDir."/../../../");
if(!file_exists($rootDir.'/settings.php')) {
echo "settings.php not found! Forgot to copy it from config/settings.php?";
die();
}
require_once($mwrootDir.'/deployment/settings.php');
$wgScriptPath=isset(DF_Config::$scriptPath) ? DF_Config::$scriptPath : "/mediawiki";
$smwgDFIP=$rootDir;
// touch the login marker
touch("$rootDir/tools/webadmin/sessiondata/userloggedin");
require_once($mwrootDir.'/deployment/languages/DF_Language.php');
require_once('includes/DF_SettingsTab.php');
require_once('includes/DF_ContentBundleTab.php');
require_once('includes/DF_LogTab.php');
require_once('includes/DF_ProfilerTab.php');
require_once('includes/DF_StatusTab.php');
require_once('includes/DF_SearchTab.php');
require_once('includes/DF_MaintenanceTab.php');
require_once('includes/DF_UploadTab.php');
require_once('includes/DF_RepositoriesTab.php');
require_once('includes/DF_ServersTab.php');
require_once('includes/DF_LocalSettingsTab.php');
require_once('includes/DF_CommandInterface.php');
require_once($mwrootDir.'/deployment/io/DF_Log.php');
require_once($mwrootDir.'/deployment/io/DF_PrintoutStream.php');
$dfgOut = DFPrintoutStream::getInstance(DF_OUTPUT_FORMAT_HTML);
try {
Logger::getInstance();
Rollback::getInstance($mwrootDir);
} catch(DF_SettingError $e) {
echo "<h1>Installation problem</h1>";
echo $e->getMsg();
die();
}
dffInitLanguage();
// set server
$wgServer = '';
if( isset( $_SERVER['SERVER_NAME'] ) ) {
$wgServerName = $_SERVER['SERVER_NAME'];
} elseif( isset( $_SERVER['HOSTNAME'] ) ) {
$wgServerName = $_SERVER['HOSTNAME'];
} elseif( isset( $_SERVER['HTTP_HOST'] ) ) {
$wgServerName = $_SERVER['HTTP_HOST'];
} elseif( isset( $_SERVER['SERVER_ADDR'] ) ) {
$wgServerName = $_SERVER['SERVER_ADDR'];
} else {
$wgServerName = 'localhost';
}
# check if server use https:
$wgProto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
$wgServer = $wgProto.'://' . $wgServerName;
# If the port is a non-standard one, add it to the URL
if( isset( $_SERVER['SERVER_PORT'] )
&& !strpos( $wgServerName, ':' )
&& ( ( $wgProto == 'http' && $_SERVER['SERVER_PORT'] != 80 )
|| ( $wgProto == 'https' && $_SERVER['SERVER_PORT'] != 443 ) ) ) {
$wgServer .= ":" . $_SERVER['SERVER_PORT'];
}
// check for ajax call
$mode = "";
if ( ! empty( $_GET["rs"] ) ) {
$mode = "get";
}
if ( !empty( $_POST["rs"] ) ) {
$mode = "post";
}
switch( $mode ) {
case 'get':
$func_name = isset( $_GET["rs"] ) ? $_GET["rs"] : '';
if ( ! empty( $_GET["rsargs"] ) ) {
$args = $_GET["rsargs"];
} else {
$args = array();
}
break;
case 'post':
$func_name = isset( $_POST["rs"] ) ? $_POST["rs"] : '';
if ( ! empty( $_POST["rsargs"] ) ) {
$args = $_POST["rsargs"];
} else {
$args = array();
}
break;
}
$dfgStatusTab = new DFStatusTab();
$dfgSearchTab = new DFSearchTab();
$dfgMaintenanceTab = new DFMaintenanceTab();
$dfgUploadTab = new DFUploadTab();
$dfgSettingsTab = new DFRepositoriesTab();
$dfgLocalSettingsTab = new DFLocalSettingsTab();
$dfgServersTab = new DFServersTab();
$dfgLogTab = new DFLogTab();
$dfgProfilerTab = new DFProfilerTab();
$dfgContentBundlesTab = new DFContentBundleTab();
$dfgWATSettingsTab = new DFSettingsTab();
// for ajax calls
if (isset($func_name)) {
$dfgCommandInterface = new DFCommandInterface();
$ret = $dfgCommandInterface->dispatch($func_name, $args);
if (is_string($ret)) echo $ret;
die();
}
// initialize tabs
try {
$statusTabName = $dfgStatusTab->getTabName();
$statusTabHtml = $dfgStatusTab->getHTML();
$searchTabName = $dfgSearchTab->getTabName();
$searchTabHtml = $dfgSearchTab->getHTML();
$maintenanceTabName = $dfgMaintenanceTab->getTabName();
$maintenanceTabHtml = $dfgMaintenanceTab->getHTML();
$dfgUploadTabName = $dfgUploadTab->getTabName();
$dfgUploadTabHtml = $dfgUploadTab->getHTML();
$dfgSettingsTabName = $dfgSettingsTab->getTabName();
$dfgSettingsTabHtml = $dfgSettingsTab->getHTML();
$dfgLocalSettingsTabName = $dfgLocalSettingsTab->getTabName();
$dfgLocalSettingsTabHtml = $dfgLocalSettingsTab->getHTML();
$dfgServersTabName = $dfgServersTab->getTabName();
$dfgServersTabHtml = $dfgServersTab->getHTML();
$dfgLogTabName = $dfgLogTab->getTabName();
$dfgLogTabHtml = $dfgLogTab->getHTML();
$dfgContentBundlesTabName = $dfgContentBundlesTab->getTabName();
$dfgContentBundlesTabHtml = $dfgContentBundlesTab->getHTML();
$dfgWATSettingsBundlesTabName = $dfgWATSettingsTab->getTabName();
$dfgWATSettingsBundlesTabHtml = $dfgWATSettingsTab->getHTML();
$dfgProfilerTabName = $dfgProfilerTab->getTabName();
$dfgProfilerTabHtml = $dfgProfilerTab->getHTML();
} catch(DF_SettingError $e) {
echo $e->getMsg();
die();
}
if (!isset(DF_Config::$df_lang)) {
$dfgLangCode = "En";
} else {
$dfgLangCode = ucfirst(DF_Config::$df_lang);
}
$javascriptLang = '<script type="text/javascript" src="scripts/languages/DF_WebAdmin_User'.$dfgLangCode.'.js"></script>';
$javascriptLang .= '<script type="text/javascript" src="scripts/languages/DF_WebAdmin_Language.js"></script>';
if (isset($_GET['tab'])) {
$selectedTab = $_GET['tab'];
} else {
$selectedTab = 0;
}
$dfVersion = DF_WEBADMIN_TOOL_VERSION_AND_BUILD;
Tools::isWindows($dfOS);
$heading = $dfgLang->getLanguageString('df_webadmin');
if (isset(DF_Config::$df_developerVersion) && DF_Config::$df_developerVersion == true) {
$scriptTags = <<<ENDS
<script type="text/javascript" src="scripts/webadminOperations.js"></script>
<script type="text/javascript" src="scripts/webadminGlobal.js"></script>
<script type="text/javascript" src="scripts/webadminRepositories.js"></script>
<script type="text/javascript" src="scripts/webadminMaintenance.js"></script>
<script type="text/javascript" src="scripts/webadminSearch.js"></script>
<script type="text/javascript" src="scripts/webadminStatus.js"></script>
<script type="text/javascript" src="scripts/webadminServers.js"></script>
<script type="text/javascript" src="scripts/webadminContentBundle.js"></script>
<script type="text/javascript" src="scripts/webadminUpload.js"></script>
<script type="text/javascript" src="scripts/webadminLocalSettings.js"></script>
<script type="text/javascript" src="scripts/webadminLogs.js"></script>
<script type="text/javascript" src="scripts/webadminSettings.js"></script>
<script type="text/javascript" src="scripts/webadminProfiler.js"></script>
ENDS;
} else {
$scriptTags = '<script type="text/javascript" src="scripts/webadmin_all.js"></script>';
}
$html = <<<ENDS
<!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" dir="ltr" lang="en-gb" xml:lang="en-gb">
<head>
<title>$heading</title>
<link type="text/css" href="skins/ui-lightness/jquery-ui-1.8.13.custom.css" rel="stylesheet" />
<link type="text/css" href="skins/webadmin.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="scripts/jquery.json-2.3.js"></script>
<script type="text/javascript">
wgServer="$wgServer";
wgScriptPath="$wgScriptPath";
dfgVersion="$dfVersion";
dfgOS="$dfOS";
$(function(){
// Tabs
$('#tabs').tabs( { selected: $selectedTab });
});
</script>
$javascriptLang
<script type="text/javascript" src="scripts/sorttable.js"></script>
$scriptTags
</head>
ENDS
;
$wikiName = !empty(DF_Config::$df_wikiName) ? "(".DF_Config::$df_wikiName.")" : "";
$html .= "<body><img src=\"skins/logo.png\" style=\"float:left; margin-right: 30px\" />".
"<div style=\"float:right\">".
"<a id=\"df_webadmin_aboutlink\">".$dfgLang->getLanguageString('df_webadmin_about')."</a> | ".
"<a href=\"$wgServer$wgScriptPath/index.php\" target=\"_blank\">".$dfgLang->getLanguageString('df_linktowiki')."</a> | ".
"<a href=\"$wgServer$wgScriptPath/deployment/tools/webadmin/logout.php\">".$dfgLang->getLanguageString('df_logout')."</a>".
"</div>".
"<div id=\"df_header\">$heading $wikiName</div>";
$restoreWarning = $dfgLang->getLanguageString('df_restore_warning');
$restoreRemoveWarning = $dfgLang->getLanguageString('df_remove_restore_warning');
$deinstallWarning = $dfgLang->getLanguageString('df_uninstall_warning');
$globalUpdateWarning = $dfgLang->getLanguageString('df_globalupdate_warning');
$checkExtensionHeading = $dfgLang->getLanguageString('df_inspectextension_heading');
$deinstallHeading = $dfgLang->getLanguageString('df_webadmin_deinstall');
$globalUpdateHeading = $dfgLang->getLanguageString('df_webadmin_globalupdate');
$updateHeading = $dfgLang->getLanguageString('df_webadmin_update');
$restoreHeading = $dfgLang->getLanguageString('df_webadmin_maintenacetab');
$html .= <<<ENDS
<div id="tabs">
<ul>
<li><a href="#tabs-1">$statusTabName</a></li>
<li><a href="#tabs-2">$searchTabName</a></li>
<li><a href="#tabs-3">$dfgUploadTabName</a></li>
<li><a href="#tabs-4">$maintenanceTabName</a></li>
<li><a href="#tabs-5">$dfgSettingsTabName</a></li>
<li><a href="#tabs-6">$dfgLocalSettingsTabName</a></li>
<li><a href="#tabs-7">$dfgServersTabName</a></li>
<li><a href="#tabs-8">$dfgLogTabName</a></li>
<li><a href="#tabs-9">$dfgContentBundlesTabName</a></li>
<li><a href="#tabs-10">$dfgWATSettingsBundlesTabName</a></li>
<li><a href="#tabs-11">$dfgProfilerTabName</a></li>
</ul>
<div id="tabs-1">$statusTabHtml</div>
<div id="tabs-2">$searchTabHtml</div>
<div id="tabs-3">$dfgUploadTabHtml</div>
<div id="tabs-4">$maintenanceTabHtml</div>
<div id="tabs-5">$dfgSettingsTabHtml</div>
<div id="tabs-6">$dfgLocalSettingsTabHtml</div>
<div id="tabs-7">$dfgServersTabHtml</div>
<div id="tabs-8">$dfgLogTabHtml</div>
<div id="tabs-9">$dfgContentBundlesTabHtml</div>
<div id="tabs-10">$dfgWATSettingsBundlesTabHtml</div>
<div id="tabs-11">$dfgProfilerTabHtml</div>
</div>
<div id="global-updatedialog-confirm" title="$globalUpdateHeading" style="display:none">
<p><span style="float:left; margin:0 7px 20px 0;"></span><span id="global-updatedialog-confirm-text">$globalUpdateWarning</span></p>
</div>
<div id="updatedialog-confirm" title="$updateHeading" style="display:none">
<p><span style="float:left; margin:0 7px 20px 0;"></span><span id="updatedialog-confirm-text"></span></p>
</div>
<div id="deinstall-dialog-confirm" title="$deinstallHeading" style="display:none">
<p><span style="float:left; margin:0 7px 20px 0;"></span><span id="deinstall-dialog-confirm-text">$deinstallWarning</span></p>
</div>
<div id="restore-dialog-confirm" title="$restoreHeading" style="display:none">
<p><span style="float:left; margin:0 7px 20px 0;"></span><span id="restore-dialog-confirm-text">$restoreWarning</span></p>
</div>
<div id="remove-restore-dialog-confirm" title="$restoreHeading" style="display:none">
<p><span style="float:left; margin:0 7px 20px 0;"></span><span id="restore-dialog-confirm-text">$restoreRemoveWarning</span></p>
</div>
<div id="check-extension-dialog" title="$checkExtensionHeading" style="display:none">
<p><span style="float:left; margin:0 7px 20px 0;"></span><span id="check-extension-dialog-text"></span></p>
</div>
<div id="df_extension_details" style="display:none"></div>
<div id="df_install_dialog" style="display:none"></div>
<div id="df_webadmin_about_dialog" style="display:none"></div>
ENDS
;
$html .= "</body>";
echo $html;
die();
|
ontoprise/HaloSMWExtension
|
deployment/tools/webadmin/index.php
|
PHP
|
gpl-2.0
| 14,114
|
#include <iostream>
using namespace std;
int v,n,m,w[31];
void dfs(int c, int w1)
{
if(w1>v) return;
if(v-w1<m) m=v-w1;
if(m==0) return;
for(w1+=w[c];c<n;c++)
dfs(c+1,w1);
}
int main()
{
cin>>v>>n;m=v;
for(int i = 0; i < n; i++) cin>>w[i];
dfs(0,0);
cout<<m<<endl;
return 0;
}
|
iwtwiioi/OnlineJudge
|
wikioi/Run_176606_Score_80_Date_2013-08-10.cpp
|
C++
|
gpl-2.0
| 334
|
OVERVIEW
========
General instructions for installing, building and running
the PebblePointer apps.
These directions are written with an Linux-as-dev-system perspective.
This code was developed and tested on a Nexus-7 2nd Gen.
It is assumed that you have installed --
the Pebble SDK, and
the Android SDK with Eclipse installed
PREPARE A WORKSPACE FOR PEBBLEPOINTER
=====================================
1) Create new workspace (optional) assume: ~/workspace
mkdir ~/workspace
cd ~/workspace
2) Checkout PebblePointer from github
git clone https://github.com/foldedtoad/PebblePointer.git
SETTING UP THE ANDROID PROJECT
==============================
3) Start Eclipse and "Switch Workspace" to new workspace
[File]-->[Switch Workspace]-->[other] { navigate to your workspace } [OK]
4) Import PEBBLE_KIT project into Eclipse.
[File]-->[Import]-->[Android]-->[Existing Android Code Into Workspace]-->[Next]
[Browse] { pebble-dev/PebbleSDK-2.2/PebbleKit-Android/PebbleKit } [OK]
Be sure "Project to Import" is checked for PEBBLE_KIT.
[Finish]
You should now see "PEBBLE_KIT" listed in Package Explorer in Eclipse.
5) Import the Android app project.
[File]-->[Import]-->[Android]-->[Existing Android Code Into Workspace]-->[Next]
[Browse] { ~/workspace/PebblePointer/android-app } [OK]
Be sure "Project to Import" is checked for MainActivity.
[Finish]
You should now see "MainActivity" listed in Package Explorer in Eclipse.
6) If you see an red X by the src directory, then do the following
In the "Package Explorer", select MainActivity so it is hi-lited.
[Project]-->[Properties]-->[Android]
If you see a red X in the Reference box, then
Select and [Remove] it.
[Add], select "PEBBLE_KIT", then [OK]
[Apply] then [OK]
Else skip this step.
7) You should now be able to build and load (debug) the Android app on your
target system.
BUILDING THE PEBBLE WATCH APP
==============================
8) From a command shell, navigate to { ~/workspace/Pebble/watch-app }
9) Review the "make.sh" file
10) Run `PEBBLE_IP=196.168.1.2 ./make.sh`, which will do a build, load and go sequence
for the watch app. Set `PEBBLE_IP` to the IP address of your target Android
device which is bound to your Pebble watch.
|
foldedtoad/PebblePointer
|
README.md
|
Markdown
|
gpl-2.0
| 2,381
|
/*
* linux/fs/super.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* super.c contains code to handle: - mount structures
* - super-block tables
* - filesystem drivers list
* - mount system call
* - umount system call
* - ustat system call
*
* GK 2/5/95 - Changed to support mounting the root fs via NFS
*
* Added kerneld support: Jacques Gelinas and Bjorn Ekwall
* Added change_root: Werner Almesberger & Hans Lermen, Feb '96
* Added options to /proc/mounts:
* Torbjörn Lindh (torbjorn.lindh@gopta.se), April 14, 1996.
* Added devfs support: Richard Gooch <rgooch@atnf.csiro.au>, 13-JAN-1998
* Heavily rewritten for 'one fs - one tree' dcache architecture. AV, Mar 2000
*/
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/writeback.h> /* for the emergency remount stuff */
#include <linux/idr.h>
#include <linux/mutex.h>
#include <linux/backing-dev.h>
#include <linux/rculist_bl.h>
#include <linux/cleancache.h>
#include <linux/fsnotify.h>
#include <linux/lockdep.h>
#include "internal.h"
LIST_HEAD(super_blocks);
static DEFINE_SPINLOCK(sb_lock);
static char *sb_writers_name[SB_FREEZE_LEVELS] = {
"sb_writers",
"sb_pagefaults",
"sb_internal",
};
/*
* One thing we have to be careful of with a per-sb shrinker is that we don't
* drop the last active reference to the superblock from within the shrinker.
* If that happens we could trigger unregistering the shrinker from within the
* shrinker path and that leads to deadlock on the shrinker_rwsem. Hence we
* take a passive reference to the superblock to avoid this from occurring.
*/
static unsigned long super_cache_scan(struct shrinker *shrink,
struct shrink_control *sc)
{
struct super_block *sb;
long fs_objects = 0;
long total_objects;
long freed = 0;
long dentries;
long inodes;
sb = container_of(shrink, struct super_block, s_shrink);
/*
* Deadlock avoidance. We may hold various FS locks, and we don't want
* to recurse into the FS that called us in clear_inode() and friends..
*/
if (!(sc->gfp_mask & __GFP_FS))
return SHRINK_STOP;
if (!trylock_super(sb))
return SHRINK_STOP;
if (sb->s_op->nr_cached_objects)
fs_objects = sb->s_op->nr_cached_objects(sb, sc);
inodes = list_lru_shrink_count(&sb->s_inode_lru, sc);
dentries = list_lru_shrink_count(&sb->s_dentry_lru, sc);
total_objects = dentries + inodes + fs_objects + 1;
if (!total_objects)
total_objects = 1;
/* proportion the scan between the caches */
dentries = mult_frac(sc->nr_to_scan, dentries, total_objects);
inodes = mult_frac(sc->nr_to_scan, inodes, total_objects);
fs_objects = mult_frac(sc->nr_to_scan, fs_objects, total_objects);
/*
* prune the dcache first as the icache is pinned by it, then
* prune the icache, followed by the filesystem specific caches
*
* Ensure that we always scan at least one object - memcg kmem
* accounting uses this to fully empty the caches.
*/
sc->nr_to_scan = dentries + 1;
freed = prune_dcache_sb(sb, sc);
sc->nr_to_scan = inodes + 1;
freed += prune_icache_sb(sb, sc);
if (fs_objects) {
sc->nr_to_scan = fs_objects + 1;
freed += sb->s_op->free_cached_objects(sb, sc);
}
up_read(&sb->s_umount);
return freed;
}
static unsigned long super_cache_count(struct shrinker *shrink,
struct shrink_control *sc)
{
struct super_block *sb;
long total_objects = 0;
sb = container_of(shrink, struct super_block, s_shrink);
/*
* Don't call trylock_super as it is a potential
* scalability bottleneck. The counts could get updated
* between super_cache_count and super_cache_scan anyway.
* Call to super_cache_count with shrinker_rwsem held
* ensures the safety of call to list_lru_shrink_count() and
* s_op->nr_cached_objects().
*/
if (sb->s_op && sb->s_op->nr_cached_objects)
total_objects = sb->s_op->nr_cached_objects(sb, sc);
total_objects += list_lru_shrink_count(&sb->s_dentry_lru, sc);
total_objects += list_lru_shrink_count(&sb->s_inode_lru, sc);
total_objects = vfs_pressure_ratio(total_objects);
return total_objects;
}
/**
* destroy_super - frees a superblock
* @s: superblock to free
*
* Frees a superblock.
*/
static void destroy_super(struct super_block *s)
{
int i;
list_lru_destroy(&s->s_dentry_lru);
list_lru_destroy(&s->s_inode_lru);
for (i = 0; i < SB_FREEZE_LEVELS; i++)
percpu_counter_destroy(&s->s_writers.counter[i]);
security_sb_free(s);
WARN_ON(!list_empty(&s->s_mounts));
kfree(s->s_subtype);
kfree(s->s_options);
kfree_rcu(s, rcu);
}
/**
* alloc_super - create new superblock
* @type: filesystem type superblock should belong to
* @flags: the mount flags
*
* Allocates and initializes a new &struct super_block. alloc_super()
* returns a pointer new superblock or %NULL if allocation had failed.
*/
static struct super_block *alloc_super(struct file_system_type *type, int flags)
{
struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER);
static const struct super_operations default_op;
int i;
if (!s)
return NULL;
INIT_LIST_HEAD(&s->s_mounts);
if (security_sb_alloc(s))
goto fail;
for (i = 0; i < SB_FREEZE_LEVELS; i++) {
if (percpu_counter_init(&s->s_writers.counter[i], 0,
GFP_KERNEL) < 0)
goto fail;
lockdep_init_map(&s->s_writers.lock_map[i], sb_writers_name[i],
&type->s_writers_key[i], 0);
}
init_waitqueue_head(&s->s_writers.wait);
init_waitqueue_head(&s->s_writers.wait_unfrozen);
s->s_bdi = &noop_backing_dev_info;
s->s_flags = flags;
INIT_HLIST_NODE(&s->s_instances);
INIT_HLIST_BL_HEAD(&s->s_anon);
INIT_LIST_HEAD(&s->s_inodes);
if (list_lru_init_memcg(&s->s_dentry_lru))
goto fail;
if (list_lru_init_memcg(&s->s_inode_lru))
goto fail;
init_rwsem(&s->s_umount);
lockdep_set_class(&s->s_umount, &type->s_umount_key);
/*
* sget() can have s_umount recursion.
*
* When it cannot find a suitable sb, it allocates a new
* one (this one), and tries again to find a suitable old
* one.
*
* In case that succeeds, it will acquire the s_umount
* lock of the old one. Since these are clearly distrinct
* locks, and this object isn't exposed yet, there's no
* risk of deadlocks.
*
* Annotate this by putting this lock in a different
* subclass.
*/
down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
s->s_count = 1;
atomic_set(&s->s_active, 1);
mutex_init(&s->s_vfs_rename_mutex);
lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
mutex_init(&s->s_dquot.dqio_mutex);
mutex_init(&s->s_dquot.dqonoff_mutex);
s->s_maxbytes = MAX_NON_LFS;
s->s_op = &default_op;
s->s_time_gran = 1000000000;
s->cleancache_poolid = CLEANCACHE_NO_POOL;
s->s_shrink.seeks = DEFAULT_SEEKS;
s->s_shrink.scan_objects = super_cache_scan;
s->s_shrink.count_objects = super_cache_count;
s->s_shrink.batch = 1024;
s->s_shrink.flags = SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE;
return s;
fail:
destroy_super(s);
return NULL;
}
/* Superblock refcounting */
/*
* Drop a superblock's refcount. The caller must hold sb_lock.
*/
static void __put_super(struct super_block *sb)
{
if (!--sb->s_count) {
list_del_init(&sb->s_list);
destroy_super(sb);
}
}
/**
* put_super - drop a temporary reference to superblock
* @sb: superblock in question
*
* Drops a temporary reference, frees superblock if there's no
* references left.
*/
static void put_super(struct super_block *sb)
{
spin_lock(&sb_lock);
__put_super(sb);
spin_unlock(&sb_lock);
}
/**
* deactivate_locked_super - drop an active reference to superblock
* @s: superblock to deactivate
*
* Drops an active reference to superblock, converting it into a temprory
* one if there is no other active references left. In that case we
* tell fs driver to shut it down and drop the temporary reference we
* had just acquired.
*
* Caller holds exclusive lock on superblock; that lock is released.
*/
void deactivate_locked_super(struct super_block *s)
{
struct file_system_type *fs = s->s_type;
if (atomic_dec_and_test(&s->s_active)) {
cleancache_invalidate_fs(s);
unregister_shrinker(&s->s_shrink);
fs->kill_sb(s);
/*
* Since list_lru_destroy() may sleep, we cannot call it from
* put_super(), where we hold the sb_lock. Therefore we destroy
* the lru lists right now.
*/
list_lru_destroy(&s->s_dentry_lru);
list_lru_destroy(&s->s_inode_lru);
put_filesystem(fs);
put_super(s);
} else {
up_write(&s->s_umount);
}
}
EXPORT_SYMBOL(deactivate_locked_super);
/**
* deactivate_super - drop an active reference to superblock
* @s: superblock to deactivate
*
* Variant of deactivate_locked_super(), except that superblock is *not*
* locked by caller. If we are going to drop the final active reference,
* lock will be acquired prior to that.
*/
void deactivate_super(struct super_block *s)
{
if (!atomic_add_unless(&s->s_active, -1, 1)) {
down_write(&s->s_umount);
deactivate_locked_super(s);
}
}
EXPORT_SYMBOL(deactivate_super);
/**
* grab_super - acquire an active reference
* @s: reference we are trying to make active
*
* Tries to acquire an active reference. grab_super() is used when we
* had just found a superblock in super_blocks or fs_type->fs_supers
* and want to turn it into a full-blown active reference. grab_super()
* is called with sb_lock held and drops it. Returns 1 in case of
* success, 0 if we had failed (superblock contents was already dead or
* dying when grab_super() had been called). Note that this is only
* called for superblocks not in rundown mode (== ones still on ->fs_supers
* of their type), so increment of ->s_count is OK here.
*/
static int grab_super(struct super_block *s) __releases(sb_lock)
{
s->s_count++;
spin_unlock(&sb_lock);
down_write(&s->s_umount);
if ((s->s_flags & MS_BORN) && atomic_inc_not_zero(&s->s_active)) {
put_super(s);
return 1;
}
up_write(&s->s_umount);
put_super(s);
return 0;
}
/*
* trylock_super - try to grab ->s_umount shared
* @sb: reference we are trying to grab
*
* Try to prevent fs shutdown. This is used in places where we
* cannot take an active reference but we need to ensure that the
* filesystem is not shut down while we are working on it. It returns
* false if we cannot acquire s_umount or if we lose the race and
* filesystem already got into shutdown, and returns true with the s_umount
* lock held in read mode in case of success. On successful return,
* the caller must drop the s_umount lock when done.
*
* Note that unlike get_super() et.al. this one does *not* bump ->s_count.
* The reason why it's safe is that we are OK with doing trylock instead
* of down_read(). There's a couple of places that are OK with that, but
* it's very much not a general-purpose interface.
*/
bool trylock_super(struct super_block *sb)
{
if (down_read_trylock(&sb->s_umount)) {
if (!hlist_unhashed(&sb->s_instances) &&
sb->s_root && (sb->s_flags & MS_BORN))
return true;
up_read(&sb->s_umount);
}
return false;
}
/**
* generic_shutdown_super - common helper for ->kill_sb()
* @sb: superblock to kill
*
* generic_shutdown_super() does all fs-independent work on superblock
* shutdown. Typical ->kill_sb() should pick all fs-specific objects
* that need destruction out of superblock, call generic_shutdown_super()
* and release aforementioned objects. Note: dentries and inodes _are_
* taken care of and do not need specific handling.
*
* Upon calling this function, the filesystem may no longer alter or
* rearrange the set of dentries belonging to this super_block, nor may it
* change the attachments of dentries to inodes.
*/
void generic_shutdown_super(struct super_block *sb)
{
const struct super_operations *sop = sb->s_op;
if (sb->s_root) {
shrink_dcache_for_umount(sb);
sync_filesystem(sb);
sb->s_flags &= ~MS_ACTIVE;
fsnotify_unmount_inodes(&sb->s_inodes);
evict_inodes(sb);
if (sb->s_dio_done_wq) {
destroy_workqueue(sb->s_dio_done_wq);
sb->s_dio_done_wq = NULL;
}
if (sop->put_super)
sop->put_super(sb);
if (!list_empty(&sb->s_inodes)) {
printk("VFS: Busy inodes after unmount of %s. "
"Self-destruct in 5 seconds. Have a nice day...\n",
sb->s_id);
}
}
spin_lock(&sb_lock);
/* should be initialized for __put_super_and_need_restart() */
hlist_del_init(&sb->s_instances);
spin_unlock(&sb_lock);
up_write(&sb->s_umount);
}
EXPORT_SYMBOL(generic_shutdown_super);
/**
* sget - find or create a superblock
* @type: filesystem type superblock should belong to
* @test: comparison callback
* @set: setup callback
* @flags: mount flags
* @data: argument to each of them
*/
struct super_block *sget(struct file_system_type *type,
int (*test)(struct super_block *,void *),
int (*set)(struct super_block *,void *),
int flags,
void *data)
{
struct super_block *s = NULL;
struct super_block *old;
int err;
retry:
spin_lock(&sb_lock);
if (test) {
hlist_for_each_entry(old, &type->fs_supers, s_instances) {
if (!test(old, data))
continue;
if (!grab_super(old))
goto retry;
if (s) {
up_write(&s->s_umount);
destroy_super(s);
s = NULL;
}
return old;
}
}
if (!s) {
spin_unlock(&sb_lock);
s = alloc_super(type, flags);
if (!s)
return ERR_PTR(-ENOMEM);
goto retry;
}
err = set(s, data);
if (err) {
spin_unlock(&sb_lock);
up_write(&s->s_umount);
destroy_super(s);
return ERR_PTR(err);
}
s->s_type = type;
strlcpy(s->s_id, type->name, sizeof(s->s_id));
list_add_tail(&s->s_list, &super_blocks);
hlist_add_head(&s->s_instances, &type->fs_supers);
spin_unlock(&sb_lock);
get_filesystem(type);
register_shrinker(&s->s_shrink);
return s;
}
EXPORT_SYMBOL(sget);
void drop_super(struct super_block *sb)
{
up_read(&sb->s_umount);
put_super(sb);
}
EXPORT_SYMBOL(drop_super);
/**
* iterate_supers - call function for all active superblocks
* @f: function to call
* @arg: argument to pass to it
*
* Scans the superblock list and calls given function, passing it
* locked superblock and given argument.
*/
void iterate_supers(void (*f)(struct super_block *, void *), void *arg)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (hlist_unhashed(&sb->s_instances))
continue;
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
if (sb->s_root && (sb->s_flags & MS_BORN))
f(sb, arg);
up_read(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
}
/**
* iterate_supers_type - call function for superblocks of given type
* @type: fs type
* @f: function to call
* @arg: argument to pass to it
*
* Scans the superblock list and calls given function, passing it
* locked superblock and given argument.
*/
void iterate_supers_type(struct file_system_type *type,
void (*f)(struct super_block *, void *), void *arg)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
hlist_for_each_entry(sb, &type->fs_supers, s_instances) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
if (sb->s_root && (sb->s_flags & MS_BORN))
f(sb, arg);
up_read(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
}
EXPORT_SYMBOL(iterate_supers_type);
/**
* get_super - get the superblock of a device
* @bdev: device to get the superblock for
*
* Scans the superblock list and finds the superblock of the file system
* mounted on the device given. %NULL is returned if no match is found.
*/
struct super_block *get_super(struct block_device *bdev)
{
struct super_block *sb;
if (!bdev)
return NULL;
spin_lock(&sb_lock);
rescan:
list_for_each_entry(sb, &super_blocks, s_list) {
if (hlist_unhashed(&sb->s_instances))
continue;
if (sb->s_bdev == bdev) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
/* still alive? */
if (sb->s_root && (sb->s_flags & MS_BORN))
return sb;
up_read(&sb->s_umount);
/* nope, got unmounted */
spin_lock(&sb_lock);
__put_super(sb);
goto rescan;
}
}
spin_unlock(&sb_lock);
return NULL;
}
EXPORT_SYMBOL(get_super);
/**
* get_super_thawed - get thawed superblock of a device
* @bdev: device to get the superblock for
*
* Scans the superblock list and finds the superblock of the file system
* mounted on the device. The superblock is returned once it is thawed
* (or immediately if it was not frozen). %NULL is returned if no match
* is found.
*/
struct super_block *get_super_thawed(struct block_device *bdev)
{
while (1) {
struct super_block *s = get_super(bdev);
if (!s || s->s_writers.frozen == SB_UNFROZEN)
return s;
up_read(&s->s_umount);
wait_event(s->s_writers.wait_unfrozen,
s->s_writers.frozen == SB_UNFROZEN);
put_super(s);
}
}
EXPORT_SYMBOL(get_super_thawed);
/**
* get_active_super - get an active reference to the superblock of a device
* @bdev: device to get the superblock for
*
* Scans the superblock list and finds the superblock of the file system
* mounted on the device given. Returns the superblock with an active
* reference or %NULL if none was found.
*/
struct super_block *get_active_super(struct block_device *bdev)
{
struct super_block *sb;
if (!bdev)
return NULL;
restart:
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (hlist_unhashed(&sb->s_instances))
continue;
if (sb->s_bdev == bdev) {
if (!grab_super(sb))
goto restart;
up_write(&sb->s_umount);
return sb;
}
}
spin_unlock(&sb_lock);
return NULL;
}
struct super_block *user_get_super(dev_t dev)
{
struct super_block *sb;
spin_lock(&sb_lock);
rescan:
list_for_each_entry(sb, &super_blocks, s_list) {
if (hlist_unhashed(&sb->s_instances))
continue;
if (sb->s_dev == dev) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
/* still alive? */
if (sb->s_root && (sb->s_flags & MS_BORN))
return sb;
up_read(&sb->s_umount);
/* nope, got unmounted */
spin_lock(&sb_lock);
__put_super(sb);
goto rescan;
}
}
spin_unlock(&sb_lock);
return NULL;
}
/**
* do_remount_sb - asks filesystem to change mount options.
* @sb: superblock in question
* @flags: numeric part of options
* @data: the rest of options
* @force: whether or not to force the change
*
* Alters the mount options of a mounted file system.
*/
int do_remount_sb(struct super_block *sb, int flags, void *data, int force)
{
int retval;
int remount_ro;
if (sb->s_writers.frozen != SB_UNFROZEN)
return -EBUSY;
#ifdef CONFIG_BLOCK
if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev))
return -EACCES;
#endif
remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY);
if (remount_ro) {
if (!hlist_empty(&sb->s_pins)) {
up_write(&sb->s_umount);
group_pin_kill(&sb->s_pins);
down_write(&sb->s_umount);
if (!sb->s_root)
return 0;
if (sb->s_writers.frozen != SB_UNFROZEN)
return -EBUSY;
remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY);
}
}
shrink_dcache_sb(sb);
/* If we are remounting RDONLY and current sb is read/write,
make sure there are no rw files opened */
if (remount_ro) {
if (force) {
sb->s_readonly_remount = 1;
smp_wmb();
} else {
retval = sb_prepare_remount_readonly(sb);
if (retval)
return retval;
}
}
if (sb->s_op->remount_fs) {
retval = sb->s_op->remount_fs(sb, &flags, data);
if (retval) {
if (!force)
goto cancel_readonly;
/* If forced remount, go ahead despite any errors */
WARN(1, "forced remount of a %s fs returned %i\n",
sb->s_type->name, retval);
}
}
sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK);
/* Needs to be ordered wrt mnt_is_readonly() */
smp_wmb();
sb->s_readonly_remount = 0;
/*
* Some filesystems modify their metadata via some other path than the
* bdev buffer cache (eg. use a private mapping, or directories in
* pagecache, etc). Also file data modifications go via their own
* mappings. So If we try to mount readonly then copy the filesystem
* from bdev, we could get stale data, so invalidate it to give a best
* effort at coherency.
*/
if (remount_ro && sb->s_bdev)
invalidate_bdev(sb->s_bdev);
return 0;
cancel_readonly:
sb->s_readonly_remount = 0;
return retval;
}
static void do_emergency_remount(struct work_struct *work)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (hlist_unhashed(&sb->s_instances))
continue;
sb->s_count++;
spin_unlock(&sb_lock);
down_write(&sb->s_umount);
if (sb->s_root && sb->s_bdev && (sb->s_flags & MS_BORN) &&
!(sb->s_flags & MS_RDONLY)) {
/*
* What lock protects sb->s_flags??
*/
do_remount_sb(sb, MS_RDONLY, NULL, 1);
}
up_write(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
kfree(work);
printk("Emergency Remount complete\n");
}
void emergency_remount(void)
{
struct work_struct *work;
work = kmalloc(sizeof(*work), GFP_ATOMIC);
if (work) {
INIT_WORK(work, do_emergency_remount);
schedule_work(work);
}
}
/*
* Unnamed block devices are dummy devices used by virtual
* filesystems which don't use real block-devices. -- jrs
*/
static DEFINE_IDA(unnamed_dev_ida);
static DEFINE_SPINLOCK(unnamed_dev_lock);/* protects the above */
/* Many userspace utilities consider an FSID of 0 invalid.
* Always return at least 1 from get_anon_bdev.
*/
static int unnamed_dev_start = 1;
int get_anon_bdev(dev_t *p)
{
int dev;
int error;
retry:
if (ida_pre_get(&unnamed_dev_ida, GFP_ATOMIC) == 0)
return -ENOMEM;
spin_lock(&unnamed_dev_lock);
error = ida_get_new_above(&unnamed_dev_ida, unnamed_dev_start, &dev);
if (!error)
unnamed_dev_start = dev + 1;
spin_unlock(&unnamed_dev_lock);
if (error == -EAGAIN)
/* We raced and lost with another CPU. */
goto retry;
else if (error)
return -EAGAIN;
if (dev == (1 << MINORBITS)) {
spin_lock(&unnamed_dev_lock);
ida_remove(&unnamed_dev_ida, dev);
if (unnamed_dev_start > dev)
unnamed_dev_start = dev;
spin_unlock(&unnamed_dev_lock);
return -EMFILE;
}
*p = MKDEV(0, dev & MINORMASK);
return 0;
}
EXPORT_SYMBOL(get_anon_bdev);
void free_anon_bdev(dev_t dev)
{
int slot = MINOR(dev);
spin_lock(&unnamed_dev_lock);
ida_remove(&unnamed_dev_ida, slot);
if (slot < unnamed_dev_start)
unnamed_dev_start = slot;
spin_unlock(&unnamed_dev_lock);
}
EXPORT_SYMBOL(free_anon_bdev);
int set_anon_super(struct super_block *s, void *data)
{
return get_anon_bdev(&s->s_dev);
}
EXPORT_SYMBOL(set_anon_super);
void kill_anon_super(struct super_block *sb)
{
dev_t dev = sb->s_dev;
generic_shutdown_super(sb);
free_anon_bdev(dev);
}
EXPORT_SYMBOL(kill_anon_super);
void kill_litter_super(struct super_block *sb)
{
if (sb->s_root)
d_genocide(sb->s_root);
kill_anon_super(sb);
}
EXPORT_SYMBOL(kill_litter_super);
static int ns_test_super(struct super_block *sb, void *data)
{
return sb->s_fs_info == data;
}
static int ns_set_super(struct super_block *sb, void *data)
{
sb->s_fs_info = data;
return set_anon_super(sb, NULL);
}
struct dentry *mount_ns(struct file_system_type *fs_type, int flags,
void *data, int (*fill_super)(struct super_block *, void *, int))
{
struct super_block *sb;
sb = sget(fs_type, ns_test_super, ns_set_super, flags, data);
if (IS_ERR(sb))
return ERR_CAST(sb);
if (!sb->s_root) {
int err;
err = fill_super(sb, data, flags & MS_SILENT ? 1 : 0);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
}
return dget(sb->s_root);
}
EXPORT_SYMBOL(mount_ns);
#ifdef CONFIG_BLOCK
static int set_bdev_super(struct super_block *s, void *data)
{
s->s_bdev = data;
s->s_dev = s->s_bdev->bd_dev;
/*
* We set the bdi here to the queue backing, file systems can
* overwrite this in ->fill_super()
*/
s->s_bdi = &bdev_get_queue(s->s_bdev)->backing_dev_info;
return 0;
}
static int test_bdev_super(struct super_block *s, void *data)
{
return (void *)s->s_bdev == data;
}
struct dentry *mount_bdev(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
struct block_device *bdev;
struct super_block *s;
fmode_t mode = FMODE_READ | FMODE_EXCL;
int error = 0;
if (!(flags & MS_RDONLY))
mode |= FMODE_WRITE;
bdev = blkdev_get_by_path(dev_name, mode, fs_type);
if (IS_ERR(bdev))
return ERR_CAST(bdev);
/*
* once the super is inserted into the list by sget, s_umount
* will protect the lockfs code from trying to start a snapshot
* while we are mounting
*/
mutex_lock(&bdev->bd_fsfreeze_mutex);
if (bdev->bd_fsfreeze_count > 0) {
mutex_unlock(&bdev->bd_fsfreeze_mutex);
error = -EBUSY;
goto error_bdev;
}
s = sget(fs_type, test_bdev_super, set_bdev_super, flags | MS_NOSEC,
bdev);
mutex_unlock(&bdev->bd_fsfreeze_mutex);
if (IS_ERR(s))
goto error_s;
if (s->s_root) {
if ((flags ^ s->s_flags) & MS_RDONLY) {
deactivate_locked_super(s);
error = -EBUSY;
goto error_bdev;
}
/*
* s_umount nests inside bd_mutex during
* __invalidate_device(). blkdev_put() acquires
* bd_mutex and can't be called under s_umount. Drop
* s_umount temporarily. This is safe as we're
* holding an active reference.
*/
up_write(&s->s_umount);
blkdev_put(bdev, mode);
down_write(&s->s_umount);
} else {
char b[BDEVNAME_SIZE];
s->s_mode = mode;
strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id));
sb_set_blocksize(s, block_size(bdev));
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
goto error;
}
s->s_flags |= MS_ACTIVE;
bdev->bd_super = s;
}
return dget(s->s_root);
error_s:
error = PTR_ERR(s);
error_bdev:
blkdev_put(bdev, mode);
error:
return ERR_PTR(error);
}
EXPORT_SYMBOL(mount_bdev);
void kill_block_super(struct super_block *sb)
{
struct block_device *bdev = sb->s_bdev;
fmode_t mode = sb->s_mode;
bdev->bd_super = NULL;
generic_shutdown_super(sb);
sync_blockdev(bdev);
WARN_ON_ONCE(!(mode & FMODE_EXCL));
blkdev_put(bdev, mode | FMODE_EXCL);
}
EXPORT_SYMBOL(kill_block_super);
#endif
struct dentry *mount_nodev(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
int error;
struct super_block *s = sget(fs_type, NULL, set_anon_super, flags, NULL);
if (IS_ERR(s))
return ERR_CAST(s);
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
return ERR_PTR(error);
}
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
}
EXPORT_SYMBOL(mount_nodev);
static int compare_single(struct super_block *s, void *p)
{
return 1;
}
struct dentry *mount_single(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
struct super_block *s;
int error;
s = sget(fs_type, compare_single, set_anon_super, flags, NULL);
if (IS_ERR(s))
return ERR_CAST(s);
if (!s->s_root) {
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
return ERR_PTR(error);
}
s->s_flags |= MS_ACTIVE;
} else {
do_remount_sb(s, flags, data, 0);
}
return dget(s->s_root);
}
EXPORT_SYMBOL(mount_single);
struct dentry *
mount_fs(struct file_system_type *type, int flags, const char *name, void *data)
{
struct dentry *root;
struct super_block *sb;
char *secdata = NULL;
int error = -ENOMEM;
if (data && !(type->fs_flags & FS_BINARY_MOUNTDATA)) {
secdata = alloc_secdata();
if (!secdata)
goto out;
error = security_sb_copy_data(data, secdata);
if (error)
goto out_free_secdata;
}
root = type->mount(type, flags, name, data);
if (IS_ERR(root)) {
error = PTR_ERR(root);
goto out_free_secdata;
}
sb = root->d_sb;
BUG_ON(!sb);
WARN_ON(!sb->s_bdi);
sb->s_flags |= MS_BORN;
error = security_sb_kern_mount(sb, flags, secdata);
if (error)
goto out_sb;
/*
* filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE
* but s_maxbytes was an unsigned long long for many releases. Throw
* this warning for a little while to try and catch filesystems that
* violate this rule.
*/
WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to "
"negative value (%lld)\n", type->name, sb->s_maxbytes);
up_write(&sb->s_umount);
free_secdata(secdata);
return root;
out_sb:
dput(root);
deactivate_locked_super(sb);
out_free_secdata:
free_secdata(secdata);
out:
return ERR_PTR(error);
}
/*
* This is an internal function, please use sb_end_{write,pagefault,intwrite}
* instead.
*/
void __sb_end_write(struct super_block *sb, int level)
{
percpu_counter_dec(&sb->s_writers.counter[level-1]);
/*
* Make sure s_writers are updated before we wake up waiters in
* freeze_super().
*/
smp_mb();
if (waitqueue_active(&sb->s_writers.wait))
wake_up(&sb->s_writers.wait);
rwsem_release(&sb->s_writers.lock_map[level-1], 1, _RET_IP_);
}
EXPORT_SYMBOL(__sb_end_write);
#ifdef CONFIG_LOCKDEP
/*
* We want lockdep to tell us about possible deadlocks with freezing but
* it's it bit tricky to properly instrument it. Getting a freeze protection
* works as getting a read lock but there are subtle problems. XFS for example
* gets freeze protection on internal level twice in some cases, which is OK
* only because we already hold a freeze protection also on higher level. Due
* to these cases we have to tell lockdep we are doing trylock when we
* already hold a freeze protection for a higher freeze level.
*/
static void acquire_freeze_lock(struct super_block *sb, int level, bool trylock,
unsigned long ip)
{
int i;
if (!trylock) {
for (i = 0; i < level - 1; i++)
if (lock_is_held(&sb->s_writers.lock_map[i])) {
trylock = true;
break;
}
}
rwsem_acquire_read(&sb->s_writers.lock_map[level-1], 0, trylock, ip);
}
#endif
/*
* This is an internal function, please use sb_start_{write,pagefault,intwrite}
* instead.
*/
int __sb_start_write(struct super_block *sb, int level, bool wait)
{
retry:
if (unlikely(sb->s_writers.frozen >= level)) {
if (!wait)
return 0;
wait_event(sb->s_writers.wait_unfrozen,
sb->s_writers.frozen < level);
}
#ifdef CONFIG_LOCKDEP
acquire_freeze_lock(sb, level, !wait, _RET_IP_);
#endif
percpu_counter_inc(&sb->s_writers.counter[level-1]);
/*
* Make sure counter is updated before we check for frozen.
* freeze_super() first sets frozen and then checks the counter.
*/
smp_mb();
if (unlikely(sb->s_writers.frozen >= level)) {
__sb_end_write(sb, level);
goto retry;
}
return 1;
}
EXPORT_SYMBOL(__sb_start_write);
/**
* sb_wait_write - wait until all writers to given file system finish
* @sb: the super for which we wait
* @level: type of writers we wait for (normal vs page fault)
*
* This function waits until there are no writers of given type to given file
* system. Caller of this function should make sure there can be no new writers
* of type @level before calling this function. Otherwise this function can
* livelock.
*/
static void sb_wait_write(struct super_block *sb, int level)
{
s64 writers;
/*
* We just cycle-through lockdep here so that it does not complain
* about returning with lock to userspace
*/
rwsem_acquire(&sb->s_writers.lock_map[level-1], 0, 0, _THIS_IP_);
rwsem_release(&sb->s_writers.lock_map[level-1], 1, _THIS_IP_);
do {
DEFINE_WAIT(wait);
/*
* We use a barrier in prepare_to_wait() to separate setting
* of frozen and checking of the counter
*/
prepare_to_wait(&sb->s_writers.wait, &wait,
TASK_UNINTERRUPTIBLE);
writers = percpu_counter_sum(&sb->s_writers.counter[level-1]);
if (writers)
schedule();
finish_wait(&sb->s_writers.wait, &wait);
} while (writers);
}
/**
* freeze_super - lock the filesystem and force it into a consistent state
* @sb: the super to lock
*
* Syncs the super to make sure the filesystem is consistent and calls the fs's
* freeze_fs. Subsequent calls to this without first thawing the fs will return
* -EBUSY.
*
* During this function, sb->s_writers.frozen goes through these values:
*
* SB_UNFROZEN: File system is normal, all writes progress as usual.
*
* SB_FREEZE_WRITE: The file system is in the process of being frozen. New
* writes should be blocked, though page faults are still allowed. We wait for
* all writes to complete and then proceed to the next stage.
*
* SB_FREEZE_PAGEFAULT: Freezing continues. Now also page faults are blocked
* but internal fs threads can still modify the filesystem (although they
* should not dirty new pages or inodes), writeback can run etc. After waiting
* for all running page faults we sync the filesystem which will clean all
* dirty pages and inodes (no new dirty pages or inodes can be created when
* sync is running).
*
* SB_FREEZE_FS: The file system is frozen. Now all internal sources of fs
* modification are blocked (e.g. XFS preallocation truncation on inode
* reclaim). This is usually implemented by blocking new transactions for
* filesystems that have them and need this additional guard. After all
* internal writers are finished we call ->freeze_fs() to finish filesystem
* freezing. Then we transition to SB_FREEZE_COMPLETE state. This state is
* mostly auxiliary for filesystems to verify they do not modify frozen fs.
*
* sb->s_writers.frozen is protected by sb->s_umount.
*/
int freeze_super(struct super_block *sb)
{
int ret;
atomic_inc(&sb->s_active);
down_write(&sb->s_umount);
if (sb->s_writers.frozen != SB_UNFROZEN) {
deactivate_locked_super(sb);
return -EBUSY;
}
if (!(sb->s_flags & MS_BORN)) {
up_write(&sb->s_umount);
return 0; /* sic - it's "nothing to do" */
}
if (sb->s_flags & MS_RDONLY) {
/* Nothing to do really... */
sb->s_writers.frozen = SB_FREEZE_COMPLETE;
up_write(&sb->s_umount);
return 0;
}
/* From now on, no new normal writers can start */
sb->s_writers.frozen = SB_FREEZE_WRITE;
smp_wmb();
/* Release s_umount to preserve sb_start_write -> s_umount ordering */
up_write(&sb->s_umount);
sb_wait_write(sb, SB_FREEZE_WRITE);
/* Now we go and block page faults... */
down_write(&sb->s_umount);
sb->s_writers.frozen = SB_FREEZE_PAGEFAULT;
smp_wmb();
sb_wait_write(sb, SB_FREEZE_PAGEFAULT);
/* All writers are done so after syncing there won't be dirty data */
sync_filesystem(sb);
/* Now wait for internal filesystem counter */
sb->s_writers.frozen = SB_FREEZE_FS;
smp_wmb();
sb_wait_write(sb, SB_FREEZE_FS);
if (sb->s_op->freeze_fs) {
ret = sb->s_op->freeze_fs(sb);
if (ret) {
printk(KERN_ERR
"VFS:Filesystem freeze failed\n");
sb->s_writers.frozen = SB_UNFROZEN;
smp_wmb();
wake_up(&sb->s_writers.wait_unfrozen);
deactivate_locked_super(sb);
return ret;
}
}
/*
* This is just for debugging purposes so that fs can warn if it
* sees write activity when frozen is set to SB_FREEZE_COMPLETE.
*/
sb->s_writers.frozen = SB_FREEZE_COMPLETE;
up_write(&sb->s_umount);
return 0;
}
EXPORT_SYMBOL(freeze_super);
/**
* thaw_super -- unlock filesystem
* @sb: the super to thaw
*
* Unlocks the filesystem and marks it writeable again after freeze_super().
*/
int thaw_super(struct super_block *sb)
{
int error;
down_write(&sb->s_umount);
if (sb->s_writers.frozen == SB_UNFROZEN) {
up_write(&sb->s_umount);
return -EINVAL;
}
if (sb->s_flags & MS_RDONLY)
goto out;
if (sb->s_op->unfreeze_fs) {
error = sb->s_op->unfreeze_fs(sb);
if (error) {
printk(KERN_ERR
"VFS:Filesystem thaw failed\n");
up_write(&sb->s_umount);
return error;
}
}
out:
sb->s_writers.frozen = SB_UNFROZEN;
smp_wmb();
wake_up(&sb->s_writers.wait_unfrozen);
deactivate_locked_super(sb);
return 0;
}
EXPORT_SYMBOL(thaw_super);
|
RomanHargrave/pf-kernel
|
fs/super.c
|
C
|
gpl-2.0
| 36,201
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'c:/steganography/main.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(1024, 576)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.group_image = QtGui.QGroupBox(self.centralwidget)
self.group_image.setGeometry(QtCore.QRect(10, 10, 1001, 291))
self.group_image.setObjectName(_fromUtf8("group_image"))
self.lbl_image = QtGui.QLabel(self.group_image)
self.lbl_image.setGeometry(QtCore.QRect(180, 20, 451, 261))
self.lbl_image.setAutoFillBackground(False)
self.lbl_image.setFrameShape(QtGui.QFrame.Panel)
self.lbl_image.setFrameShadow(QtGui.QFrame.Raised)
self.lbl_image.setText(_fromUtf8(""))
self.lbl_image.setScaledContents(True)
self.lbl_image.setObjectName(_fromUtf8("lbl_image"))
self.lbl_filename = QtGui.QLabel(self.group_image)
self.lbl_filename.setGeometry(QtCore.QRect(10, 20, 161, 21))
self.lbl_filename.setAlignment(QtCore.Qt.AlignCenter)
self.lbl_filename.setObjectName(_fromUtf8("lbl_filename"))
self.btn_load = QtGui.QPushButton(self.group_image)
self.btn_load.setGeometry(QtCore.QRect(10, 50, 161, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.btn_load.setFont(font)
self.btn_load.setObjectName(_fromUtf8("btn_load"))
self.lbl_spacing = QtGui.QLabel(self.group_image)
self.lbl_spacing.setGeometry(QtCore.QRect(20, 150, 71, 21))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.lbl_spacing.setFont(font)
self.lbl_spacing.setObjectName(_fromUtf8("lbl_spacing"))
self.box_spacing = QtGui.QSpinBox(self.group_image)
self.box_spacing.setGeometry(QtCore.QRect(90, 150, 71, 22))
self.box_spacing.setMinimum(1)
self.box_spacing.setMaximum(100)
self.box_spacing.setProperty("value", 32)
self.box_spacing.setObjectName(_fromUtf8("box_spacing"))
self.radio_decode = QtGui.QRadioButton(self.group_image)
self.radio_decode.setGeometry(QtCore.QRect(20, 120, 151, 17))
self.radio_decode.setChecked(False)
self.radio_decode.setObjectName(_fromUtf8("radio_decode"))
self.radio_encode = QtGui.QRadioButton(self.group_image)
self.radio_encode.setGeometry(QtCore.QRect(20, 90, 141, 17))
self.radio_encode.setChecked(True)
self.radio_encode.setObjectName(_fromUtf8("radio_encode"))
self.verticalLayoutWidget = QtGui.QWidget(self.group_image)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(640, 20, 160, 131))
self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
self.layout_labels = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.layout_labels.setSpacing(12)
self.layout_labels.setObjectName(_fromUtf8("layout_labels"))
self.lbl_height = QtGui.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.lbl_height.setFont(font)
self.lbl_height.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.lbl_height.setObjectName(_fromUtf8("lbl_height"))
self.layout_labels.addWidget(self.lbl_height)
self.lbl_width = QtGui.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.lbl_width.setFont(font)
self.lbl_width.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.lbl_width.setObjectName(_fromUtf8("lbl_width"))
self.layout_labels.addWidget(self.lbl_width)
self.lbl_format = QtGui.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.lbl_format.setFont(font)
self.lbl_format.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.lbl_format.setObjectName(_fromUtf8("lbl_format"))
self.layout_labels.addWidget(self.lbl_format)
self.lbl_size = QtGui.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.lbl_size.setFont(font)
self.lbl_size.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.lbl_size.setObjectName(_fromUtf8("lbl_size"))
self.layout_labels.addWidget(self.lbl_size)
self.lbl_max_length = QtGui.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.lbl_max_length.setFont(font)
self.lbl_max_length.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.lbl_max_length.setObjectName(_fromUtf8("lbl_max_length"))
self.layout_labels.addWidget(self.lbl_max_length)
self.verticalLayoutWidget_2 = QtGui.QWidget(self.group_image)
self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(810, 20, 181, 130))
self.verticalLayoutWidget_2.setObjectName(_fromUtf8("verticalLayoutWidget_2"))
self.layout_values = QtGui.QVBoxLayout(self.verticalLayoutWidget_2)
self.layout_values.setSpacing(12)
self.layout_values.setObjectName(_fromUtf8("layout_values"))
self.lbl_height_value = QtGui.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(9)
self.lbl_height_value.setFont(font)
self.lbl_height_value.setObjectName(_fromUtf8("lbl_height_value"))
self.layout_values.addWidget(self.lbl_height_value)
self.lbl_width_value = QtGui.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(9)
self.lbl_width_value.setFont(font)
self.lbl_width_value.setObjectName(_fromUtf8("lbl_width_value"))
self.layout_values.addWidget(self.lbl_width_value)
self.lbl_format_value = QtGui.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(9)
self.lbl_format_value.setFont(font)
self.lbl_format_value.setObjectName(_fromUtf8("lbl_format_value"))
self.layout_values.addWidget(self.lbl_format_value)
self.lbl_size_value = QtGui.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(9)
self.lbl_size_value.setFont(font)
self.lbl_size_value.setObjectName(_fromUtf8("lbl_size_value"))
self.layout_values.addWidget(self.lbl_size_value)
self.lbl_max_length_value = QtGui.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(9)
self.lbl_max_length_value.setFont(font)
self.lbl_max_length_value.setObjectName(_fromUtf8("lbl_max_length_value"))
self.layout_values.addWidget(self.lbl_max_length_value)
self.lbl_spacing_info = QtGui.QLabel(self.group_image)
self.lbl_spacing_info.setGeometry(QtCore.QRect(20, 180, 141, 71))
self.lbl_spacing_info.setWordWrap(True)
self.lbl_spacing_info.setObjectName(_fromUtf8("lbl_spacing_info"))
self.lbl_status = QtGui.QLabel(self.group_image)
self.lbl_status.setGeometry(QtCore.QRect(640, 160, 351, 121))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Consolas"))
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.lbl_status.setFont(font)
self.lbl_status.setFrameShape(QtGui.QFrame.Panel)
self.lbl_status.setFrameShadow(QtGui.QFrame.Sunken)
self.lbl_status.setLineWidth(2)
self.lbl_status.setScaledContents(False)
self.lbl_status.setAlignment(QtCore.Qt.AlignCenter)
self.lbl_status.setWordWrap(True)
self.lbl_status.setIndent(-1)
self.lbl_status.setObjectName(_fromUtf8("lbl_status"))
self.group_message = QtGui.QGroupBox(self.centralwidget)
self.group_message.setGeometry(QtCore.QRect(10, 310, 1001, 261))
self.group_message.setObjectName(_fromUtf8("group_message"))
self.text_message = QtGui.QTextEdit(self.group_message)
self.text_message.setGeometry(QtCore.QRect(180, 20, 811, 191))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Consolas"))
font.setPointSize(9)
self.text_message.setFont(font)
self.text_message.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.text_message.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.text_message.setObjectName(_fromUtf8("text_message"))
self.btn_load_text_file = QtGui.QPushButton(self.group_message)
self.btn_load_text_file.setGeometry(QtCore.QRect(10, 22, 161, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.btn_load_text_file.setFont(font)
self.btn_load_text_file.setObjectName(_fromUtf8("btn_load_text_file"))
self.lbl_num_characters = QtGui.QLabel(self.group_message)
self.lbl_num_characters.setGeometry(QtCore.QRect(180, 220, 811, 20))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Consolas"))
font.setPointSize(10)
self.lbl_num_characters.setFont(font)
self.lbl_num_characters.setAlignment(QtCore.Qt.AlignCenter)
self.lbl_num_characters.setObjectName(_fromUtf8("lbl_num_characters"))
self.lbl_message_info = QtGui.QLabel(self.group_message)
self.lbl_message_info.setGeometry(QtCore.QRect(10, 60, 151, 91))
self.lbl_message_info.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.lbl_message_info.setWordWrap(True)
self.lbl_message_info.setObjectName(_fromUtf8("lbl_message_info"))
self.lbl_allowed_symbols = QtGui.QLabel(self.group_message)
self.lbl_allowed_symbols.setGeometry(QtCore.QRect(20, 140, 151, 101))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Consolas"))
font.setPointSize(12)
self.lbl_allowed_symbols.setFont(font)
self.lbl_allowed_symbols.setAlignment(QtCore.Qt.AlignCenter)
self.lbl_allowed_symbols.setWordWrap(True)
self.lbl_allowed_symbols.setObjectName(_fromUtf8("lbl_allowed_symbols"))
self.btn_process = QtGui.QPushButton(self.group_message)
self.btn_process.setGeometry(QtCore.QRect(830, 220, 161, 31))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.btn_process.setFont(font)
self.btn_process.setAcceptDrops(False)
self.btn_process.setAutoFillBackground(False)
self.btn_process.setAutoDefault(True)
self.btn_process.setDefault(True)
self.btn_process.setObjectName(_fromUtf8("btn_process"))
self.lbl_spacing_info_2 = QtGui.QLabel(self.centralwidget)
self.lbl_spacing_info_2.setGeometry(QtCore.QRect(890, 0, 131, 20))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(109, 109, 109))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(109, 109, 109))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
self.lbl_spacing_info_2.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(7)
self.lbl_spacing_info_2.setFont(font)
self.lbl_spacing_info_2.setWordWrap(True)
self.lbl_spacing_info_2.setObjectName(_fromUtf8("lbl_spacing_info_2"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "Nick\'s Image Steganography", None))
self.group_image.setTitle(_translate("MainWindow", "Image Settings", None))
self.lbl_filename.setText(_translate("MainWindow", "<no image selected>", None))
self.btn_load.setText(_translate("MainWindow", "Load Image", None))
self.lbl_spacing.setText(_translate("MainWindow", "Spacing:", None))
self.box_spacing.setToolTip(_translate("MainWindow", "Default: 32", None))
self.radio_decode.setText(_translate("MainWindow", "Decode Image", None))
self.radio_encode.setText(_translate("MainWindow", "Encode Message", None))
self.lbl_height.setText(_translate("MainWindow", "Height:", None))
self.lbl_width.setText(_translate("MainWindow", "Width:", None))
self.lbl_format.setText(_translate("MainWindow", "Format:", None))
self.lbl_size.setText(_translate("MainWindow", "Size:", None))
self.lbl_max_length.setText(_translate("MainWindow", "Max Message Length:", None))
self.lbl_height_value.setText(_translate("MainWindow", "0 px", None))
self.lbl_width_value.setText(_translate("MainWindow", "0 px", None))
self.lbl_format_value.setText(_translate("MainWindow", "NONE", None))
self.lbl_size_value.setText(_translate("MainWindow", "0 bytes", None))
self.lbl_max_length_value.setText(_translate("MainWindow", "0 characters", None))
self.lbl_spacing_info.setText(_translate("MainWindow", "This value selects how many pixels are skipped for every encoded pixel. Lower values will affect the image more.", None))
self.lbl_status.setText(_translate("MainWindow", "This mode allows you to select an image file and enter a message below. When you are finished, click Process.", None))
self.group_message.setTitle(_translate("MainWindow", "Message", None))
self.btn_load_text_file.setText(_translate("MainWindow", "Load Text File", None))
self.lbl_num_characters.setText(_translate("MainWindow", "0 / 0 characters", None))
self.lbl_message_info.setText(_translate("MainWindow", "Enter the message you would like to encode into the box. Whitespace characters will be converted into spaces. English letters, numbers, and spaces are supported, plus the following characters: ", None))
self.lbl_allowed_symbols.setText(_translate("MainWindow", "!\"#$%&\'()\\ *+-,/:;<=> ?@[]^_`{|}~", None))
self.btn_process.setText(_translate("MainWindow", "Process", None))
self.lbl_spacing_info_2.setText(_translate("MainWindow", "Copyright © 2015 Nick Klose", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
nklose/Steganography
|
gui_main.py
|
Python
|
gpl-2.0
| 15,883
|
<article id="post-0" class="<?php hybrid_entry_class(); ?>">
<header class="entry-header">
<h1 class="entry-title"><?php _e( 'Nothing found', 'socially-awkward' ); ?></h1>
</header>
<div class="entry-content">
<p><?php _e( 'Apologies, but no entries were found.', 'socially-awkward' ); ?></p>
</div><!-- .entry-content -->
</article><!-- .hentry .error -->
|
katidid/greffdesign_old
|
wp-content/themes/socially-awkward/loop-error.php
|
PHP
|
gpl-2.0
| 385
|
// **********************************************************************
//
// Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
package Demo;
public class MyGreeting implements java.io.Serializable
{
public String text;
}
|
sbesson/zeroc-ice
|
java/demo/Ice/serialize/Demo/MyGreeting.java
|
Java
|
gpl-2.0
| 440
|
<div class="search-job-string">
<?php
$view = '<div class="row row-' . $job_string['number'] . '">';
$view .= '<div class="title title-' . $job_string['number'] . '">' . $job_string['title'] . '</div>';
$view .= '<div class="price price-' . $job_string['number'] . '">' . $job_string['price'] . '</div>';
$view .= '<div class="description description-' . $job_string['number'] . '">' . $job_string['description'] . '</div>';
$view .= '<div class="date date-' . $job_string['number'] . '">' . $job_string['created'] . '</div>';
$view .= '</div>';
print $view;
?>
</div>
|
arrides/cassowary
|
sites/all/modules/custom/cassowary_search/cassowary-search-job-string.tpl.php
|
PHP
|
gpl-2.0
| 582
|
/* Copyright (c) 2011-2012, The 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/init.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <asm/dma.h>
#include "msm-pcm-q6.h"
#include "msm-pcm-routing.h"
#include "qdsp6/q6voice.h"
#define VOIP_MAX_Q_LEN 10
#define VOIP_MAX_VOC_PKT_SIZE 640
#define VOIP_MIN_VOC_PKT_SIZE 320
#define DSP_FRAME_HDR_LEN 1
#define MODE_IS127 0x2
#define MODE_4GV_NB 0x3
#define MODE_4GV_WB 0x4
#define MODE_AMR 0x5
#define MODE_AMR_WB 0xD
#define MODE_PCM 0xC
#define MODE_G711 0xA
#define MODE_G711A 0xF
enum msm_audio_g711a_frame_type {
MVS_G711A_SPEECH_GOOD,
MVS_G711A_SID,
MVS_G711A_NO_DATA,
MVS_G711A_ERASURE
};
enum msm_audio_g711a_mode {
MVS_G711A_MODE_MULAW,
MVS_G711A_MODE_ALAW
};
enum msm_audio_g711_mode {
MVS_G711_MODE_MULAW,
MVS_G711_MODE_ALAW
};
#undef pr_info
#undef pr_err
#define pr_info(fmt, ...) pr_aud_info(fmt, ##__VA_ARGS__)
#define pr_err(fmt, ...) pr_aud_err(fmt, ##__VA_ARGS__)
enum format {
FORMAT_S16_LE = 2,
FORMAT_SPECIAL = 31,
};
enum amr_rate_type {
AMR_RATE_4750,
AMR_RATE_5150,
AMR_RATE_5900,
AMR_RATE_6700,
AMR_RATE_7400,
AMR_RATE_7950,
AMR_RATE_10200,
AMR_RATE_12200,
AMR_RATE_6600,
AMR_RATE_8850,
AMR_RATE_12650,
AMR_RATE_14250,
AMR_RATE_15850,
AMR_RATE_18250,
AMR_RATE_19850,
AMR_RATE_23050,
AMR_RATE_23850,
AMR_RATE_UNDEF
};
enum voip_state {
VOIP_STOPPED,
VOIP_STARTED,
};
struct voip_frame {
union {
uint32_t frame_type;
uint32_t packet_rate;
} header;
uint32_t len;
uint8_t voc_pkt[VOIP_MAX_VOC_PKT_SIZE];
};
struct voip_buf_node {
struct list_head list;
struct voip_frame frame;
};
struct voip_drv_info {
enum voip_state state;
struct snd_pcm_substream *playback_substream;
struct snd_pcm_substream *capture_substream;
struct list_head in_queue;
struct list_head free_in_queue;
struct list_head out_queue;
struct list_head free_out_queue;
wait_queue_head_t out_wait;
wait_queue_head_t in_wait;
struct mutex lock;
spinlock_t dsp_lock;
spinlock_t dsp_ul_lock;
uint32_t mode;
uint32_t rate_type;
uint32_t rate;
uint32_t dtx_mode;
uint8_t capture_start;
uint8_t playback_start;
uint8_t playback_instance;
uint8_t capture_instance;
unsigned int play_samp_rate;
unsigned int cap_samp_rate;
unsigned int pcm_size;
unsigned int pcm_count;
unsigned int pcm_playback_irq_pos;
unsigned int pcm_playback_buf_pos;
unsigned int pcm_capture_size;
unsigned int pcm_capture_count;
unsigned int pcm_capture_irq_pos;
unsigned int pcm_capture_buf_pos;
};
static int voip_get_media_type(uint32_t mode, uint32_t rate_type,
unsigned int samp_rate);
static int voip_get_rate_type(uint32_t mode,
uint32_t rate,
uint32_t *rate_type);
static int msm_voip_mode_rate_config_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol);
static int msm_voip_mode_rate_config_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol);
static struct voip_drv_info voip_info;
static struct snd_pcm_hardware msm_pcm_hardware = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED),
.formats = SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_SPECIAL,
.rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000,
.rate_min = 8000,
.rate_max = 16000,
.channels_min = 1,
.channels_max = 1,
.buffer_bytes_max = sizeof(struct voip_buf_node) * VOIP_MAX_Q_LEN,
.period_bytes_min = VOIP_MIN_VOC_PKT_SIZE,
.period_bytes_max = VOIP_MAX_VOC_PKT_SIZE,
.periods_min = VOIP_MAX_Q_LEN,
.periods_max = VOIP_MAX_Q_LEN,
.fifo_size = 0,
};
static int msm_voip_mute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int mute = ucontrol->value.integer.value[0];
pr_debug("%s: mute=%d\n", __func__, mute);
voc_set_tx_mute(voc_get_session_id(VOIP_SESSION_NAME), TX_PATH, mute);
return 0;
}
static int msm_voip_mute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int msm_voip_volume_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int volume = ucontrol->value.integer.value[0];
pr_debug("%s: volume: %d\n", __func__, volume);
voc_set_rx_vol_index(voc_get_session_id(VOIP_SESSION_NAME),
RX_PATH,
volume);
return 0;
}
static int msm_voip_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int msm_voip_dtx_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
mutex_lock(&voip_info.lock);
voip_info.dtx_mode = ucontrol->value.integer.value[0];
pr_debug("%s: dtx: %d\n", __func__, voip_info.dtx_mode);
mutex_unlock(&voip_info.lock);
return 0;
}
static int msm_voip_dtx_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
mutex_lock(&voip_info.lock);
ucontrol->value.integer.value[0] = voip_info.dtx_mode;
mutex_unlock(&voip_info.lock);
return 0;
}
static int msm_voip_fens_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int fens_enable = ucontrol->value.integer.value[0];
pr_info("%s: FENS_VOIP enable=%d\n", __func__, fens_enable);
voc_set_pp_enable(voc_get_session_id(VOIP_SESSION_NAME),
MODULE_ID_VOICE_MODULE_FENS, fens_enable);
return 0;
}
static int msm_voip_fens_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] =
voc_get_pp_enable(voc_get_session_id(VOIP_SESSION_NAME),
MODULE_ID_VOICE_MODULE_FENS);
return 0;
}
static struct snd_kcontrol_new msm_voip_controls[] = {
SOC_SINGLE_EXT("Voip Tx Mute", SND_SOC_NOPM, 0, 1, 0,
msm_voip_mute_get, msm_voip_mute_put),
SOC_SINGLE_EXT("Voip Rx Volume", SND_SOC_NOPM, 0, 5, 0,
msm_voip_volume_get, msm_voip_volume_put),
SOC_SINGLE_MULTI_EXT("Voip Mode Rate Config", SND_SOC_NOPM, 0, 23850,
0, 2, msm_voip_mode_rate_config_get,
msm_voip_mode_rate_config_put),
SOC_SINGLE_EXT("Voip Dtx Mode", SND_SOC_NOPM, 0, 1, 0,
msm_voip_dtx_mode_get, msm_voip_dtx_mode_put),
SOC_SINGLE_EXT("FENS_VOIP Enable", SND_SOC_NOPM, 0, 1, 0,
msm_voip_fens_get, msm_voip_fens_put),
};
static int msm_pcm_voip_probe(struct snd_soc_platform *platform)
{
snd_soc_add_platform_controls(platform, msm_voip_controls,
ARRAY_SIZE(msm_voip_controls));
return 0;
}
static unsigned int supported_sample_rates[] = {8000, 16000};
static void voip_process_ul_pkt(uint8_t *voc_pkt,
uint32_t pkt_len,
void *private_data)
{
struct voip_buf_node *buf_node = NULL;
struct voip_drv_info *prtd = private_data;
unsigned long dsp_flags;
if (prtd->capture_substream == NULL)
return;
spin_lock_irqsave(&prtd->dsp_ul_lock, dsp_flags);
if (!list_empty(&prtd->free_out_queue) && prtd->capture_start) {
buf_node = list_first_entry(&prtd->free_out_queue,
struct voip_buf_node, list);
list_del(&buf_node->list);
switch (prtd->mode) {
case MODE_AMR_WB:
case MODE_AMR: {
buf_node->frame.header.frame_type =
((*voc_pkt) & 0xF0) >> 4;
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
buf_node->frame.len = pkt_len - DSP_FRAME_HDR_LEN;
memcpy(&buf_node->frame.voc_pkt[0],
voc_pkt,
buf_node->frame.len);
list_add_tail(&buf_node->list, &prtd->out_queue);
break;
}
case MODE_IS127:
case MODE_4GV_NB:
case MODE_4GV_WB: {
buf_node->frame.header.packet_rate = (*voc_pkt) & 0x0F;
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
buf_node->frame.len = pkt_len - DSP_FRAME_HDR_LEN;
memcpy(&buf_node->frame.voc_pkt[0],
voc_pkt,
buf_node->frame.len);
list_add_tail(&buf_node->list, &prtd->out_queue);
break;
}
case MODE_G711:
case MODE_G711A:{
/* G711 frames are 10ms each, but the DSP works with
* 20ms frames and sends two 10ms frames per buffer.
* Extract the two frames and put them in separate
* buffers.
*/
/* Remove the first DSP frame info header.
* Header format: G711A
* Bits 0-1: Frame type
* Bits 2-3: Frame rate
*
* Header format: G711
* Bits 2-3: Frame rate
*/
if (prtd->mode == MODE_G711A)
buf_node->frame.header.frame_type =
(*voc_pkt) & 0x03;
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
/* There are two frames in the buffer. Length of the
* first frame:
*/
buf_node->frame.len = (pkt_len -
2 * DSP_FRAME_HDR_LEN) / 2;
memcpy(&buf_node->frame.voc_pkt[0],
voc_pkt,
buf_node->frame.len);
voc_pkt = voc_pkt + buf_node->frame.len;
list_add_tail(&buf_node->list, &prtd->out_queue);
/* Get another buffer from the free Q and fill in the
* second frame.
*/
if (!list_empty(&prtd->free_out_queue)) {
buf_node =
list_first_entry(&prtd->free_out_queue,
struct voip_buf_node,
list);
list_del(&buf_node->list);
/* Remove the second DSP frame info header.
* Header format:
* Bits 0-1: Frame type
* Bits 2-3: Frame rate
*/
if (prtd->mode == MODE_G711A)
buf_node->frame.header.frame_type =
(*voc_pkt) & 0x03;
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
/* There are two frames in the buffer. Length
* of the second frame:
*/
buf_node->frame.len = (pkt_len -
2 * DSP_FRAME_HDR_LEN) / 2;
memcpy(&buf_node->frame.voc_pkt[0],
voc_pkt,
buf_node->frame.len);
list_add_tail(&buf_node->list,
&prtd->out_queue);
} else {
/* Drop the second frame */
pr_err("%s: UL data dropped, read is slow\n",
__func__);
}
break;
}
default: {
buf_node->frame.len = pkt_len;
memcpy(&buf_node->frame.voc_pkt[0],
voc_pkt,
buf_node->frame.len);
list_add_tail(&buf_node->list, &prtd->out_queue);
}
}
pr_debug("ul_pkt: pkt_len =%d, frame.len=%d\n", pkt_len,
buf_node->frame.len);
prtd->pcm_capture_irq_pos += prtd->pcm_capture_count;
spin_unlock_irqrestore(&prtd->dsp_ul_lock, dsp_flags);
snd_pcm_period_elapsed(prtd->capture_substream);
} else {
spin_unlock_irqrestore(&prtd->dsp_ul_lock, dsp_flags);
pr_err("UL data dropped\n");
}
wake_up(&prtd->out_wait);
}
static void voip_process_dl_pkt(uint8_t *voc_pkt,
uint32_t *pkt_len,
void *private_data)
{
struct voip_buf_node *buf_node = NULL;
struct voip_drv_info *prtd = private_data;
unsigned long dsp_flags;
if (prtd->playback_substream == NULL)
return;
spin_lock_irqsave(&prtd->dsp_lock, dsp_flags);
if (!list_empty(&prtd->in_queue) && prtd->playback_start) {
buf_node = list_first_entry(&prtd->in_queue,
struct voip_buf_node, list);
list_del(&buf_node->list);
switch (prtd->mode) {
case MODE_AMR:
case MODE_AMR_WB: {
*voc_pkt = ((buf_node->frame.header.frame_type &
0x0F) << 4) | (prtd->rate_type & 0x0F);
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
*pkt_len = buf_node->frame.len + DSP_FRAME_HDR_LEN;
memcpy(voc_pkt,
&buf_node->frame.voc_pkt[0],
buf_node->frame.len);
list_add_tail(&buf_node->list, &prtd->free_in_queue);
break;
}
case MODE_IS127:
case MODE_4GV_NB:
case MODE_4GV_WB: {
*voc_pkt = buf_node->frame.header.packet_rate & 0x0F;
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
*pkt_len = buf_node->frame.len + DSP_FRAME_HDR_LEN;
memcpy(voc_pkt,
&buf_node->frame.voc_pkt[0],
buf_node->frame.len);
list_add_tail(&buf_node->list, &prtd->free_in_queue);
break;
}
case MODE_G711:
case MODE_G711A:{
/* G711 frames are 10ms each but the DSP expects 20ms
* worth of data, so send two 10ms frames per buffer.
*/
/* Add the first DSP frame info header. Header format:
* Bits 0-1: Frame type
* Bits 2-3: Frame rate
*/
*voc_pkt = ((prtd->rate_type & 0x0F) << 2) |
(buf_node->frame.header.frame_type & 0x03);
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
*pkt_len = buf_node->frame.len + DSP_FRAME_HDR_LEN;
memcpy(voc_pkt,
&buf_node->frame.voc_pkt[0],
buf_node->frame.len);
voc_pkt = voc_pkt + buf_node->frame.len;
list_add_tail(&buf_node->list, &prtd->free_in_queue);
if (!list_empty(&prtd->in_queue)) {
/* Get the second buffer. */
buf_node = list_first_entry(&prtd->in_queue,
struct voip_buf_node,
list);
list_del(&buf_node->list);
/* Add the second DSP frame info header.
* Header format:
* Bits 0-1: Frame type
* Bits 2-3: Frame rate
*/
*voc_pkt = ((prtd->rate_type & 0x0F) << 2) |
(buf_node->frame.header.frame_type & 0x03);
voc_pkt = voc_pkt + DSP_FRAME_HDR_LEN;
*pkt_len = *pkt_len +
buf_node->frame.len + DSP_FRAME_HDR_LEN;
memcpy(voc_pkt,
&buf_node->frame.voc_pkt[0],
buf_node->frame.len);
list_add_tail(&buf_node->list,
&prtd->free_in_queue);
} else {
/* Only 10ms worth of data is available, signal
* erasure frame.
*/
*voc_pkt = ((prtd->rate_type & 0x0F) << 2) |
(MVS_G711A_ERASURE & 0x03);
*pkt_len = *pkt_len + DSP_FRAME_HDR_LEN;
pr_debug("%s, Only 10ms read, erase 2nd frame\n",
__func__);
}
break;
}
default: {
*pkt_len = buf_node->frame.len;
memcpy(voc_pkt,
&buf_node->frame.voc_pkt[0],
buf_node->frame.len);
list_add_tail(&buf_node->list, &prtd->free_in_queue);
}
}
pr_debug("dl_pkt: pkt_len=%d, frame_len=%d\n", *pkt_len,
buf_node->frame.len);
prtd->pcm_playback_irq_pos += prtd->pcm_count;
spin_unlock_irqrestore(&prtd->dsp_lock, dsp_flags);
snd_pcm_period_elapsed(prtd->playback_substream);
} else {
*pkt_len = 0;
spin_unlock_irqrestore(&prtd->dsp_lock, dsp_flags);
pr_err("DL data not available\n");
}
wake_up(&prtd->in_wait);
}
static struct snd_pcm_hw_constraint_list constraints_sample_rates = {
.count = ARRAY_SIZE(supported_sample_rates),
.list = supported_sample_rates,
.mask = 0,
};
static int msm_pcm_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
prtd->play_samp_rate = runtime->rate;
prtd->pcm_size = snd_pcm_lib_buffer_bytes(substream);
prtd->pcm_count = snd_pcm_lib_period_bytes(substream);
prtd->pcm_playback_irq_pos = 0;
prtd->pcm_playback_buf_pos = 0;
return 0;
}
static int msm_pcm_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
int ret = 0;
prtd->cap_samp_rate = runtime->rate;
prtd->pcm_capture_size = snd_pcm_lib_buffer_bytes(substream);
prtd->pcm_capture_count = snd_pcm_lib_period_bytes(substream);
prtd->pcm_capture_irq_pos = 0;
prtd->pcm_capture_buf_pos = 0;
return ret;
}
static int msm_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
int ret = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
pr_debug("%s: Trigger start\n", __func__);
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
prtd->capture_start = 1;
else
prtd->playback_start = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
pr_debug("SNDRV_PCM_TRIGGER_STOP\n");
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
prtd->playback_start = 0;
else
prtd->capture_start = 0;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int msm_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = &voip_info;
int ret = 0;
pr_debug("%s, VoIP\n", __func__);
mutex_lock(&prtd->lock);
runtime->hw = msm_pcm_hardware;
ret = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE,
&constraints_sample_rates);
if (ret < 0)
pr_debug("snd_pcm_hw_constraint_list failed\n");
ret = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (ret < 0) {
pr_debug("snd_pcm_hw_constraint_integer failed\n");
goto err;
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
prtd->playback_substream = substream;
prtd->playback_instance++;
} else {
prtd->capture_substream = substream;
prtd->capture_instance++;
}
runtime->private_data = prtd;
err:
mutex_unlock(&prtd->lock);
return ret;
}
static int msm_pcm_playback_copy(struct snd_pcm_substream *substream, int a,
snd_pcm_uframes_t hwoff, void __user *buf, snd_pcm_uframes_t frames)
{
int ret = 0;
struct voip_buf_node *buf_node = NULL;
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
unsigned long dsp_flags;
int count = frames_to_bytes(runtime, frames);
pr_debug("%s: count = %d, frames=%d\n", __func__, count, (int)frames);
ret = wait_event_interruptible_timeout(prtd->in_wait,
(!list_empty(&prtd->free_in_queue) ||
prtd->state == VOIP_STOPPED),
1 * HZ);
if (ret > 0) {
if (count <= VOIP_MAX_VOC_PKT_SIZE) {
spin_lock_irqsave(&prtd->dsp_lock, dsp_flags);
buf_node =
list_first_entry(&prtd->free_in_queue,
struct voip_buf_node, list);
list_del(&buf_node->list);
spin_unlock_irqrestore(&prtd->dsp_lock, dsp_flags);
if (prtd->mode == MODE_PCM) {
ret = copy_from_user(&buf_node->frame.voc_pkt,
buf, count);
buf_node->frame.len = count;
} else
ret = copy_from_user(&buf_node->frame,
buf, count);
spin_lock_irqsave(&prtd->dsp_lock, dsp_flags);
list_add_tail(&buf_node->list, &prtd->in_queue);
spin_unlock_irqrestore(&prtd->dsp_lock, dsp_flags);
} else {
pr_err("%s: Write cnt %d is > VOIP_MAX_VOC_PKT_SIZE\n",
__func__, count);
ret = -ENOMEM;
}
} else if (ret == 0) {
pr_err("%s: No free DL buffs\n", __func__);
ret = -ETIMEDOUT;
} else {
pr_err("%s: playback copy was interrupted\n", __func__);
}
return ret;
}
static int msm_pcm_capture_copy(struct snd_pcm_substream *substream,
int channel, snd_pcm_uframes_t hwoff, void __user *buf,
snd_pcm_uframes_t frames)
{
int ret = 0;
int count = 0;
struct voip_buf_node *buf_node = NULL;
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
unsigned long dsp_flags;
count = frames_to_bytes(runtime, frames);
pr_debug("%s: count = %d\n", __func__, count);
ret = wait_event_interruptible_timeout(prtd->out_wait,
(!list_empty(&prtd->out_queue) ||
prtd->state == VOIP_STOPPED),
1 * HZ);
if (ret > 0) {
if (count <= VOIP_MAX_VOC_PKT_SIZE) {
spin_lock_irqsave(&prtd->dsp_ul_lock, dsp_flags);
buf_node = list_first_entry(&prtd->out_queue,
struct voip_buf_node, list);
list_del(&buf_node->list);
spin_unlock_irqrestore(&prtd->dsp_ul_lock, dsp_flags);
if (prtd->mode == MODE_PCM)
ret = copy_to_user(buf,
&buf_node->frame.voc_pkt,
count);
else
ret = copy_to_user(buf,
&buf_node->frame,
count);
if (ret) {
pr_err("%s: Copy to user retuned %d\n",
__func__, ret);
ret = -EFAULT;
}
spin_lock_irqsave(&prtd->dsp_ul_lock, dsp_flags);
list_add_tail(&buf_node->list,
&prtd->free_out_queue);
spin_unlock_irqrestore(&prtd->dsp_ul_lock, dsp_flags);
} else {
pr_err("%s: Read count %d > VOIP_MAX_VOC_PKT_SIZE\n",
__func__, count);
ret = -ENOMEM;
}
} else if (ret == 0) {
pr_err("%s: No UL data available\n", __func__);
ret = -ETIMEDOUT;
} else {
pr_err("%s: Read was interrupted\n", __func__);
ret = -ERESTARTSYS;
}
return ret;
}
static int msm_pcm_copy(struct snd_pcm_substream *substream, int a,
snd_pcm_uframes_t hwoff, void __user *buf, snd_pcm_uframes_t frames)
{
int ret = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_copy(substream, a, hwoff, buf, frames);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_copy(substream, a, hwoff, buf, frames);
return ret;
}
static int msm_pcm_close(struct snd_pcm_substream *substream)
{
int ret = 0;
struct list_head *ptr = NULL;
struct list_head *next = NULL;
struct voip_buf_node *buf_node = NULL;
struct snd_dma_buffer *p_dma_buf, *c_dma_buf;
struct snd_pcm_substream *p_substream, *c_substream;
struct snd_pcm_runtime *runtime;
struct voip_drv_info *prtd;
unsigned long dsp_flags;
if (substream == NULL) {
pr_err("substream is NULL\n");
return -EINVAL;
}
runtime = substream->runtime;
prtd = runtime->private_data;
wake_up(&prtd->out_wait);
mutex_lock(&prtd->lock);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
prtd->playback_instance--;
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
prtd->capture_instance--;
if (!prtd->playback_instance && !prtd->capture_instance) {
if (prtd->state == VOIP_STARTED) {
prtd->state = VOIP_STOPPED;
voc_end_voice_call(
voc_get_session_id(VOIP_SESSION_NAME));
voc_register_mvs_cb(NULL, NULL, prtd);
}
pr_debug("release all buffer\n");
p_substream = prtd->playback_substream;
if (p_substream == NULL) {
pr_debug("p_substream is NULL\n");
goto capt;
}
p_dma_buf = &p_substream->dma_buffer;
if (p_dma_buf == NULL) {
pr_debug("p_dma_buf is NULL\n");
goto capt;
}
if (p_dma_buf->area != NULL) {
spin_lock_irqsave(&prtd->dsp_lock, dsp_flags);
list_for_each_safe(ptr, next, &prtd->in_queue) {
buf_node = list_entry(ptr,
struct voip_buf_node, list);
list_del(&buf_node->list);
}
list_for_each_safe(ptr, next, &prtd->free_in_queue) {
buf_node = list_entry(ptr,
struct voip_buf_node, list);
list_del(&buf_node->list);
}
spin_unlock_irqrestore(&prtd->dsp_lock, dsp_flags);
dma_free_coherent(p_substream->pcm->card->dev,
runtime->hw.buffer_bytes_max, p_dma_buf->area,
p_dma_buf->addr);
p_dma_buf->area = NULL;
}
capt: c_substream = prtd->capture_substream;
if (c_substream == NULL) {
pr_debug("c_substream is NULL\n");
goto done;
}
c_dma_buf = &c_substream->dma_buffer;
if (c_substream == NULL) {
pr_debug("c_dma_buf is NULL.\n");
goto done;
}
if (c_dma_buf->area != NULL) {
spin_lock_irqsave(&prtd->dsp_ul_lock, dsp_flags);
list_for_each_safe(ptr, next, &prtd->out_queue) {
buf_node = list_entry(ptr,
struct voip_buf_node, list);
list_del(&buf_node->list);
}
list_for_each_safe(ptr, next, &prtd->free_out_queue) {
buf_node = list_entry(ptr,
struct voip_buf_node, list);
list_del(&buf_node->list);
}
spin_unlock_irqrestore(&prtd->dsp_ul_lock, dsp_flags);
dma_free_coherent(c_substream->pcm->card->dev,
runtime->hw.buffer_bytes_max, c_dma_buf->area,
c_dma_buf->addr);
c_dma_buf->area = NULL;
}
done:
prtd->capture_substream = NULL;
prtd->playback_substream = NULL;
}
mutex_unlock(&prtd->lock);
return ret;
}
static int msm_pcm_prepare(struct snd_pcm_substream *substream)
{
int ret = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
uint32_t media_type = 0;
uint32_t rate_type = 0;
mutex_lock(&prtd->lock);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_prepare(substream);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_prepare(substream);
if ((runtime->format != FORMAT_SPECIAL) &&
((prtd->mode == MODE_AMR) || (prtd->mode == MODE_AMR_WB) ||
(prtd->mode == MODE_IS127) || (prtd->mode == MODE_4GV_NB) ||
(prtd->mode == MODE_4GV_WB) || (prtd->mode == MODE_G711) ||
(prtd->mode == MODE_G711A))) {
pr_err("mode:%d and format:%u are not mached\n",
prtd->mode, (uint32_t)runtime->format);
ret = -EINVAL;
goto done;
}
if ((runtime->format != FORMAT_S16_LE) &&
(prtd->mode == MODE_PCM)) {
pr_err("mode:%d and format:%u are not mached\n",
prtd->mode, (uint32_t)runtime->format);
ret = -EINVAL;
goto done;
}
if (prtd->playback_instance && prtd->capture_instance
&& (prtd->state != VOIP_STARTED)) {
ret = voip_get_rate_type(prtd->mode,
prtd->rate,
&rate_type);
if (ret < 0) {
pr_err("fail at getting rate_type\n");
ret = -EINVAL;
goto done;
}
prtd->rate_type = rate_type;
media_type = voip_get_media_type(prtd->mode,
prtd->rate_type,
prtd->play_samp_rate);
if (media_type < 0) {
pr_err("fail at getting media_type\n");
ret = -EINVAL;
goto done;
}
pr_debug(" media_type=%d, rate_type=%d\n", media_type,
rate_type);
if ((prtd->play_samp_rate == 8000) &&
(prtd->cap_samp_rate == 8000))
voc_config_vocoder(media_type, rate_type,
VSS_NETWORK_ID_VOIP_NB,
voip_info.dtx_mode);
else if ((prtd->play_samp_rate == 16000) &&
(prtd->cap_samp_rate == 16000))
voc_config_vocoder(media_type, rate_type,
VSS_NETWORK_ID_VOIP_WB,
voip_info.dtx_mode);
else {
pr_debug("%s: Invalid rate playback %d, capture %d\n",
__func__, prtd->play_samp_rate,
prtd->cap_samp_rate);
goto done;
}
voc_register_mvs_cb(voip_process_ul_pkt,
voip_process_dl_pkt, prtd);
voc_start_voice_call(voc_get_session_id(VOIP_SESSION_NAME));
prtd->state = VOIP_STARTED;
}
done:
mutex_unlock(&prtd->lock);
return ret;
}
static snd_pcm_uframes_t
msm_pcm_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
pr_debug("%s\n", __func__);
if (prtd->pcm_playback_irq_pos >= prtd->pcm_size)
prtd->pcm_playback_irq_pos = 0;
return bytes_to_frames(runtime, (prtd->pcm_playback_irq_pos));
}
static snd_pcm_uframes_t
msm_pcm_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct voip_drv_info *prtd = runtime->private_data;
if (prtd->pcm_capture_irq_pos >= prtd->pcm_capture_size)
prtd->pcm_capture_irq_pos = 0;
return bytes_to_frames(runtime, (prtd->pcm_capture_irq_pos));
}
static snd_pcm_uframes_t msm_pcm_pointer(struct snd_pcm_substream *substream)
{
snd_pcm_uframes_t ret = 0;
pr_debug("%s\n", __func__);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_pointer(substream);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_pointer(substream);
return ret;
}
static int msm_pcm_mmap(struct snd_pcm_substream *substream,
struct vm_area_struct *vma)
{
struct snd_pcm_runtime *runtime = substream->runtime;
pr_debug("%s\n", __func__);
dma_mmap_coherent(substream->pcm->card->dev, vma,
runtime->dma_area,
runtime->dma_addr,
runtime->dma_bytes);
return 0;
}
static int msm_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_dma_buffer *dma_buf = &substream->dma_buffer;
struct voip_buf_node *buf_node = NULL;
int i = 0, offset = 0;
pr_debug("%s: voip\n", __func__);
mutex_lock(&voip_info.lock);
dma_buf->dev.type = SNDRV_DMA_TYPE_DEV;
dma_buf->dev.dev = substream->pcm->card->dev;
dma_buf->private_data = NULL;
dma_buf->area = dma_alloc_coherent(substream->pcm->card->dev,
runtime->hw.buffer_bytes_max,
&dma_buf->addr, GFP_KERNEL);
if (!dma_buf->area) {
pr_err("%s:MSM VOIP dma_alloc failed\n", __func__);
return -ENOMEM;
}
dma_buf->bytes = runtime->hw.buffer_bytes_max;
memset(dma_buf->area, 0, runtime->hw.buffer_bytes_max);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
for (i = 0; i < VOIP_MAX_Q_LEN; i++) {
buf_node = (void *)dma_buf->area + offset;
list_add_tail(&buf_node->list,
&voip_info.free_in_queue);
offset = offset + sizeof(struct voip_buf_node);
}
} else {
for (i = 0; i < VOIP_MAX_Q_LEN; i++) {
buf_node = (void *) dma_buf->area + offset;
list_add_tail(&buf_node->list,
&voip_info.free_out_queue);
offset = offset + sizeof(struct voip_buf_node);
}
}
mutex_unlock(&voip_info.lock);
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
return 0;
}
static int msm_voip_mode_rate_config_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
mutex_lock(&voip_info.lock);
ucontrol->value.integer.value[0] = voip_info.mode;
ucontrol->value.integer.value[1] = voip_info.rate;
mutex_unlock(&voip_info.lock);
return 0;
}
static int msm_voip_mode_rate_config_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
mutex_lock(&voip_info.lock);
voip_info.mode = ucontrol->value.integer.value[0];
voip_info.rate = ucontrol->value.integer.value[1];
pr_debug("%s: mode=%d,rate=%d\n", __func__, voip_info.mode,
voip_info.rate);
mutex_unlock(&voip_info.lock);
return 0;
}
static int voip_get_rate_type(uint32_t mode, uint32_t rate,
uint32_t *rate_type)
{
int ret = 0;
switch (mode) {
case MODE_AMR: {
switch (rate) {
case 4750:
*rate_type = AMR_RATE_4750;
break;
case 5150:
*rate_type = AMR_RATE_5150;
break;
case 5900:
*rate_type = AMR_RATE_5900;
break;
case 6700:
*rate_type = AMR_RATE_6700;
break;
case 7400:
*rate_type = AMR_RATE_7400;
break;
case 7950:
*rate_type = AMR_RATE_7950;
break;
case 10200:
*rate_type = AMR_RATE_10200;
break;
case 12200:
*rate_type = AMR_RATE_12200;
break;
default:
pr_err("wrong rate for AMR NB.\n");
ret = -EINVAL;
break;
}
break;
}
case MODE_AMR_WB: {
switch (rate) {
case 6600:
*rate_type = AMR_RATE_6600 - AMR_RATE_6600;
break;
case 8850:
*rate_type = AMR_RATE_8850 - AMR_RATE_6600;
break;
case 12650:
*rate_type = AMR_RATE_12650 - AMR_RATE_6600;
break;
case 14250:
*rate_type = AMR_RATE_14250 - AMR_RATE_6600;
break;
case 15850:
*rate_type = AMR_RATE_15850 - AMR_RATE_6600;
break;
case 18250:
*rate_type = AMR_RATE_18250 - AMR_RATE_6600;
break;
case 19850:
*rate_type = AMR_RATE_19850 - AMR_RATE_6600;
break;
case 23050:
*rate_type = AMR_RATE_23050 - AMR_RATE_6600;
break;
case 23850:
*rate_type = AMR_RATE_23850 - AMR_RATE_6600;
break;
default:
pr_err("wrong rate for AMR_WB.\n");
ret = -EINVAL;
break;
}
break;
}
case MODE_PCM: {
*rate_type = 0;
break;
}
case MODE_IS127:
case MODE_4GV_NB:
case MODE_4GV_WB: {
switch (rate) {
case VOC_0_RATE:
case VOC_8_RATE:
case VOC_4_RATE:
case VOC_2_RATE:
case VOC_1_RATE:
*rate_type = rate;
break;
default:
pr_err("wrong rate for IS127/4GV_NB/WB.\n");
ret = -EINVAL;
break;
}
break;
}
case MODE_G711:
case MODE_G711A:
*rate_type = rate;
break;
default:
pr_err("wrong mode type.\n");
ret = -EINVAL;
}
pr_debug("%s, mode=%d, rate=%u, rate_type=%d\n",
__func__, mode, rate, *rate_type);
return ret;
}
static int voip_get_media_type(uint32_t mode, uint32_t rate_type,
unsigned int samp_rate)
{
uint32_t media_type;
pr_debug("%s: mode=%d, samp_rate=%d\n", __func__,
mode, samp_rate);
switch (mode) {
case MODE_AMR:
media_type = VSS_MEDIA_ID_AMR_NB_MODEM;
break;
case MODE_AMR_WB:
media_type = VSS_MEDIA_ID_AMR_WB_MODEM;
break;
case MODE_PCM:
if (samp_rate == 8000)
media_type = VSS_MEDIA_ID_PCM_NB;
else
media_type = VSS_MEDIA_ID_PCM_WB;
break;
case MODE_IS127:
media_type = VSS_MEDIA_ID_EVRC_MODEM;
break;
case MODE_4GV_NB:
media_type = VSS_MEDIA_ID_4GV_NB_MODEM;
break;
case MODE_4GV_WB:
media_type = VSS_MEDIA_ID_4GV_WB_MODEM;
break;
case MODE_G711:
case MODE_G711A:
if (rate_type == MVS_G711A_MODE_MULAW)
media_type = VSS_MEDIA_ID_G711_MULAW;
else
media_type = VSS_MEDIA_ID_G711_ALAW;
break;
default:
pr_debug(" input mode is not supported\n");
media_type = -EINVAL;
}
pr_debug("%s: media_type is 0x%x\n", __func__, media_type);
return media_type;
}
static struct snd_pcm_ops msm_pcm_ops = {
.open = msm_pcm_open,
.copy = msm_pcm_copy,
.hw_params = msm_pcm_hw_params,
.close = msm_pcm_close,
.prepare = msm_pcm_prepare,
.trigger = msm_pcm_trigger,
.pointer = msm_pcm_pointer,
.mmap = msm_pcm_mmap,
};
static int msm_asoc_pcm_new(struct snd_soc_pcm_runtime *rtd)
{
struct snd_card *card = rtd->card->snd_card;
int ret = 0;
pr_debug("msm_asoc_pcm_new\n");
if (!card->dev->coherent_dma_mask)
card->dev->coherent_dma_mask = DMA_BIT_MASK(32);
return ret;
}
static struct snd_soc_platform_driver msm_soc_platform = {
.ops = &msm_pcm_ops,
.pcm_new = msm_asoc_pcm_new,
.probe = msm_pcm_voip_probe,
};
static __devinit int msm_pcm_probe(struct platform_device *pdev)
{
pr_info("%s: dev name %s\n", __func__, dev_name(&pdev->dev));
return snd_soc_register_platform(&pdev->dev,
&msm_soc_platform);
}
static int msm_pcm_remove(struct platform_device *pdev)
{
snd_soc_unregister_platform(&pdev->dev);
return 0;
}
static struct platform_driver msm_pcm_driver = {
.driver = {
.name = "msm-voip-dsp",
.owner = THIS_MODULE,
},
.probe = msm_pcm_probe,
.remove = __devexit_p(msm_pcm_remove),
};
static int __init msm_soc_platform_init(void)
{
memset(&voip_info, 0, sizeof(voip_info));
voip_info.mode = MODE_PCM;
mutex_init(&voip_info.lock);
spin_lock_init(&voip_info.dsp_lock);
spin_lock_init(&voip_info.dsp_ul_lock);
init_waitqueue_head(&voip_info.out_wait);
init_waitqueue_head(&voip_info.in_wait);
INIT_LIST_HEAD(&voip_info.in_queue);
INIT_LIST_HEAD(&voip_info.free_in_queue);
INIT_LIST_HEAD(&voip_info.out_queue);
INIT_LIST_HEAD(&voip_info.free_out_queue);
return platform_driver_register(&msm_pcm_driver);
}
module_init(msm_soc_platform_init);
static void __exit msm_soc_platform_exit(void)
{
platform_driver_unregister(&msm_pcm_driver);
}
module_exit(msm_soc_platform_exit);
MODULE_DESCRIPTION("PCM module platform driver");
MODULE_LICENSE("GPL v2");
|
poondog/kangaroo-m7-mkII
|
sound/soc/msm/msm-pcm-voip.c
|
C
|
gpl-2.0
| 34,678
|
/*
* Created by SharpDevelop.
* User: Administrator
* Date: 12/16/2006
* Time: 12:32 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections;
namespace Metaverse.Common
{
/// <summary>
/// Description of IMetaverseController.
/// </summary>
public interface IMetaverseController
{
void RegisterMetaverseServer( IMetaverseServer server );
IMetaverseServer GetSimServer( ISim simulator );
void AttachSimulator( ISim simulator );
ArrayList GetSimulators();
}
}
|
hughperkins/osmp-cs
|
Source/Metaverse.Common/IMetaverseController.cs
|
C#
|
gpl-2.0
| 578
|
<?php
/**
* Elgg 1.8.3 upgrade 2012012000
* ip_in_syslog
*
* Adds a field for an IP address in the system log table
*/
$db_prefix = elgg_get_config ( 'dbprefix' );
$q = "ALTER TABLE {$db_prefix}system_log ADD ip_address VARCHAR(15) NOT NULL AFTER time_created";
update_data ( $q );
|
MikkelSandbag/seElgg
|
engine/lib/upgrades/2012012000-1.8.3-ip_in_syslog-87fe0f068cf62428.php
|
PHP
|
gpl-2.0
| 287
|
/***************************************************************************
qgsfiledownloader.cpp
--------------------------------------
Date : November 2016
Copyright : (C) 2016 by Alessandro Pasotti
Email : apasotti at boundlessgeo dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "qgsfiledownloader.h"
#include "qgsnetworkaccessmanager.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QMessageBox>
#ifndef QT_NO_SSL
#include <QSslError>
#endif
QgsFileDownloader::QgsFileDownloader( QUrl url, QString outputFileName, bool enableGuiNotifications )
: mUrl( url )
, mReply( nullptr )
, mProgressDialog( nullptr )
, mDownloadCanceled( false )
, mErrors()
, mGuiNotificationsEnabled( enableGuiNotifications )
{
mFile.setFileName( outputFileName );
startDownload();
}
QgsFileDownloader::~QgsFileDownloader()
{
if ( mReply )
{
mReply->abort();
mReply->deleteLater();
}
if ( mProgressDialog )
{
mProgressDialog->deleteLater();
}
}
void QgsFileDownloader::startDownload()
{
QgsNetworkAccessManager* nam = QgsNetworkAccessManager::instance();
QNetworkRequest request( mUrl );
mReply = nam->get( request );
connect( mReply, &QNetworkReply::readyRead, this, &QgsFileDownloader::onReadyRead );
connect( mReply, static_cast < void ( QNetworkReply::* )( QNetworkReply::NetworkError ) > ( &QNetworkReply::error ), this, &QgsFileDownloader::onNetworkError );
connect( mReply, &QNetworkReply::finished, this, &QgsFileDownloader::onFinished );
connect( mReply, &QNetworkReply::downloadProgress, this, &QgsFileDownloader::onDownloadProgress );
connect( nam, &QgsNetworkAccessManager::requestTimedOut, this, &QgsFileDownloader::onRequestTimedOut );
#ifndef QT_NO_SSL
connect( nam, &QgsNetworkAccessManager::sslErrors, this, &QgsFileDownloader::onSslErrors );
#endif
if ( mGuiNotificationsEnabled )
{
mProgressDialog = new QProgressDialog();
mProgressDialog->setWindowTitle( tr( "Download" ) );
mProgressDialog->setLabelText( tr( "Downloading %1." ).arg( mFile.fileName() ) );
mProgressDialog->show();
connect( mProgressDialog, &QProgressDialog::canceled, this, &QgsFileDownloader::onDownloadCanceled );
}
}
void QgsFileDownloader::onDownloadCanceled()
{
mDownloadCanceled = true;
emit downloadCanceled();
onFinished();
}
void QgsFileDownloader::onRequestTimedOut()
{
error( tr( "Network request %1 timed out" ).arg( mUrl.toString() ) );
}
#ifndef QT_NO_SSL
void QgsFileDownloader::onSslErrors( QNetworkReply *reply, const QList<QSslError> &errors )
{
Q_UNUSED( reply );
QStringList errorMessages;
errorMessages << "SSL Errors: ";
for ( auto end = errors.size(), i = 0; i != end; ++i )
{
errorMessages << errors[i].errorString();
}
error( errorMessages );
}
#endif
void QgsFileDownloader::error( QStringList errorMessages )
{
for ( auto end = errorMessages.size(), i = 0; i != end; ++i )
{
mErrors.append( errorMessages[i] );
}
// Show error
if ( mGuiNotificationsEnabled )
{
QMessageBox::warning( nullptr, tr( "Download failed" ), mErrors.join( "<br>" ) );
}
emit downloadError( mErrors );
}
void QgsFileDownloader::error( QString errorMessage )
{
error( QStringList() << errorMessage );
}
void QgsFileDownloader::onReadyRead()
{
Q_ASSERT( mReply );
if ( ! mFile.isOpen() && ! mFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
{
error( tr( "Cannot open output file: %1" ).arg( mFile.fileName() ) );
onFinished();
}
else
{
QByteArray data = mReply->readAll();
mFile.write( data );
}
}
void QgsFileDownloader::onFinished()
{
// when canceled
if ( ! mErrors.isEmpty() || mDownloadCanceled )
{
mFile.close();
mFile.remove();
if ( mGuiNotificationsEnabled )
mProgressDialog->hide();
}
else
{
// download finished normally
if ( mGuiNotificationsEnabled )
mProgressDialog->hide();
mFile.flush();
mFile.close();
// get redirection url
QVariant redirectionTarget = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
if ( mReply->error() )
{
mFile.remove();
error( tr( "Download failed: %1." ).arg( mReply->errorString() ) );
}
else if ( !redirectionTarget.isNull() )
{
QUrl newUrl = mUrl.resolved( redirectionTarget.toUrl() );
mUrl = newUrl;
mReply->deleteLater();
mFile.open( QIODevice::WriteOnly );
mFile.resize( 0 );
mFile.close();
startDownload();
return;
}
// All done
emit downloadCompleted();
}
emit downloadExited();
this->deleteLater();
}
void QgsFileDownloader::onNetworkError( QNetworkReply::NetworkError err )
{
Q_ASSERT( mReply );
error( QString( "Network error %1: %2" ).arg( err ).arg( mReply->errorString() ) );
}
void QgsFileDownloader::onDownloadProgress( qint64 bytesReceived, qint64 bytesTotal )
{
if ( mDownloadCanceled )
{
return;
}
if ( mGuiNotificationsEnabled )
{
mProgressDialog->setMaximum( bytesTotal );
mProgressDialog->setValue( bytesReceived );
}
emit downloadProgress( bytesReceived, bytesTotal );
}
|
drnextgis/QGIS
|
src/gui/qgsfiledownloader.cpp
|
C++
|
gpl-2.0
| 5,804
|
SB Breadcrumbs
===================================
SB Breadcrums is a plugin for Wordpress
SB Breadcrums will add a breadcrumbs for your website. Easy to use and custom style.
## How to use
Add the code `<?php sb_breadcrumbs(); ?>` in position you want display a breadcrumbs
You can go to *WP-Admin -> Settings -> SB Breadcrumbs* for configuration.
## Change Style
If you need to configure the CSS style of SB Breadcrumbs, you can uncheck the "Use Default Style" option from the settings page and add the styles to your theme's style.css file directly
|
trangsihung/sb-breadcrumbs
|
README.md
|
Markdown
|
gpl-2.0
| 558
|
/*****************************************************************************
* ctrl_resize.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id: ctrl_resize.cpp 16767 2006-09-21 14:32:45Z hartman $
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "ctrl_resize.hpp"
#include "../events/evt_generic.hpp"
#include "../events/evt_mouse.hpp"
#include "../events/evt_motion.hpp"
#include "../src/generic_layout.hpp"
#include "../src/os_factory.hpp"
#include "../utils/position.hpp"
#include "../commands/async_queue.hpp"
#include "../commands/cmd_resize.hpp"
CtrlResize::CtrlResize( intf_thread_t *pIntf, WindowManager &rWindowManager,
CtrlFlat &rCtrl, GenericLayout &rLayout,
const UString &rHelp, VarBool *pVisible,
WindowManager::Direction_t direction ):
CtrlFlat( pIntf, rHelp, pVisible ), m_fsm( pIntf ),
m_rWindowManager( rWindowManager ), m_rCtrl( rCtrl ),
m_rLayout( rLayout ), m_direction( direction ), m_cmdOutStill( this ),
m_cmdStillOut( this ),
m_cmdStillStill( this ),
m_cmdStillResize( this ),
m_cmdResizeStill( this ),
m_cmdResizeResize( this )
{
m_pEvt = NULL;
m_xPos = 0;
m_yPos = 0;
// States
m_fsm.addState( "out" );
m_fsm.addState( "still" );
m_fsm.addState( "resize" );
// Transitions
m_fsm.addTransition( "out", "enter", "still", &m_cmdOutStill );
m_fsm.addTransition( "still", "leave", "out", &m_cmdStillOut );
m_fsm.addTransition( "still", "motion", "still", &m_cmdStillStill );
m_fsm.addTransition( "resize", "mouse:left:up:none", "still",
&m_cmdResizeStill );
m_fsm.addTransition( "still", "mouse:left:down:none", "resize",
&m_cmdStillResize );
m_fsm.addTransition( "resize", "motion", "resize", &m_cmdResizeResize );
m_fsm.setState( "still" );
}
bool CtrlResize::mouseOver( int x, int y ) const
{
return m_rCtrl.mouseOver( x, y );
}
void CtrlResize::draw( OSGraphics &rImage, int xDest, int yDest )
{
m_rCtrl.draw( rImage, xDest, yDest );
}
void CtrlResize::setLayout( GenericLayout *pLayout, const Position &rPosition )
{
CtrlGeneric::setLayout( pLayout, rPosition );
// Set the layout of the decorated control as well
m_rCtrl.setLayout( pLayout, rPosition );
}
const Position *CtrlResize::getPosition() const
{
return m_rCtrl.getPosition();
}
void CtrlResize::onResize()
{
m_rCtrl.onResize();
}
void CtrlResize::handleEvent( EvtGeneric &rEvent )
{
m_pEvt = &rEvent;
m_fsm.handleTransition( rEvent.getAsString() );
// Transmit the event to the decorated control
// XXX: Is it really a good idea?
m_rCtrl.handleEvent( rEvent );
}
void CtrlResize::changeCursor( WindowManager::Direction_t direction ) const
{
OSFactory *pOsFactory = OSFactory::instance( getIntf() );
if( direction == WindowManager::kResizeSE )
pOsFactory->changeCursor( OSFactory::kResizeNWSE );
else if( direction == WindowManager::kResizeS )
pOsFactory->changeCursor( OSFactory::kResizeNS );
else if( direction == WindowManager::kResizeE )
pOsFactory->changeCursor( OSFactory::kResizeWE );
else if( direction == WindowManager::kNone )
pOsFactory->changeCursor( OSFactory::kDefaultArrow );
}
void CtrlResize::CmdOutStill::execute()
{
m_pParent->changeCursor( m_pParent->m_direction );
}
void CtrlResize::CmdStillOut::execute()
{
m_pParent->changeCursor( WindowManager::kNone );
}
void CtrlResize::CmdStillStill::execute()
{
m_pParent->changeCursor( m_pParent->m_direction );
}
void CtrlResize::CmdStillResize::execute()
{
EvtMouse *pEvtMouse = (EvtMouse*)m_pParent->m_pEvt;
// Set the cursor
m_pParent->changeCursor( m_pParent->m_direction );
m_pParent->m_xPos = pEvtMouse->getXPos();
m_pParent->m_yPos = pEvtMouse->getYPos();
m_pParent->captureMouse();
m_pParent->m_width = m_pParent->m_rLayout.getWidth();
m_pParent->m_height = m_pParent->m_rLayout.getHeight();
m_pParent->m_rWindowManager.startResize( m_pParent->m_rLayout,
m_pParent->m_direction);
}
void CtrlResize::CmdResizeStill::execute()
{
// Set the cursor
m_pParent->changeCursor( m_pParent->m_direction );
m_pParent->releaseMouse();
m_pParent->m_rWindowManager.stopResize();
}
void CtrlResize::CmdResizeResize::execute()
{
EvtMotion *pEvtMotion = (EvtMotion*)m_pParent->m_pEvt;
// Set the cursor
m_pParent->changeCursor( m_pParent->m_direction );
int newWidth = m_pParent->m_width;
newWidth += pEvtMotion->getXPos() - m_pParent->m_xPos;
int newHeight = m_pParent->m_height;
newHeight += pEvtMotion->getYPos() - m_pParent->m_yPos;
// Create a resize command, instead of calling the window manager directly.
// Thanks to this trick, the duplicate resizing commands will be trashed
// in the asynchronous queue, thus making resizing faster
CmdGeneric *pCmd = new CmdResize( m_pParent->getIntf(),
m_pParent->m_rWindowManager,
m_pParent->m_rLayout,
newWidth, newHeight );
// Push the command in the asynchronous command queue
AsyncQueue *pQueue = AsyncQueue::instance( getIntf() );
pQueue->push( CmdGenericPtr( pCmd ) );
}
|
scs/uclinux
|
user/blkfin-apps/vlc/vlc-0.8.6b/modules/gui/skins2/controls/ctrl_resize.cpp
|
C++
|
gpl-2.0
| 6,346
|
<?php
/**
* @version 0.0.6
* @package com_jazz_mastering
* @copyright Copyright (C) 2012. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Artur Pañach Bargalló <arturictus@gmail.com> - http://
*/
// no direct access
defined('_JEXEC') or die;
?>
<?php if($this->items) : ?>
<div class="items">
<ul class="items_list">
<?php foreach ($this->items as $item) :?>
<li><a href="<?php echo JRoute::_('index.php?option=com_jazz_mastering&view=compinglick&id=' . (int)$item->id); ?>"><?php echo $item->id; ?></a></li>
<?php endforeach; ?>
</ul>
</div>
<div class="pagination">
<p class="counter">
<?php echo $this->pagination->getPagesCounter(); ?>
</p>
<?php echo $this->pagination->getPagesLinks(); ?>
</div>
<?php if(JFactory::getUser()->authorise('core.create', 'com_jazz_mastering.compinglick')): ?>
<a href="<?php echo JRoute::_('index.php?option=com_jazz_mastering&task=compinglick.edit&id=0'); ?>">Add</a>
<?php endif; ?>
<?php else: ?>
There are no items in the list
<?php endif; ?>
|
lion01/weprob
|
components/com_jazz_mastering/views/compinglicks/tmpl/default.php
|
PHP
|
gpl-2.0
| 1,208
|
//
// Created by 欧阳建华 on 2017/8/11.
//
#ifndef SE_THREAD_POOL_H
#define SE_THREAD_POOL_H
#include <se/thread/thread.h>
#include <se/thread/mutex.h>
#include <se/thread/condition.h>
#include <vector>
#include <queue>
#include <functional>
namespace se {
namespace thread {
typedef std::function<void()> Task;
class ThreadPool: public Runnable
{
public:
explicit ThreadPool(int max_thread_count = 4);
void push(const Task task);
void shutdown();
~ThreadPool();
protected:
virtual void run();
private:
void createNewWorkThread();
private:
bool running;
int maxThreadCount;
int freeThreadCount;
int currentThreadCount;
std::vector<Thread *> threadList;
std::queue<Task> taskList;
Mutex mutex;
Condition notEmpty;
};
}
}
#endif //SE_THREAD_POOL_H
|
GitOyoung/SE
|
include/se/thread/thread_pool.h
|
C
|
gpl-2.0
| 917
|
using System;
using System.Collections.Generic;
using Server.Commands;
using Server.Network;
using Server.Targeting;
namespace Server.Items
{
public abstract class BaseDoor : Item, ILockable, ITelekinesisable
{
private bool m_Open, m_Locked;
private int m_OpenedID, m_OpenedSound;
private int m_ClosedID, m_ClosedSound;
private Point3D m_Offset;
private BaseDoor m_Link;
private uint m_KeyValue;
private Timer m_Timer;
private static Point3D[] m_Offsets = new Point3D[]
{
new Point3D(-1, 1, 0 ),
new Point3D( 1, 1, 0 ),
new Point3D(-1, 0, 0 ),
new Point3D( 1,-1, 0 ),
new Point3D( 1, 1, 0 ),
new Point3D( 1,-1, 0 ),
new Point3D( 0, 0, 0 ),
new Point3D( 0,-1, 0 ),
new Point3D( 0, 0, 0 ),
new Point3D( 0, 0, 0 ),
new Point3D( 0, 0, 0 ),
new Point3D( 0, 0, 0 )
};
// Called by RunUO
public static void Initialize()
{
EventSink.OpenDoorMacroUsed += new OpenDoorMacroEventHandler( EventSink_OpenDoorMacroUsed );
CommandSystem.Register( "Link", AccessLevel.GameMaster, new CommandEventHandler( Link_OnCommand ) );
CommandSystem.Register( "ChainLink", AccessLevel.GameMaster, new CommandEventHandler( ChainLink_OnCommand ) );
}
[Usage( "Link" )]
[Description( "Links two targeted doors together." )]
private static void Link_OnCommand( CommandEventArgs e )
{
e.Mobile.BeginTarget( -1, false, TargetFlags.None, new TargetCallback( Link_OnFirstTarget ) );
e.Mobile.SendMessage( "Target the first door to link." );
}
private static void Link_OnFirstTarget( Mobile from, object targeted )
{
BaseDoor door = targeted as BaseDoor;
if ( door == null )
{
from.BeginTarget( -1, false, TargetFlags.None, new TargetCallback( Link_OnFirstTarget ) );
from.SendMessage( "That is not a door. Try again." );
}
else
{
from.BeginTarget( -1, false, TargetFlags.None, new TargetStateCallback( Link_OnSecondTarget ), door );
from.SendMessage( "Target the second door to link." );
}
}
private static void Link_OnSecondTarget( Mobile from, object targeted, object state )
{
BaseDoor first = (BaseDoor)state;
BaseDoor second = targeted as BaseDoor;
if ( second == null )
{
from.BeginTarget( -1, false, TargetFlags.None, new TargetStateCallback( Link_OnSecondTarget ), first );
from.SendMessage( "That is not a door. Try again." );
}
else
{
first.Link = second;
second.Link = first;
from.SendMessage( "The doors have been linked." );
}
}
[Usage( "ChainLink" )]
[Description( "Chain-links two or more targeted doors together." )]
private static void ChainLink_OnCommand( CommandEventArgs e )
{
e.Mobile.BeginTarget( -1, false, TargetFlags.None, new TargetStateCallback( ChainLink_OnTarget ), new List<BaseDoor>() );
e.Mobile.SendMessage( "Target the first of a sequence of doors to link." );
}
private static void ChainLink_OnTarget( Mobile from, object targeted, object state )
{
BaseDoor door = targeted as BaseDoor;
if ( door == null )
{
from.BeginTarget( -1, false, TargetFlags.None, new TargetStateCallback( ChainLink_OnTarget ), state );
from.SendMessage( "That is not a door. Try again." );
}
else
{
List<BaseDoor> list = (List<BaseDoor>)state;
if ( list.Count > 0 && list[0] == door )
{
if ( list.Count >= 2 )
{
for ( int i = 0; i < list.Count; ++i )
list[i].Link = list[(i + 1) % list.Count];
from.SendMessage( "The chain of doors have been linked." );
}
else
{
from.BeginTarget( -1, false, TargetFlags.None, new TargetStateCallback( ChainLink_OnTarget ), state );
from.SendMessage( "You have not yet targeted two unique doors. Target the second door to link." );
}
}
else if ( list.Contains( door ) )
{
from.BeginTarget( -1, false, TargetFlags.None, new TargetStateCallback( ChainLink_OnTarget ), state );
from.SendMessage( "You have already targeted that door. Target another door, or retarget the first door to complete the chain." );
}
else
{
list.Add( door );
from.BeginTarget( -1, false, TargetFlags.None, new TargetStateCallback( ChainLink_OnTarget ), state );
if ( list.Count == 1 )
from.SendMessage( "Target the second door to link." );
else
from.SendMessage( "Target another door to link. To complete the chain, retarget the first door." );
}
}
}
private static void EventSink_OpenDoorMacroUsed( OpenDoorMacroEventArgs args )
{
Mobile m = args.Mobile;
if ( m.Map != null )
{
int x = m.X, y = m.Y;
switch ( m.Direction & Direction.Mask )
{
case Direction.North: --y; break;
case Direction.Right: ++x; --y; break;
case Direction.East: ++x; break;
case Direction.Down: ++x; ++y; break;
case Direction.South: ++y; break;
case Direction.Left: --x; ++y; break;
case Direction.West: --x; break;
case Direction.Up: --x; --y; break;
}
Sector sector = m.Map.GetSector( x, y );
foreach ( Item item in sector.Items )
{
if ( item.Location.X == x && item.Location.Y == y && (item.Z + item.ItemData.Height) > m.Z && (m.Z + 16) > item.Z && item is BaseDoor && m.CanSee( item ) && m.InLOS( item ) )
{
if ( m.CheckAlive() )
{
m.SendLocalizedMessage( 500024 ); // Opening door...
item.OnDoubleClick( m );
}
break;
}
}
}
}
public static Point3D GetOffset( DoorFacing facing )
{
return m_Offsets[(int)facing];
}
private class InternalTimer : Timer
{
private BaseDoor m_Door;
public InternalTimer( BaseDoor door ) : base( TimeSpan.FromSeconds( 20.0 ), TimeSpan.FromSeconds( 10.0 ) )
{
Priority = TimerPriority.OneSecond;
m_Door = door;
}
protected override void OnTick()
{
if ( m_Door.Open && m_Door.IsFreeToClose() )
m_Door.Open = false;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public bool Locked
{
get
{
return m_Locked;
}
set
{
m_Locked = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public uint KeyValue
{
get
{
return m_KeyValue;
}
set
{
m_KeyValue = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public bool Open
{
get
{
return m_Open;
}
set
{
if ( m_Open != value )
{
m_Open = value;
ItemID = m_Open ? m_OpenedID : m_ClosedID;
if ( m_Open )
Location = new Point3D( X + m_Offset.X, Y + m_Offset.Y, Z + m_Offset.Z );
else
Location = new Point3D( X - m_Offset.X, Y - m_Offset.Y, Z - m_Offset.Z );
Effects.PlaySound( this, Map, m_Open ? m_OpenedSound : m_ClosedSound );
if ( m_Open )
m_Timer.Start();
else
m_Timer.Stop();
}
}
}
public bool CanClose()
{
if ( !m_Open )
return true;
Map map = Map;
if ( map == null )
return false;
Point3D p = new Point3D( X - m_Offset.X, Y - m_Offset.Y, Z - m_Offset.Z );
return CheckFit( map, p, 16 );
}
private bool CheckFit( Map map, Point3D p, int height )
{
if ( map == Map.Internal )
return false;
int x = p.X;
int y = p.Y;
int z = p.Z;
Sector sector = map.GetSector( x, y );
List<Item> items = sector.Items;
List<Mobile> mobs = sector.Mobiles;
for ( int i = 0; i < items.Count; ++i )
{
Item item = items[i];
if ( item.ItemID < 0x4000 && item.AtWorldPoint( x, y ) && !(item is BaseDoor) )
{
ItemData id = item.ItemData;
bool surface = id.Surface;
bool impassable = id.Impassable;
if ( (surface || impassable) && (item.Z + id.CalcHeight) > z && (z + height) > item.Z )
return false;
}
}
for ( int i = 0; i < mobs.Count; ++i )
{
Mobile m = mobs[i];
if ( m.Location.X == x && m.Location.Y == y )
{
if ( m.Hidden && m.AccessLevel > AccessLevel.Player )
continue;
if ( !m.Alive )
continue;
if ( (m.Z + 16) > z && (z + height) > m.Z )
return false;
}
}
return true;
}
[CommandProperty( AccessLevel.GameMaster )]
public int OpenedID
{
get
{
return m_OpenedID;
}
set
{
m_OpenedID = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int ClosedID
{
get
{
return m_ClosedID;
}
set
{
m_ClosedID = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int OpenedSound
{
get
{
return m_OpenedSound;
}
set
{
m_OpenedSound = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int ClosedSound
{
get
{
return m_ClosedSound;
}
set
{
m_ClosedSound = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public Point3D Offset
{
get
{
return m_Offset;
}
set
{
m_Offset = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public BaseDoor Link
{
get
{
if ( m_Link != null && m_Link.Deleted )
m_Link = null;
return m_Link;
}
set
{
m_Link = value;
}
}
public virtual bool UseChainedFunctionality{ get{ return false; } }
public List<BaseDoor> GetChain()
{
List<BaseDoor> list = new List<BaseDoor>();
BaseDoor c = this;
do
{
list.Add( c );
c = c.Link;
} while ( c != null && !list.Contains( c ) );
return list;
}
public bool IsFreeToClose()
{
if ( !UseChainedFunctionality )
return CanClose();
List<BaseDoor> list = GetChain();
bool freeToClose = true;
for ( int i = 0; freeToClose && i < list.Count; ++i )
freeToClose = list[i].CanClose();
return freeToClose;
}
public void OnTelekinesis( Mobile from )
{
Effects.SendLocationParticles( EffectItem.Create( Location, Map, EffectItem.DefaultDuration ), 0x376A, 9, 32, 5022 );
Effects.PlaySound( Location, Map, 0x1F5 );
Use( from );
}
public virtual bool IsInside( Mobile from )
{
return false;
}
public virtual bool UseLocks()
{
return true;
}
public virtual void Use( Mobile from )
{
if ( m_Locked && !m_Open && UseLocks() )
{
if ( from.AccessLevel >= AccessLevel.GameMaster )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 502502 ); // That is locked, but you open it with your godly powers.
//from.Send( new MessageLocalized( Serial, ItemID, MessageType.Regular, 0x3B2, 3, 502502, "", "" ) ); // That is locked, but you open it with your godly powers.
}
else if ( Key.ContainsKey( from.Backpack, this.KeyValue ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 501282 ); // You quickly unlock, open, and relock the door
}
else if ( IsInside( from ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 501280 ); // That is locked, but is usable from the inside.
}
else
{
if ( Hue == 0x44E && Map == Map.Malas ) // doom door into healer room in doom
this.SendLocalizedMessageTo( from, 1060014 ); // Only the dead may pass.
else
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 502503 ); // That is locked.
return;
}
}
if ( m_Open && !IsFreeToClose() )
return;
if ( m_Open )
OnClosed( from );
else
OnOpened( from );
if ( UseChainedFunctionality )
{
bool open = !m_Open;
List<BaseDoor> list = GetChain();
for ( int i = 0; i < list.Count; ++i )
list[i].Open = open;
}
else
{
Open = !m_Open;
BaseDoor link = this.Link;
if ( m_Open && link != null && !link.Open )
link.Open = true;
}
}
public virtual void OnOpened( Mobile from )
{
}
public virtual void OnClosed( Mobile from )
{
}
public override void OnDoubleClick( Mobile from )
{
if ( from.AccessLevel == AccessLevel.Player && (/*!from.InLOS( this ) || */!from.InRange( GetWorldLocation(), 2 )) )
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
else
Use( from );
}
public BaseDoor( int closedID, int openedID, int openedSound, int closedSound, Point3D offset ) : base( closedID )
{
m_OpenedID = openedID;
m_ClosedID = closedID;
m_OpenedSound = openedSound;
m_ClosedSound = closedSound;
m_Offset = offset;
m_Timer = new InternalTimer( this );
Movable = false;
}
public BaseDoor( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( m_KeyValue );
writer.Write( m_Open );
writer.Write( m_Locked );
writer.Write( m_OpenedID );
writer.Write( m_ClosedID );
writer.Write( m_OpenedSound );
writer.Write( m_ClosedSound );
writer.Write( m_Offset );
writer.Write( m_Link );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_KeyValue = reader.ReadUInt();
m_Open = reader.ReadBool();
m_Locked = reader.ReadBool();
m_OpenedID = reader.ReadInt();
m_ClosedID = reader.ReadInt();
m_OpenedSound = reader.ReadInt();
m_ClosedSound = reader.ReadInt();
m_Offset = reader.ReadPoint3D();
m_Link = reader.ReadItem() as BaseDoor;
m_Timer = new InternalTimer( this );
if ( m_Open )
m_Timer.Start();
break;
}
}
}
}
}
|
alucardxlx/kaltar
|
Scripts/Items/Construction/Doors/BaseDoor.cs
|
C#
|
gpl-2.0
| 14,062
|
/*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "PVRDatabase.h"
#include "dbwrappers/dataset.h"
#include "settings/AdvancedSettings.h"
#include "settings/VideoSettings.h"
#include "settings/Settings.h"
#include "utils/log.h"
#include "utils/StringUtils.h"
#include "PVRManager.h"
#include "channels/PVRChannelGroupsContainer.h"
#include "channels/PVRChannelGroupInternal.h"
#include "addons/PVRClient.h"
using namespace dbiplus;
using namespace PVR;
using namespace ADDON;
#define PVRDB_DEBUGGING 0
bool CPVRDatabase::Open()
{
return CDatabase::Open(g_advancedSettings.m_databaseTV);
}
void CPVRDatabase::CreateTables()
{
CLog::Log(LOGINFO, "PVR - %s - creating tables", __FUNCTION__);
CLog::Log(LOGDEBUG, "PVR - %s - creating table 'clients'", __FUNCTION__);
m_pDS->exec(
"CREATE TABLE clients ("
"idClient integer primary key, "
"sName varchar(64), "
"sUid varchar(32)"
")"
);
CLog::Log(LOGDEBUG, "PVR - %s - creating table 'channels'", __FUNCTION__);
m_pDS->exec(
"CREATE TABLE channels ("
"idChannel integer primary key, "
"iUniqueId integer, "
"bIsRadio bool, "
"bIsHidden bool, "
"bIsUserSetIcon bool, "
"bIsUserSetName bool, "
"bIsLocked bool, "
"sIconPath varchar(255), "
"sChannelName varchar(64), "
"bIsVirtual bool, "
"bEPGEnabled bool, "
"sEPGScraper varchar(32), "
"iLastWatched integer,"
// TODO use mapping table
"iClientId integer, "
"iClientChannelNumber integer, "
"sInputFormat varchar(32), "
"sStreamURL varchar(255), "
"iEncryptionSystem integer, "
"idEpg integer"
")"
);
// TODO use a mapping table so multiple backends per channel can be implemented
// CLog::Log(LOGDEBUG, "PVR - %s - creating table 'map_channels_clients'", __FUNCTION__);
// m_pDS->exec(
// "CREATE TABLE map_channels_clients ("
// "idChannel integer primary key, "
// "idClient integer, "
// "iClientChannelNumber integer,"
// "sInputFormat string,"
// "sStreamURL string,"
// "iEncryptionSystem integer"
// ");"
// );
// m_pDS->exec("CREATE UNIQUE INDEX idx_idChannel_idClient on map_channels_clients(idChannel, idClient);");
CLog::Log(LOGDEBUG, "PVR - %s - creating table 'channelgroups'", __FUNCTION__);
m_pDS->exec(
"CREATE TABLE channelgroups ("
"idGroup integer primary key,"
"bIsRadio bool, "
"iGroupType integer, "
"sName varchar(64), "
"iLastWatched integer"
")"
);
CLog::Log(LOGDEBUG, "PVR - %s - creating table 'map_channelgroups_channels'", __FUNCTION__);
m_pDS->exec(
"CREATE TABLE map_channelgroups_channels ("
"idChannel integer, "
"idGroup integer, "
"iChannelNumber integer"
")"
);
// disable all PVR add-on when started the first time
ADDON::VECADDONS addons;
if (!CAddonMgr::Get().GetAddons(ADDON_PVRDLL, addons, true))
CLog::Log(LOGERROR, "PVR - %s - failed to get add-ons from the add-on manager", __FUNCTION__);
else
{
for (IVECADDONS it = addons.begin(); it != addons.end(); it++)
CAddonMgr::Get().DisableAddon(it->get()->ID());
}
}
void CPVRDatabase::CreateAnalytics()
{
CLog::Log(LOGINFO, "%s - creating indices", __FUNCTION__);
m_pDS->exec("CREATE UNIQUE INDEX idx_channels_iClientId_iUniqueId on channels(iClientId, iUniqueId);");
m_pDS->exec("CREATE INDEX idx_channelgroups_bIsRadio on channelgroups(bIsRadio);");
m_pDS->exec("CREATE UNIQUE INDEX idx_idGroup_idChannel on map_channelgroups_channels(idGroup, idChannel);");
}
void CPVRDatabase::UpdateTables(int iVersion)
{
if (iVersion < 13)
m_pDS->exec("ALTER TABLE channels ADD idEpg integer;");
if (iVersion < 19)
{
// bit of a hack, but we need to keep the version/contents of the non-pvr databases the same to allow clean upgrades
ADDON::VECADDONS addons;
if (!CAddonMgr::Get().GetAddons(ADDON_PVRDLL, addons, true))
CLog::Log(LOGERROR, "PVR - %s - failed to get add-ons from the add-on manager", __FUNCTION__);
else
{
CAddonDatabase database;
database.Open();
for (IVECADDONS it = addons.begin(); it != addons.end(); it++)
{
if (!database.IsSystemPVRAddonEnabled(it->get()->ID()))
CAddonMgr::Get().DisableAddon(it->get()->ID());
}
database.Close();
}
}
if (iVersion < 20)
m_pDS->exec("ALTER TABLE channels ADD bIsUserSetIcon bool");
if (iVersion < 21)
m_pDS->exec("ALTER TABLE channelgroups ADD iGroupType integer");
if (iVersion < 22)
m_pDS->exec("ALTER TABLE channels ADD bIsLocked bool");
if (iVersion < 23)
m_pDS->exec("ALTER TABLE channelgroups ADD iLastWatched integer");
if (iVersion < 24)
m_pDS->exec("ALTER TABLE channels ADD bIsUserSetName bool");
if (iVersion < 25)
m_pDS->exec("DROP TABLE IF EXISTS channelsettings");
}
int CPVRDatabase::GetLastChannelId(void)
{
int iReturn(0);
std::string strQuery = PrepareSQL("SELECT MAX(idChannel) as iMaxChannel FROM channels");
if (ResultQuery(strQuery))
{
try
{
if (!m_pDS->eof())
iReturn = m_pDS->fv("iMaxChannel").get_asInt();
m_pDS->close();
}
catch (...) {}
}
return iReturn;
}
/********** Channel methods **********/
bool CPVRDatabase::DeleteChannels(void)
{
CLog::Log(LOGDEBUG, "PVR - %s - deleting all channels from the database", __FUNCTION__);
return DeleteValues("channels");
}
bool CPVRDatabase::DeleteClientChannels(const CPVRClient &client)
{
/* invalid client Id */
if (client.GetID() <= 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid client id: %i", __FUNCTION__, client.GetID());
return false;
}
CLog::Log(LOGDEBUG, "PVR - %s - deleting all channels from client '%i' from the database", __FUNCTION__, client.GetID());
Filter filter;
filter.AppendWhere(PrepareSQL("iClientId = %u", client.GetID()));
return DeleteValues("channels", filter);
}
bool CPVRDatabase::Delete(const CPVRChannel &channel)
{
/* invalid channel */
if (channel.ChannelID() <= 0)
return false;
CLog::Log(LOGDEBUG, "PVR - %s - deleting channel '%s' from the database", __FUNCTION__, channel.ChannelName().c_str());
Filter filter;
filter.AppendWhere(PrepareSQL("idChannel = %u", channel.ChannelID()));
return DeleteValues("channels", filter);
}
int CPVRDatabase::Get(CPVRChannelGroupInternal &results)
{
int iReturn(0);
std::string strQuery = PrepareSQL("SELECT channels.idChannel, channels.iUniqueId, channels.bIsRadio, channels.bIsHidden, channels.bIsUserSetIcon, channels.bIsUserSetName, "
"channels.sIconPath, channels.sChannelName, channels.bIsVirtual, channels.bEPGEnabled, channels.sEPGScraper, channels.iLastWatched, channels.iClientId, channels.bIsLocked, "
"channels.iClientChannelNumber, channels.sInputFormat, channels.sInputFormat, channels.sStreamURL, channels.iEncryptionSystem, map_channelgroups_channels.iChannelNumber, channels.idEpg "
"FROM map_channelgroups_channels "
"LEFT JOIN channels ON channels.idChannel = map_channelgroups_channels.idChannel "
"WHERE map_channelgroups_channels.idGroup = %u", results.IsRadio() ? XBMC_INTERNAL_GROUP_RADIO : XBMC_INTERNAL_GROUP_TV);
if (ResultQuery(strQuery))
{
try
{
bool bIgnoreEpgDB = CSettings::Get().GetBool("epg.ignoredbforclient");
while (!m_pDS->eof())
{
CPVRChannelPtr channel = CPVRChannelPtr(new CPVRChannel());
channel->m_iChannelId = m_pDS->fv("idChannel").get_asInt();
channel->m_iUniqueId = m_pDS->fv("iUniqueId").get_asInt();
channel->m_bIsRadio = m_pDS->fv("bIsRadio").get_asBool();
channel->m_bIsHidden = m_pDS->fv("bIsHidden").get_asBool();
channel->m_bIsUserSetIcon = m_pDS->fv("bIsUserSetIcon").get_asBool();
channel->m_bIsUserSetName = m_pDS->fv("bIsUserSetName").get_asBool();
channel->m_bIsLocked = m_pDS->fv("bIsLocked").get_asBool();
channel->m_strIconPath = m_pDS->fv("sIconPath").get_asString();
channel->m_strChannelName = m_pDS->fv("sChannelName").get_asString();
channel->m_bIsVirtual = m_pDS->fv("bIsVirtual").get_asBool();
channel->m_bEPGEnabled = m_pDS->fv("bEPGEnabled").get_asBool();
channel->m_strEPGScraper = m_pDS->fv("sEPGScraper").get_asString();
channel->m_iLastWatched = (time_t) m_pDS->fv("iLastWatched").get_asInt();
channel->m_iClientId = m_pDS->fv("iClientId").get_asInt();
channel->m_iClientChannelNumber = m_pDS->fv("iClientChannelNumber").get_asInt();
channel->m_strInputFormat = m_pDS->fv("sInputFormat").get_asString();
channel->m_strStreamURL = m_pDS->fv("sStreamURL").get_asString();
channel->m_iClientEncryptionSystem = m_pDS->fv("iEncryptionSystem").get_asInt();
if (bIgnoreEpgDB)
channel->m_iEpgId = -1;
else
channel->m_iEpgId = m_pDS->fv("idEpg").get_asInt();
channel->UpdateEncryptionName();
#if PVRDB_DEBUGGING
CLog::Log(LOGDEBUG, "PVR - %s - channel '%s' loaded from the database", __FUNCTION__, channel->m_strChannelName.c_str());
#endif
PVRChannelGroupMember newMember = { channel, (unsigned int)m_pDS->fv("iChannelNumber").get_asInt() };
results.m_members.push_back(newMember);
m_pDS->next();
++iReturn;
}
m_pDS->close();
}
catch (...)
{
CLog::Log(LOGERROR, "PVR - %s - couldn't load channels from the database", __FUNCTION__);
}
}
else
{
CLog::Log(LOGERROR, "PVR - %s - query failed", __FUNCTION__);
}
m_pDS->close();
return iReturn;
}
/********** Channel group methods **********/
bool CPVRDatabase::RemoveChannelsFromGroup(const CPVRChannelGroup &group)
{
Filter filter;
filter.AppendWhere(PrepareSQL("idGroup = %u", group.GroupID()));
return DeleteValues("map_channelgroups_channels", filter);
}
bool CPVRDatabase::GetCurrentGroupMembers(const CPVRChannelGroup &group, std::vector<int> &members)
{
bool bReturn(false);
/* invalid group id */
if (group.GroupID() <= 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid group id: %d", __FUNCTION__, group.GroupID());
return false;
}
std::string strCurrentMembersQuery = PrepareSQL("SELECT idChannel FROM map_channelgroups_channels WHERE idGroup = %u", group.GroupID());
if (ResultQuery(strCurrentMembersQuery))
{
try
{
while (!m_pDS->eof())
{
members.push_back(m_pDS->fv("idChannel").get_asInt());
m_pDS->next();
}
m_pDS->close();
bReturn = true;
}
catch (...)
{
CLog::Log(LOGERROR, "PVR - %s - couldn't load channels from the database", __FUNCTION__);
}
}
else
{
CLog::Log(LOGERROR, "PVR - %s - query failed", __FUNCTION__);
}
return bReturn;
}
bool CPVRDatabase::DeleteChannelsFromGroup(const CPVRChannelGroup &group)
{
/* invalid group id */
if (group.GroupID() <= 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid group id: %d", __FUNCTION__, group.GroupID());
return false;
}
Filter filter;
filter.AppendWhere(PrepareSQL("idGroup = %u", group.GroupID()));
return DeleteValues("map_channelgroups_channels", filter);
}
bool CPVRDatabase::DeleteChannelsFromGroup(const CPVRChannelGroup &group, const std::vector<int> &channelsToDelete)
{
bool bDelete(true);
unsigned int iDeletedChannels(0);
/* invalid group id */
if (group.GroupID() <= 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid group id: %d", __FUNCTION__, group.GroupID());
return false;
}
while (iDeletedChannels < channelsToDelete.size())
{
std::string strChannelsToDelete;
for (unsigned int iChannelPtr = 0; iChannelPtr + iDeletedChannels < channelsToDelete.size() && iChannelPtr < 50; iChannelPtr++)
strChannelsToDelete += StringUtils::Format(", %d", channelsToDelete.at(iDeletedChannels + iChannelPtr));
if (!strChannelsToDelete.empty())
{
strChannelsToDelete.erase(0, 2);
Filter filter;
filter.AppendWhere(PrepareSQL("idGroup = %u", group.GroupID()));
filter.AppendWhere(PrepareSQL("idChannel IN (%s)", strChannelsToDelete.c_str()));
bDelete = DeleteValues("map_channelgroups_channels", filter) && bDelete;
}
iDeletedChannels += 50;
}
return bDelete;
}
bool CPVRDatabase::RemoveStaleChannelsFromGroup(const CPVRChannelGroup &group)
{
bool bDelete(true);
/* invalid group id */
if (group.GroupID() <= 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid group id: %d", __FUNCTION__, group.GroupID());
return false;
}
if (!group.IsInternalGroup())
{
/* First remove channels that don't exist in the main channels table */
// XXX work around for frodo: fix this up so it uses one query for all db types
// mysql doesn't support subqueries when deleting and sqlite doesn't support joins when deleting
if (g_advancedSettings.m_databaseTV.type.Equals("mysql"))
{
std::string strQuery = PrepareSQL("DELETE m FROM map_channelgroups_channels m LEFT JOIN channels c ON (c.idChannel = m.idChannel) WHERE c.idChannel IS NULL");
bDelete = ExecuteQuery(strQuery);
}
else
{
Filter filter;
filter.AppendWhere("idChannel IN (SELECT m.idChannel FROM map_channelgroups_channels m LEFT JOIN channels on m.idChannel = channels.idChannel WHERE channels.idChannel IS NULL)");
bDelete = DeleteValues("map_channelgroups_channels", filter);
}
}
if (group.m_members.size() > 0)
{
std::vector<int> currentMembers;
if (GetCurrentGroupMembers(group, currentMembers))
{
std::vector<int> channelsToDelete;
for (unsigned int iChannelPtr = 0; iChannelPtr < currentMembers.size(); iChannelPtr++)
{
if (!group.IsGroupMember(currentMembers.at(iChannelPtr)))
channelsToDelete.push_back(currentMembers.at(iChannelPtr));
}
bDelete = DeleteChannelsFromGroup(group, channelsToDelete) && bDelete;
}
}
else
{
Filter filter;
filter.AppendWhere(PrepareSQL("idGroup = %u", group.GroupID()));
bDelete = DeleteValues("map_channelgroups_channels", filter) && bDelete;
}
return bDelete;
}
bool CPVRDatabase::DeleteChannelGroups(void)
{
CLog::Log(LOGDEBUG, "PVR - %s - deleting all channel groups from the database", __FUNCTION__);
return DeleteValues("channelgroups") &&
DeleteValues("map_channelgroups_channels");
}
bool CPVRDatabase::Delete(const CPVRChannelGroup &group)
{
/* invalid group id */
if (group.GroupID() <= 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid group id: %d", __FUNCTION__, group.GroupID());
return false;
}
Filter filter;
filter.AppendWhere(PrepareSQL("idGroup = %u", group.GroupID()));
filter.AppendWhere(PrepareSQL("bIsRadio = %u", group.IsRadio()));
return RemoveChannelsFromGroup(group) &&
DeleteValues("channelgroups", filter);
}
bool CPVRDatabase::Get(CPVRChannelGroups &results)
{
bool bReturn = false;
std::string strQuery = PrepareSQL("SELECT * from channelgroups WHERE bIsRadio = %u", results.IsRadio());
if (ResultQuery(strQuery))
{
try
{
while (!m_pDS->eof())
{
CPVRChannelGroup data(m_pDS->fv("bIsRadio").get_asBool(), m_pDS->fv("idGroup").get_asInt(), m_pDS->fv("sName").get_asString());
data.SetGroupType(m_pDS->fv("iGroupType").get_asInt());
data.SetLastWatched((time_t) m_pDS->fv("iLastWatched").get_asInt());
results.Update(data);
CLog::Log(LOGDEBUG, "PVR - %s - group '%s' loaded from the database", __FUNCTION__, data.GroupName().c_str());
m_pDS->next();
}
m_pDS->close();
bReturn = true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s - couldn't load channels from the database", __FUNCTION__);
}
}
return bReturn;
}
int CPVRDatabase::Get(CPVRChannelGroup &group)
{
int iReturn = -1;
/* invalid group id */
if (group.GroupID() < 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid group id: %d", __FUNCTION__, group.GroupID());
return -1;
}
std::string strQuery = PrepareSQL("SELECT idChannel, iChannelNumber FROM map_channelgroups_channels WHERE idGroup = %u ORDER BY iChannelNumber", group.GroupID());
if (ResultQuery(strQuery))
{
iReturn = 0;
try
{
while (!m_pDS->eof())
{
int iChannelId = m_pDS->fv("idChannel").get_asInt();
int iChannelNumber = m_pDS->fv("iChannelNumber").get_asInt();
CPVRChannelPtr channel = g_PVRChannelGroups->GetGroupAll(group.IsRadio())->GetByChannelID(iChannelId);
if (channel)
{
#if PVRDB_DEBUGGING
CLog::Log(LOGDEBUG, "PVR - %s - channel '%s' loaded from the database", __FUNCTION__, channel->m_strChannelName.c_str());
#endif
PVRChannelGroupMember newMember = { channel, (unsigned int)iChannelNumber };
group.m_members.push_back(newMember);
iReturn++;
}
else
{
// remove a channel that doesn't exist (anymore) from the table
Filter filter;
filter.AppendWhere(PrepareSQL("idGroup = %u", group.GroupID()));
filter.AppendWhere(PrepareSQL("idChannel = %u", iChannelId));
DeleteValues("map_channelgroups_channels", filter);
}
m_pDS->next();
}
m_pDS->close();
}
catch(...)
{
CLog::Log(LOGERROR, "PVR - %s - failed to get channels", __FUNCTION__);
}
}
if (iReturn > 0)
group.SortByChannelNumber();
return iReturn;
}
bool CPVRDatabase::PersistChannels(CPVRChannelGroup &group)
{
bool bReturn(true);
int iLastChannel(0);
/* we can only safely get this from a local db */
if (m_sqlite)
iLastChannel = GetLastChannelId();
for (unsigned int iChannelPtr = 0; iChannelPtr < group.m_members.size(); iChannelPtr++)
{
PVRChannelGroupMember member = group.m_members.at(iChannelPtr);
if (member.channel->IsChanged() || member.channel->IsNew())
{
if (m_sqlite && member.channel->IsNew())
member.channel->SetChannelID(++iLastChannel);
bReturn &= Persist(*member.channel, m_sqlite || !member.channel->IsNew());
}
}
bReturn &= CommitInsertQueries();
return bReturn;
}
bool CPVRDatabase::PersistGroupMembers(CPVRChannelGroup &group)
{
bool bReturn = true;
bool bRemoveChannels = true;
std::string strQuery;
CSingleLock lock(group.m_critSection);
if (group.m_members.size() > 0)
{
for (unsigned int iChannelPtr = 0; iChannelPtr < group.m_members.size(); iChannelPtr++)
{
PVRChannelGroupMember member = group.m_members.at(iChannelPtr);
std::string strWhereClause = PrepareSQL("idChannel = %u AND idGroup = %u AND iChannelNumber = %u",
member.channel->ChannelID(), group.GroupID(), member.iChannelNumber);
std::string strValue = GetSingleValue("map_channelgroups_channels", "idChannel", strWhereClause);
if (strValue.empty())
{
strQuery = PrepareSQL("REPLACE INTO map_channelgroups_channels ("
"idGroup, idChannel, iChannelNumber) "
"VALUES (%i, %i, %i);",
group.GroupID(), member.channel->ChannelID(), member.iChannelNumber);
QueueInsertQuery(strQuery);
}
}
lock.Leave();
bReturn = CommitInsertQueries();
bRemoveChannels = RemoveStaleChannelsFromGroup(group);
}
return bReturn && bRemoveChannels;
}
/********** Client methods **********/
bool CPVRDatabase::DeleteClients()
{
CLog::Log(LOGDEBUG, "PVR - %s - deleting all clients from the database", __FUNCTION__);
return DeleteValues("clients");
//TODO && DeleteValues("map_channels_clients");
}
bool CPVRDatabase::Delete(const CPVRClient &client)
{
/* invalid client uid */
if (client.ID().empty())
{
CLog::Log(LOGERROR, "PVR - %s - invalid client uid", __FUNCTION__);
return false;
}
Filter filter;
filter.AppendWhere(PrepareSQL("sUid = '%s'", client.ID().c_str()));
return DeleteValues("clients", filter);
}
int CPVRDatabase::GetClientId(const std::string &strClientUid)
{
std::string strWhereClause = PrepareSQL("sUid = '%s'", strClientUid.c_str());
std::string strValue = GetSingleValue("clients", "idClient", strWhereClause);
if (strValue.empty())
return -1;
return atol(strValue.c_str());
}
bool CPVRDatabase::ResetEPG(void)
{
std::string strQuery = PrepareSQL("UPDATE channels SET idEpg = 0");
return ExecuteQuery(strQuery);
}
bool CPVRDatabase::Persist(CPVRChannelGroup &group)
{
bool bReturn(false);
if (group.GroupName().empty())
{
CLog::Log(LOGERROR, "%s - empty group name", __FUNCTION__);
return bReturn;
}
std::string strQuery;
bReturn = true;
{
CSingleLock lock(group.m_critSection);
/* insert a new entry when this is a new group, or replace the existing one otherwise */
if (group.GroupID() <= 0)
strQuery = PrepareSQL("INSERT INTO channelgroups (bIsRadio, iGroupType, sName, iLastWatched) VALUES (%i, %i, '%s', %u)",
(group.IsRadio() ? 1 :0), group.GroupType(), group.GroupName().c_str(), group.LastWatched());
else
strQuery = PrepareSQL("REPLACE INTO channelgroups (idGroup, bIsRadio, iGroupType, sName, iLastWatched) VALUES (%i, %i, %i, '%s', %u)",
group.GroupID(), (group.IsRadio() ? 1 :0), group.GroupType(), group.GroupName().c_str(), group.LastWatched());
bReturn = ExecuteQuery(strQuery);
/* set the group id if it was <= 0 */
if (bReturn && group.GroupID() <= 0)
group.m_iGroupId = (int) m_pDS->lastinsertid();
}
/* only persist the channel data for the internal groups */
if (group.IsInternalGroup())
bReturn &= PersistChannels(group);
/* persist the group member entries */
if (bReturn)
bReturn = PersistGroupMembers(group);
return bReturn;
}
int CPVRDatabase::Persist(const AddonPtr client)
{
int iReturn(-1);
/* invalid client uid or name */
if (client->Name().empty() || client->ID().empty())
{
CLog::Log(LOGERROR, "PVR - %s - invalid client uid or name", __FUNCTION__);
return iReturn;
}
std::string strQuery = PrepareSQL("REPLACE INTO clients (sName, sUid) VALUES ('%s', '%s');",
client->Name().c_str(), client->ID().c_str());
if (ExecuteQuery(strQuery))
iReturn = (int) m_pDS->lastinsertid();
return iReturn;
}
bool CPVRDatabase::Persist(CPVRChannel &channel, bool bQueueWrite /* = false */)
{
bool bReturn(false);
/* invalid channel */
if (channel.UniqueID() <= 0)
{
CLog::Log(LOGERROR, "PVR - %s - invalid channel uid: %d", __FUNCTION__, channel.UniqueID());
return bReturn;
}
std::string strQuery;
if (channel.ChannelID() <= 0)
{
/* new channel */
strQuery = PrepareSQL("INSERT INTO channels ("
"iUniqueId, bIsRadio, bIsHidden, bIsUserSetIcon, bIsUserSetName, bIsLocked, "
"sIconPath, sChannelName, bIsVirtual, bEPGEnabled, sEPGScraper, iLastWatched, iClientId, "
"iClientChannelNumber, sInputFormat, sStreamURL, iEncryptionSystem, idEpg) "
"VALUES (%i, %i, %i, %i, %i, %i, '%s', '%s', %i, %i, '%s', %u, %i, %i, '%s', '%s', %i, %i)",
channel.UniqueID(), (channel.IsRadio() ? 1 :0), (channel.IsHidden() ? 1 : 0), (channel.IsUserSetIcon() ? 1 : 0), (channel.IsUserSetName() ? 1 : 0), (channel.IsLocked() ? 1 : 0),
channel.IconPath().c_str(), channel.ChannelName().c_str(), (channel.IsVirtual() ? 1 : 0), (channel.EPGEnabled() ? 1 : 0), channel.EPGScraper().c_str(), channel.LastWatched(), channel.ClientID(),
channel.ClientChannelNumber(), channel.InputFormat().c_str(), channel.StreamURL().c_str(), channel.EncryptionSystem(),
channel.EpgID());
}
else
{
/* update channel */
strQuery = PrepareSQL("REPLACE INTO channels ("
"iUniqueId, bIsRadio, bIsHidden, bIsUserSetIcon, bIsUserSetName, bIsLocked, "
"sIconPath, sChannelName, bIsVirtual, bEPGEnabled, sEPGScraper, iLastWatched, iClientId, "
"iClientChannelNumber, sInputFormat, sStreamURL, iEncryptionSystem, idChannel, idEpg) "
"VALUES (%i, %i, %i, %i, %i, %i, '%s', '%s', %i, %i, '%s', %u, %i, %i, '%s', '%s', %i, %i, %i)",
channel.UniqueID(), (channel.IsRadio() ? 1 :0), (channel.IsHidden() ? 1 : 0), (channel.IsUserSetIcon() ? 1 : 0), (channel.IsUserSetName() ? 1 : 0), (channel.IsLocked() ? 1 : 0),
channel.IconPath().c_str(), channel.ChannelName().c_str(), (channel.IsVirtual() ? 1 : 0), (channel.EPGEnabled() ? 1 : 0), channel.EPGScraper().c_str(), channel.LastWatched(), channel.ClientID(),
channel.ClientChannelNumber(), channel.InputFormat().c_str(), channel.StreamURL().c_str(), channel.EncryptionSystem(), channel.ChannelID(),
channel.EpgID());
}
if (bQueueWrite)
{
QueueInsertQuery(strQuery);
bReturn = true;
}
else if (ExecuteQuery(strQuery))
{
CSingleLock lock(channel.m_critSection);
if (channel.m_iChannelId <= 0)
channel.m_iChannelId = (int)m_pDS->lastinsertid();
bReturn = true;
}
return bReturn;
}
|
NaeiKinDus/xbmc
|
xbmc/pvr/PVRDatabase.cpp
|
C++
|
gpl-2.0
| 26,260
|
/*
* Product specific probe and attach routines for:
* 3940, 2940, aic7895, aic7890, aic7880,
* aic7870, aic7860 and aic7850 SCSI controllers
*
* Copyright (c) 1994-2001 Justin T. Gibbs.
* Copyright (c) 2000-2001 Adaptec 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*
* $Id: //depot/aic7xxx/aic7xxx/aic7xxx_pci.c#79 $
*/
#ifdef __linux__
#include "aic7xxx_osm.h"
#include "aic7xxx_inline.h"
#include "aic7xxx_93cx6.h"
#else
#include <dev/aic7xxx/aic7xxx_osm.h>
#include <dev/aic7xxx/aic7xxx_inline.h>
#include <dev/aic7xxx/aic7xxx_93cx6.h>
#endif
#include "aic7xxx_pci.h"
static inline uint64_t
ahc_compose_id(u_int device, u_int vendor, u_int subdevice, u_int subvendor)
{
uint64_t id;
id = subvendor
| (subdevice << 16)
| ((uint64_t)vendor << 32)
| ((uint64_t)device << 48);
return (id);
}
#define AHC_PCI_IOADDR PCIR_MAPS /* I/O Address */
#define AHC_PCI_MEMADDR (PCIR_MAPS + 4) /* Mem I/O Address */
#define DEVID_9005_TYPE(id) ((id) & 0xF)
#define DEVID_9005_TYPE_HBA 0x0 /* Standard Card */
#define DEVID_9005_TYPE_AAA 0x3 /* RAID Card */
#define DEVID_9005_TYPE_SISL 0x5 /* Container ROMB */
#define DEVID_9005_TYPE_MB 0xF /* On Motherboard */
#define DEVID_9005_MAXRATE(id) (((id) & 0x30) >> 4)
#define DEVID_9005_MAXRATE_U160 0x0
#define DEVID_9005_MAXRATE_ULTRA2 0x1
#define DEVID_9005_MAXRATE_ULTRA 0x2
#define DEVID_9005_MAXRATE_FAST 0x3
#define DEVID_9005_MFUNC(id) (((id) & 0x40) >> 6)
#define DEVID_9005_CLASS(id) (((id) & 0xFF00) >> 8)
#define DEVID_9005_CLASS_SPI 0x0 /* Parallel SCSI */
#define SUBID_9005_TYPE(id) ((id) & 0xF)
#define SUBID_9005_TYPE_MB 0xF /* On Motherboard */
#define SUBID_9005_TYPE_CARD 0x0 /* Standard Card */
#define SUBID_9005_TYPE_LCCARD 0x1 /* Low Cost Card */
#define SUBID_9005_TYPE_RAID 0x3 /* Combined with Raid */
#define SUBID_9005_TYPE_KNOWN(id) \
((((id) & 0xF) == SUBID_9005_TYPE_MB) \
|| (((id) & 0xF) == SUBID_9005_TYPE_CARD) \
|| (((id) & 0xF) == SUBID_9005_TYPE_LCCARD) \
|| (((id) & 0xF) == SUBID_9005_TYPE_RAID))
#define SUBID_9005_MAXRATE(id) (((id) & 0x30) >> 4)
#define SUBID_9005_MAXRATE_ULTRA2 0x0
#define SUBID_9005_MAXRATE_ULTRA 0x1
#define SUBID_9005_MAXRATE_U160 0x2
#define SUBID_9005_MAXRATE_RESERVED 0x3
#define SUBID_9005_SEEPTYPE(id) \
((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \
? ((id) & 0xC0) >> 6 \
: ((id) & 0x300) >> 8)
#define SUBID_9005_SEEPTYPE_NONE 0x0
#define SUBID_9005_SEEPTYPE_1K 0x1
#define SUBID_9005_SEEPTYPE_2K_4K 0x2
#define SUBID_9005_SEEPTYPE_RESERVED 0x3
#define SUBID_9005_AUTOTERM(id) \
((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \
? (((id) & 0x400) >> 10) == 0 \
: (((id) & 0x40) >> 6) == 0)
#define SUBID_9005_NUMCHAN(id) \
((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \
? ((id) & 0x300) >> 8 \
: ((id) & 0xC00) >> 10)
#define SUBID_9005_LEGACYCONN(id) \
((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \
? 0 \
: ((id) & 0x80) >> 7)
#define SUBID_9005_MFUNCENB(id) \
((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \
? ((id) & 0x800) >> 11 \
: ((id) & 0x1000) >> 12)
/*
* Informational only. Should use chip register to be
* certain, but may be use in identification strings.
*/
#define SUBID_9005_CARD_SCSIWIDTH_MASK 0x2000
#define SUBID_9005_CARD_PCIWIDTH_MASK 0x4000
#define SUBID_9005_CARD_SEDIFF_MASK 0x8000
static ahc_device_setup_t ahc_aic785X_setup;
static ahc_device_setup_t ahc_aic7860_setup;
static ahc_device_setup_t ahc_apa1480_setup;
static ahc_device_setup_t ahc_aic7870_setup;
static ahc_device_setup_t ahc_aic7870h_setup;
static ahc_device_setup_t ahc_aha394X_setup;
static ahc_device_setup_t ahc_aha394Xh_setup;
static ahc_device_setup_t ahc_aha494X_setup;
static ahc_device_setup_t ahc_aha494Xh_setup;
static ahc_device_setup_t ahc_aha398X_setup;
static ahc_device_setup_t ahc_aic7880_setup;
static ahc_device_setup_t ahc_aic7880h_setup;
static ahc_device_setup_t ahc_aha2940Pro_setup;
static ahc_device_setup_t ahc_aha394XU_setup;
static ahc_device_setup_t ahc_aha394XUh_setup;
static ahc_device_setup_t ahc_aha398XU_setup;
static ahc_device_setup_t ahc_aic7890_setup;
static ahc_device_setup_t ahc_aic7892_setup;
static ahc_device_setup_t ahc_aic7895_setup;
static ahc_device_setup_t ahc_aic7895h_setup;
static ahc_device_setup_t ahc_aic7896_setup;
static ahc_device_setup_t ahc_aic7899_setup;
static ahc_device_setup_t ahc_aha29160C_setup;
static ahc_device_setup_t ahc_raid_setup;
static ahc_device_setup_t ahc_aha394XX_setup;
static ahc_device_setup_t ahc_aha494XX_setup;
static ahc_device_setup_t ahc_aha398XX_setup;
static const struct ahc_pci_identity ahc_pci_ident_table[] = {
/* aic7850 based controllers */
{
ID_AHA_2902_04_10_15_20C_30C,
ID_ALL_MASK,
"Adaptec 2902/04/10/15/20C/30C SCSI adapter",
ahc_aic785X_setup
},
/* aic7860 based controllers */
{
ID_AHA_2930CU,
ID_ALL_MASK,
"Adaptec 2930CU SCSI adapter",
ahc_aic7860_setup
},
{
ID_AHA_1480A & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 1480A Ultra SCSI adapter",
ahc_apa1480_setup
},
{
ID_AHA_2940AU_0 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2940A Ultra SCSI adapter",
ahc_aic7860_setup
},
{
ID_AHA_2940AU_CN & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2940A/CN Ultra SCSI adapter",
ahc_aic7860_setup
},
{
ID_AHA_2930C_VAR & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2930C Ultra SCSI adapter (VAR)",
ahc_aic7860_setup
},
/* aic7870 based controllers */
{
ID_AHA_2940,
ID_ALL_MASK,
"Adaptec 2940 SCSI adapter",
ahc_aic7870_setup
},
{
ID_AHA_3940,
ID_ALL_MASK,
"Adaptec 3940 SCSI adapter",
ahc_aha394X_setup
},
{
ID_AHA_398X,
ID_ALL_MASK,
"Adaptec 398X SCSI RAID adapter",
ahc_aha398X_setup
},
{
ID_AHA_2944,
ID_ALL_MASK,
"Adaptec 2944 SCSI adapter",
ahc_aic7870h_setup
},
{
ID_AHA_3944,
ID_ALL_MASK,
"Adaptec 3944 SCSI adapter",
ahc_aha394Xh_setup
},
{
ID_AHA_4944,
ID_ALL_MASK,
"Adaptec 4944 SCSI adapter",
ahc_aha494Xh_setup
},
/* aic7880 based controllers */
{
ID_AHA_2940U & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2940 Ultra SCSI adapter",
ahc_aic7880_setup
},
{
ID_AHA_3940U & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 3940 Ultra SCSI adapter",
ahc_aha394XU_setup
},
{
ID_AHA_2944U & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2944 Ultra SCSI adapter",
ahc_aic7880h_setup
},
{
ID_AHA_3944U & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 3944 Ultra SCSI adapter",
ahc_aha394XUh_setup
},
{
ID_AHA_398XU & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 398X Ultra SCSI RAID adapter",
ahc_aha398XU_setup
},
{
/*
* XXX Don't know the slot numbers
* so we can't identify channels
*/
ID_AHA_4944U & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 4944 Ultra SCSI adapter",
ahc_aic7880h_setup
},
{
ID_AHA_2930U & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2930 Ultra SCSI adapter",
ahc_aic7880_setup
},
{
ID_AHA_2940U_PRO & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2940 Pro Ultra SCSI adapter",
ahc_aha2940Pro_setup
},
{
ID_AHA_2940U_CN & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec 2940/CN Ultra SCSI adapter",
ahc_aic7880_setup
},
/* Ignore all SISL (AAC on MB) based controllers. */
{
ID_9005_SISL_ID,
ID_9005_SISL_MASK,
NULL,
NULL
},
/* aic7890 based controllers */
{
ID_AHA_2930U2,
ID_ALL_MASK,
"Adaptec 2930 Ultra2 SCSI adapter",
ahc_aic7890_setup
},
{
ID_AHA_2940U2B,
ID_ALL_MASK,
"Adaptec 2940B Ultra2 SCSI adapter",
ahc_aic7890_setup
},
{
ID_AHA_2940U2_OEM,
ID_ALL_MASK,
"Adaptec 2940 Ultra2 SCSI adapter (OEM)",
ahc_aic7890_setup
},
{
ID_AHA_2940U2,
ID_ALL_MASK,
"Adaptec 2940 Ultra2 SCSI adapter",
ahc_aic7890_setup
},
{
ID_AHA_2950U2B,
ID_ALL_MASK,
"Adaptec 2950 Ultra2 SCSI adapter",
ahc_aic7890_setup
},
{
ID_AIC7890_ARO,
ID_ALL_MASK,
"Adaptec aic7890/91 Ultra2 SCSI adapter (ARO)",
ahc_aic7890_setup
},
{
ID_AAA_131U2,
ID_ALL_MASK,
"Adaptec AAA-131 Ultra2 RAID adapter",
ahc_aic7890_setup
},
/* aic7892 based controllers */
{
ID_AHA_29160,
ID_ALL_MASK,
"Adaptec 29160 Ultra160 SCSI adapter",
ahc_aic7892_setup
},
{
ID_AHA_29160_CPQ,
ID_ALL_MASK,
"Adaptec (Compaq OEM) 29160 Ultra160 SCSI adapter",
ahc_aic7892_setup
},
{
ID_AHA_29160N,
ID_ALL_MASK,
"Adaptec 29160N Ultra160 SCSI adapter",
ahc_aic7892_setup
},
{
ID_AHA_29160C,
ID_ALL_MASK,
"Adaptec 29160C Ultra160 SCSI adapter",
ahc_aha29160C_setup
},
{
ID_AHA_29160B,
ID_ALL_MASK,
"Adaptec 29160B Ultra160 SCSI adapter",
ahc_aic7892_setup
},
{
ID_AHA_19160B,
ID_ALL_MASK,
"Adaptec 19160B Ultra160 SCSI adapter",
ahc_aic7892_setup
},
{
ID_AIC7892_ARO,
ID_ALL_MASK,
"Adaptec aic7892 Ultra160 SCSI adapter (ARO)",
ahc_aic7892_setup
},
{
ID_AHA_2915_30LP,
ID_ALL_MASK,
"Adaptec 2915/30LP Ultra160 SCSI adapter",
ahc_aic7892_setup
},
/* aic7895 based controllers */
{
ID_AHA_2940U_DUAL,
ID_ALL_MASK,
"Adaptec 2940/DUAL Ultra SCSI adapter",
ahc_aic7895_setup
},
{
ID_AHA_3940AU,
ID_ALL_MASK,
"Adaptec 3940A Ultra SCSI adapter",
ahc_aic7895_setup
},
{
ID_AHA_3944AU,
ID_ALL_MASK,
"Adaptec 3944A Ultra SCSI adapter",
ahc_aic7895h_setup
},
{
ID_AIC7895_ARO,
ID_AIC7895_ARO_MASK,
"Adaptec aic7895 Ultra SCSI adapter (ARO)",
ahc_aic7895_setup
},
/* aic7896/97 based controllers */
{
ID_AHA_3950U2B_0,
ID_ALL_MASK,
"Adaptec 3950B Ultra2 SCSI adapter",
ahc_aic7896_setup
},
{
ID_AHA_3950U2B_1,
ID_ALL_MASK,
"Adaptec 3950B Ultra2 SCSI adapter",
ahc_aic7896_setup
},
{
ID_AHA_3950U2D_0,
ID_ALL_MASK,
"Adaptec 3950D Ultra2 SCSI adapter",
ahc_aic7896_setup
},
{
ID_AHA_3950U2D_1,
ID_ALL_MASK,
"Adaptec 3950D Ultra2 SCSI adapter",
ahc_aic7896_setup
},
{
ID_AIC7896_ARO,
ID_ALL_MASK,
"Adaptec aic7896/97 Ultra2 SCSI adapter (ARO)",
ahc_aic7896_setup
},
/* aic7899 based controllers */
{
ID_AHA_3960D,
ID_ALL_MASK,
"Adaptec 3960D Ultra160 SCSI adapter",
ahc_aic7899_setup
},
{
ID_AHA_3960D_CPQ,
ID_ALL_MASK,
"Adaptec (Compaq OEM) 3960D Ultra160 SCSI adapter",
ahc_aic7899_setup
},
{
ID_AIC7899_ARO,
ID_ALL_MASK,
"Adaptec aic7899 Ultra160 SCSI adapter (ARO)",
ahc_aic7899_setup
},
/* Generic chip probes for devices we don't know 'exactly' */
{
ID_AIC7850 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7850 SCSI adapter",
ahc_aic785X_setup
},
{
ID_AIC7855 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7855 SCSI adapter",
ahc_aic785X_setup
},
{
ID_AIC7859 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7859 SCSI adapter",
ahc_aic7860_setup
},
{
ID_AIC7860 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7860 Ultra SCSI adapter",
ahc_aic7860_setup
},
{
ID_AIC7870 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7870 SCSI adapter",
ahc_aic7870_setup
},
{
ID_AIC7880 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7880 Ultra SCSI adapter",
ahc_aic7880_setup
},
{
ID_AIC7890 & ID_9005_GENERIC_MASK,
ID_9005_GENERIC_MASK,
"Adaptec aic7890/91 Ultra2 SCSI adapter",
ahc_aic7890_setup
},
{
ID_AIC7892 & ID_9005_GENERIC_MASK,
ID_9005_GENERIC_MASK,
"Adaptec aic7892 Ultra160 SCSI adapter",
ahc_aic7892_setup
},
{
ID_AIC7895 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7895 Ultra SCSI adapter",
ahc_aic7895_setup
},
{
ID_AIC7896 & ID_9005_GENERIC_MASK,
ID_9005_GENERIC_MASK,
"Adaptec aic7896/97 Ultra2 SCSI adapter",
ahc_aic7896_setup
},
{
ID_AIC7899 & ID_9005_GENERIC_MASK,
ID_9005_GENERIC_MASK,
"Adaptec aic7899 Ultra160 SCSI adapter",
ahc_aic7899_setup
},
{
ID_AIC7810 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7810 RAID memory controller",
ahc_raid_setup
},
{
ID_AIC7815 & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec aic7815 RAID memory controller",
ahc_raid_setup
}
};
static const u_int ahc_num_pci_devs = ARRAY_SIZE(ahc_pci_ident_table);
#define AHC_394X_SLOT_CHANNEL_A 4
#define AHC_394X_SLOT_CHANNEL_B 5
#define AHC_398X_SLOT_CHANNEL_A 4
#define AHC_398X_SLOT_CHANNEL_B 8
#define AHC_398X_SLOT_CHANNEL_C 12
#define AHC_494X_SLOT_CHANNEL_A 4
#define AHC_494X_SLOT_CHANNEL_B 5
#define AHC_494X_SLOT_CHANNEL_C 6
#define AHC_494X_SLOT_CHANNEL_D 7
#define DEVCONFIG 0x40
#define PCIERRGENDIS 0x80000000ul
#define SCBSIZE32 0x00010000ul /* aic789X only */
#define REXTVALID 0x00001000ul /* ultra cards only */
#define MPORTMODE 0x00000400ul /* aic7870+ only */
#define RAMPSM 0x00000200ul /* aic7870+ only */
#define VOLSENSE 0x00000100ul
#define PCI64BIT 0x00000080ul /* 64Bit PCI bus (Ultra2 Only)*/
#define SCBRAMSEL 0x00000080ul
#define MRDCEN 0x00000040ul
#define EXTSCBTIME 0x00000020ul /* aic7870 only */
#define EXTSCBPEN 0x00000010ul /* aic7870 only */
#define BERREN 0x00000008ul
#define DACEN 0x00000004ul
#define STPWLEVEL 0x00000002ul
#define DIFACTNEGEN 0x00000001ul /* aic7870 only */
#define CSIZE_LATTIME 0x0c
#define CACHESIZE 0x0000003ful /* only 5 bits */
#define LATTIME 0x0000ff00ul
/* PCI STATUS definitions */
#define DPE 0x80
#define SSE 0x40
#define RMA 0x20
#define RTA 0x10
#define STA 0x08
#define DPR 0x01
static int ahc_9005_subdevinfo_valid(uint16_t vendor, uint16_t device,
uint16_t subvendor, uint16_t subdevice);
static int ahc_ext_scbram_present(struct ahc_softc *ahc);
static void ahc_scbram_config(struct ahc_softc *ahc, int enable,
int pcheck, int fast, int large);
static void ahc_probe_ext_scbram(struct ahc_softc *ahc);
static void check_extport(struct ahc_softc *ahc, u_int *sxfrctl1);
static void ahc_parse_pci_eeprom(struct ahc_softc *ahc,
struct seeprom_config *sc);
static void configure_termination(struct ahc_softc *ahc,
struct seeprom_descriptor *sd,
u_int adapter_control,
u_int *sxfrctl1);
static void ahc_new_term_detect(struct ahc_softc *ahc,
int *enableSEC_low,
int *enableSEC_high,
int *enablePRI_low,
int *enablePRI_high,
int *eeprom_present);
static void aic787X_cable_detect(struct ahc_softc *ahc, int *internal50_present,
int *internal68_present,
int *externalcable_present,
int *eeprom_present);
static void aic785X_cable_detect(struct ahc_softc *ahc, int *internal50_present,
int *externalcable_present,
int *eeprom_present);
static void write_brdctl(struct ahc_softc *ahc, uint8_t value);
static uint8_t read_brdctl(struct ahc_softc *ahc);
static void ahc_pci_intr(struct ahc_softc *ahc);
static int ahc_pci_chip_init(struct ahc_softc *ahc);
static int
ahc_9005_subdevinfo_valid(uint16_t device, uint16_t vendor,
uint16_t subdevice, uint16_t subvendor)
{
int result;
/* Default to invalid. */
result = 0;
if (vendor == 0x9005
&& subvendor == 0x9005
&& subdevice != device
&& SUBID_9005_TYPE_KNOWN(subdevice) != 0) {
switch (SUBID_9005_TYPE(subdevice)) {
case SUBID_9005_TYPE_MB:
break;
case SUBID_9005_TYPE_CARD:
case SUBID_9005_TYPE_LCCARD:
/*
* Currently only trust Adaptec cards to
* get the sub device info correct.
*/
if (DEVID_9005_TYPE(device) == DEVID_9005_TYPE_HBA)
result = 1;
break;
case SUBID_9005_TYPE_RAID:
break;
default:
break;
}
}
return (result);
}
const struct ahc_pci_identity *
ahc_find_pci_device(ahc_dev_softc_t pci)
{
uint64_t full_id;
uint16_t device;
uint16_t vendor;
uint16_t subdevice;
uint16_t subvendor;
const struct ahc_pci_identity *entry;
u_int i;
vendor = ahc_pci_read_config(pci, PCIR_DEVVENDOR, /*bytes*/2);
device = ahc_pci_read_config(pci, PCIR_DEVICE, /*bytes*/2);
subvendor = ahc_pci_read_config(pci, PCIR_SUBVEND_0, /*bytes*/2);
subdevice = ahc_pci_read_config(pci, PCIR_SUBDEV_0, /*bytes*/2);
full_id = ahc_compose_id(device, vendor, subdevice, subvendor);
/*
* If the second function is not hooked up, ignore it.
* Unfortunately, not all MB vendors implement the
* subdevice ID as per the Adaptec spec, so do our best
* to sanity check it prior to accepting the subdevice
* ID as valid.
*/
if (ahc_get_pci_function(pci) > 0
&& ahc_9005_subdevinfo_valid(vendor, device, subvendor, subdevice)
&& SUBID_9005_MFUNCENB(subdevice) == 0)
return (NULL);
for (i = 0; i < ahc_num_pci_devs; i++) {
entry = &ahc_pci_ident_table[i];
if (entry->full_id == (full_id & entry->id_mask)) {
/* Honor exclusion entries. */
if (entry->name == NULL)
return (NULL);
return (entry);
}
}
return (NULL);
}
int
ahc_pci_config(struct ahc_softc *ahc, const struct ahc_pci_identity *entry)
{
u_int command;
u_int our_id;
u_int sxfrctl1;
u_int scsiseq;
u_int dscommand0;
uint32_t devconfig;
int error;
uint8_t sblkctl;
our_id = 0;
error = entry->setup(ahc);
if (error != 0)
return (error);
ahc->chip |= AHC_PCI;
ahc->description = entry->name;
pci_set_power_state(ahc->dev_softc, AHC_POWER_STATE_D0);
error = ahc_pci_map_registers(ahc);
if (error != 0)
return (error);
/*
* Before we continue probing the card, ensure that
* its interrupts are *disabled*. We don't want
* a misstep to hang the machine in an interrupt
* storm.
*/
ahc_intr_enable(ahc, FALSE);
devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, /*bytes*/4);
/*
* If we need to support high memory, enable dual
* address cycles. This bit must be set to enable
* high address bit generation even if we are on a
* 64bit bus (PCI64BIT set in devconfig).
*/
if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
if (bootverbose)
printk("%s: Enabling 39Bit Addressing\n",
ahc_name(ahc));
devconfig |= DACEN;
}
/* Ensure that pci error generation, a test feature, is disabled. */
devconfig |= PCIERRGENDIS;
ahc_pci_write_config(ahc->dev_softc, DEVCONFIG, devconfig, /*bytes*/4);
/* Ensure busmastering is enabled */
command = ahc_pci_read_config(ahc->dev_softc, PCIR_COMMAND, /*bytes*/2);
command |= PCIM_CMD_BUSMASTEREN;
ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND, command, /*bytes*/2);
/* On all PCI adapters, we allow SCB paging */
ahc->flags |= AHC_PAGESCBS;
error = ahc_softc_init(ahc);
if (error != 0)
return (error);
/*
* Disable PCI parity error checking. Users typically
* do this to work around broken PCI chipsets that get
* the parity timing wrong and thus generate lots of spurious
* errors. The chip only allows us to disable *all* parity
* error reporting when doing this, so CIO bus, scb ram, and
* scratch ram parity errors will be ignored too.
*/
if ((ahc->flags & AHC_DISABLE_PCI_PERR) != 0)
ahc->seqctl |= FAILDIS;
ahc->bus_intr = ahc_pci_intr;
ahc->bus_chip_init = ahc_pci_chip_init;
/* Remember how the card was setup in case there is no SEEPROM */
if ((ahc_inb(ahc, HCNTRL) & POWRDN) == 0) {
ahc_pause(ahc);
if ((ahc->features & AHC_ULTRA2) != 0)
our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID;
else
our_id = ahc_inb(ahc, SCSIID) & OID;
sxfrctl1 = ahc_inb(ahc, SXFRCTL1) & STPWEN;
scsiseq = ahc_inb(ahc, SCSISEQ);
} else {
sxfrctl1 = STPWEN;
our_id = 7;
scsiseq = 0;
}
error = ahc_reset(ahc, /*reinit*/FALSE);
if (error != 0)
return (ENXIO);
if ((ahc->features & AHC_DT) != 0) {
u_int sfunct;
/* Perform ALT-Mode Setup */
sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE;
ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE);
ahc_outb(ahc, OPTIONMODE,
OPTIONMODE_DEFAULTS|AUTOACKEN|BUSFREEREV|EXPPHASEDIS);
ahc_outb(ahc, SFUNCT, sfunct);
/* Normal mode setup */
ahc_outb(ahc, CRCCONTROL1, CRCVALCHKEN|CRCENDCHKEN|CRCREQCHKEN
|TARGCRCENDEN);
}
dscommand0 = ahc_inb(ahc, DSCOMMAND0);
dscommand0 |= MPARCKEN|CACHETHEN;
if ((ahc->features & AHC_ULTRA2) != 0) {
/*
* DPARCKEN doesn't work correctly on
* some MBs so don't use it.
*/
dscommand0 &= ~DPARCKEN;
}
/*
* Handle chips that must have cache line
* streaming (dis/en)abled.
*/
if ((ahc->bugs & AHC_CACHETHEN_DIS_BUG) != 0)
dscommand0 |= CACHETHEN;
if ((ahc->bugs & AHC_CACHETHEN_BUG) != 0)
dscommand0 &= ~CACHETHEN;
ahc_outb(ahc, DSCOMMAND0, dscommand0);
ahc->pci_cachesize =
ahc_pci_read_config(ahc->dev_softc, CSIZE_LATTIME,
/*bytes*/1) & CACHESIZE;
ahc->pci_cachesize *= 4;
if ((ahc->bugs & AHC_PCI_2_1_RETRY_BUG) != 0
&& ahc->pci_cachesize == 4) {
ahc_pci_write_config(ahc->dev_softc, CSIZE_LATTIME,
0, /*bytes*/1);
ahc->pci_cachesize = 0;
}
/*
* We cannot perform ULTRA speeds without the presence
* of the external precision resistor.
*/
if ((ahc->features & AHC_ULTRA) != 0) {
uint32_t devconfig;
devconfig = ahc_pci_read_config(ahc->dev_softc,
DEVCONFIG, /*bytes*/4);
if ((devconfig & REXTVALID) == 0)
ahc->features &= ~AHC_ULTRA;
}
/* See if we have a SEEPROM and perform auto-term */
check_extport(ahc, &sxfrctl1);
/*
* Take the LED out of diagnostic mode
*/
sblkctl = ahc_inb(ahc, SBLKCTL);
ahc_outb(ahc, SBLKCTL, (sblkctl & ~(DIAGLEDEN|DIAGLEDON)));
if ((ahc->features & AHC_ULTRA2) != 0) {
ahc_outb(ahc, DFF_THRSH, RD_DFTHRSH_MAX|WR_DFTHRSH_MAX);
} else {
ahc_outb(ahc, DSPCISTATUS, DFTHRSH_100);
}
if (ahc->flags & AHC_USEDEFAULTS) {
/*
* PCI Adapter default setup
* Should only be used if the adapter does not have
* a SEEPROM.
*/
/* See if someone else set us up already */
if ((ahc->flags & AHC_NO_BIOS_INIT) == 0
&& scsiseq != 0) {
printk("%s: Using left over BIOS settings\n",
ahc_name(ahc));
ahc->flags &= ~AHC_USEDEFAULTS;
ahc->flags |= AHC_BIOS_ENABLED;
} else {
/*
* Assume only one connector and always turn
* on termination.
*/
our_id = 0x07;
sxfrctl1 = STPWEN;
}
ahc_outb(ahc, SCSICONF, our_id|ENSPCHK|RESET_SCSI);
ahc->our_id = our_id;
}
/*
* Take a look to see if we have external SRAM.
* We currently do not attempt to use SRAM that is
* shared among multiple controllers.
*/
ahc_probe_ext_scbram(ahc);
/*
* Record our termination setting for the
* generic initialization routine.
*/
if ((sxfrctl1 & STPWEN) != 0)
ahc->flags |= AHC_TERM_ENB_A;
/*
* Save chip register configuration data for chip resets
* that occur during runtime and resume events.
*/
ahc->bus_softc.pci_softc.devconfig =
ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, /*bytes*/4);
ahc->bus_softc.pci_softc.command =
ahc_pci_read_config(ahc->dev_softc, PCIR_COMMAND, /*bytes*/1);
ahc->bus_softc.pci_softc.csize_lattime =
ahc_pci_read_config(ahc->dev_softc, CSIZE_LATTIME, /*bytes*/1);
ahc->bus_softc.pci_softc.dscommand0 = ahc_inb(ahc, DSCOMMAND0);
ahc->bus_softc.pci_softc.dspcistatus = ahc_inb(ahc, DSPCISTATUS);
if ((ahc->features & AHC_DT) != 0) {
u_int sfunct;
sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE;
ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE);
ahc->bus_softc.pci_softc.optionmode = ahc_inb(ahc, OPTIONMODE);
ahc->bus_softc.pci_softc.targcrccnt = ahc_inw(ahc, TARGCRCCNT);
ahc_outb(ahc, SFUNCT, sfunct);
ahc->bus_softc.pci_softc.crccontrol1 =
ahc_inb(ahc, CRCCONTROL1);
}
if ((ahc->features & AHC_MULTI_FUNC) != 0)
ahc->bus_softc.pci_softc.scbbaddr = ahc_inb(ahc, SCBBADDR);
if ((ahc->features & AHC_ULTRA2) != 0)
ahc->bus_softc.pci_softc.dff_thrsh = ahc_inb(ahc, DFF_THRSH);
/* Core initialization */
error = ahc_init(ahc);
if (error != 0)
return (error);
ahc->init_level++;
/*
* Allow interrupts now that we are completely setup.
*/
return ahc_pci_map_int(ahc);
}
/*
* Test for the presence of external sram in an
* "unshared" configuration.
*/
static int
ahc_ext_scbram_present(struct ahc_softc *ahc)
{
u_int chip;
int ramps;
int single_user;
uint32_t devconfig;
chip = ahc->chip & AHC_CHIPID_MASK;
devconfig = ahc_pci_read_config(ahc->dev_softc,
DEVCONFIG, /*bytes*/4);
single_user = (devconfig & MPORTMODE) != 0;
if ((ahc->features & AHC_ULTRA2) != 0)
ramps = (ahc_inb(ahc, DSCOMMAND0) & RAMPS) != 0;
else if (chip == AHC_AIC7895 || chip == AHC_AIC7895C)
/*
* External SCBRAM arbitration is flakey
* on these chips. Unfortunately this means
* we don't use the extra SCB ram space on the
* 3940AUW.
*/
ramps = 0;
else if (chip >= AHC_AIC7870)
ramps = (devconfig & RAMPSM) != 0;
else
ramps = 0;
if (ramps && single_user)
return (1);
return (0);
}
/*
* Enable external scbram.
*/
static void
ahc_scbram_config(struct ahc_softc *ahc, int enable, int pcheck,
int fast, int large)
{
uint32_t devconfig;
if (ahc->features & AHC_MULTI_FUNC) {
/*
* Set the SCB Base addr (highest address bit)
* depending on which channel we are.
*/
ahc_outb(ahc, SCBBADDR, ahc_get_pci_function(ahc->dev_softc));
}
ahc->flags &= ~AHC_LSCBS_ENABLED;
if (large)
ahc->flags |= AHC_LSCBS_ENABLED;
devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, /*bytes*/4);
if ((ahc->features & AHC_ULTRA2) != 0) {
u_int dscommand0;
dscommand0 = ahc_inb(ahc, DSCOMMAND0);
if (enable)
dscommand0 &= ~INTSCBRAMSEL;
else
dscommand0 |= INTSCBRAMSEL;
if (large)
dscommand0 &= ~USCBSIZE32;
else
dscommand0 |= USCBSIZE32;
ahc_outb(ahc, DSCOMMAND0, dscommand0);
} else {
if (fast)
devconfig &= ~EXTSCBTIME;
else
devconfig |= EXTSCBTIME;
if (enable)
devconfig &= ~SCBRAMSEL;
else
devconfig |= SCBRAMSEL;
if (large)
devconfig &= ~SCBSIZE32;
else
devconfig |= SCBSIZE32;
}
if (pcheck)
devconfig |= EXTSCBPEN;
else
devconfig &= ~EXTSCBPEN;
ahc_pci_write_config(ahc->dev_softc, DEVCONFIG, devconfig, /*bytes*/4);
}
/*
* Take a look to see if we have external SRAM.
* We currently do not attempt to use SRAM that is
* shared among multiple controllers.
*/
static void
ahc_probe_ext_scbram(struct ahc_softc *ahc)
{
int num_scbs;
int test_num_scbs;
int enable;
int pcheck;
int fast;
int large;
enable = FALSE;
pcheck = FALSE;
fast = FALSE;
large = FALSE;
num_scbs = 0;
if (ahc_ext_scbram_present(ahc) == 0)
goto done;
/*
* Probe for the best parameters to use.
*/
ahc_scbram_config(ahc, /*enable*/TRUE, pcheck, fast, large);
num_scbs = ahc_probe_scbs(ahc);
if (num_scbs == 0) {
/* The SRAM wasn't really present. */
goto done;
}
enable = TRUE;
/*
* Clear any outstanding parity error
* and ensure that parity error reporting
* is enabled.
*/
ahc_outb(ahc, SEQCTL, 0);
ahc_outb(ahc, CLRINT, CLRPARERR);
ahc_outb(ahc, CLRINT, CLRBRKADRINT);
/* Now see if we can do parity */
ahc_scbram_config(ahc, enable, /*pcheck*/TRUE, fast, large);
num_scbs = ahc_probe_scbs(ahc);
if ((ahc_inb(ahc, INTSTAT) & BRKADRINT) == 0
|| (ahc_inb(ahc, ERROR) & MPARERR) == 0)
pcheck = TRUE;
/* Clear any resulting parity error */
ahc_outb(ahc, CLRINT, CLRPARERR);
ahc_outb(ahc, CLRINT, CLRBRKADRINT);
/* Now see if we can do fast timing */
ahc_scbram_config(ahc, enable, pcheck, /*fast*/TRUE, large);
test_num_scbs = ahc_probe_scbs(ahc);
if (test_num_scbs == num_scbs
&& ((ahc_inb(ahc, INTSTAT) & BRKADRINT) == 0
|| (ahc_inb(ahc, ERROR) & MPARERR) == 0))
fast = TRUE;
/*
* See if we can use large SCBs and still maintain
* the same overall count of SCBs.
*/
if ((ahc->features & AHC_LARGE_SCBS) != 0) {
ahc_scbram_config(ahc, enable, pcheck, fast, /*large*/TRUE);
test_num_scbs = ahc_probe_scbs(ahc);
if (test_num_scbs >= num_scbs) {
large = TRUE;
num_scbs = test_num_scbs;
if (num_scbs >= 64) {
/*
* We have enough space to move the
* "busy targets table" into SCB space
* and make it qualify all the way to the
* lun level.
*/
ahc->flags |= AHC_SCB_BTT;
}
}
}
done:
/*
* Disable parity error reporting until we
* can load instruction ram.
*/
ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS);
/* Clear any latched parity error */
ahc_outb(ahc, CLRINT, CLRPARERR);
ahc_outb(ahc, CLRINT, CLRBRKADRINT);
if (bootverbose && enable) {
printk("%s: External SRAM, %s access%s, %dbytes/SCB\n",
ahc_name(ahc), fast ? "fast" : "slow",
pcheck ? ", parity checking enabled" : "",
large ? 64 : 32);
}
ahc_scbram_config(ahc, enable, pcheck, fast, large);
}
/*
* Perform some simple tests that should catch situations where
* our registers are invalidly mapped.
*/
int
ahc_pci_test_register_access(struct ahc_softc *ahc)
{
int error;
u_int status1;
uint32_t cmd;
uint8_t hcntrl;
error = EIO;
/*
* Enable PCI error interrupt status, but suppress NMIs
* generated by SERR raised due to target aborts.
*/
cmd = ahc_pci_read_config(ahc->dev_softc, PCIR_COMMAND, /*bytes*/2);
ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND,
cmd & ~PCIM_CMD_SERRESPEN, /*bytes*/2);
/*
* First a simple test to see if any
* registers can be read. Reading
* HCNTRL has no side effects and has
* at least one bit that is guaranteed to
* be zero so it is a good register to
* use for this test.
*/
hcntrl = ahc_inb(ahc, HCNTRL);
if (hcntrl == 0xFF)
goto fail;
if ((hcntrl & CHIPRST) != 0) {
/*
* The chip has not been initialized since
* PCI/EISA/VLB bus reset. Don't trust
* "left over BIOS data".
*/
ahc->flags |= AHC_NO_BIOS_INIT;
}
/*
* Next create a situation where write combining
* or read prefetching could be initiated by the
* CPU or host bridge. Our device does not support
* either, so look for data corruption and/or flagged
* PCI errors. First pause without causing another
* chip reset.
*/
hcntrl &= ~CHIPRST;
ahc_outb(ahc, HCNTRL, hcntrl|PAUSE);
while (ahc_is_paused(ahc) == 0)
;
/* Clear any PCI errors that occurred before our driver attached. */
status1 = ahc_pci_read_config(ahc->dev_softc,
PCIR_STATUS + 1, /*bytes*/1);
ahc_pci_write_config(ahc->dev_softc, PCIR_STATUS + 1,
status1, /*bytes*/1);
ahc_outb(ahc, CLRINT, CLRPARERR);
ahc_outb(ahc, SEQCTL, PERRORDIS);
ahc_outb(ahc, SCBPTR, 0);
ahc_outl(ahc, SCB_BASE, 0x5aa555aa);
if (ahc_inl(ahc, SCB_BASE) != 0x5aa555aa)
goto fail;
status1 = ahc_pci_read_config(ahc->dev_softc,
PCIR_STATUS + 1, /*bytes*/1);
if ((status1 & STA) != 0)
goto fail;
error = 0;
fail:
/* Silently clear any latched errors. */
status1 = ahc_pci_read_config(ahc->dev_softc,
PCIR_STATUS + 1, /*bytes*/1);
ahc_pci_write_config(ahc->dev_softc, PCIR_STATUS + 1,
status1, /*bytes*/1);
ahc_outb(ahc, CLRINT, CLRPARERR);
ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS);
ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND, cmd, /*bytes*/2);
return (error);
}
/*
* Check the external port logic for a serial eeprom
* and termination/cable detection contrls.
*/
static void
check_extport(struct ahc_softc *ahc, u_int *sxfrctl1)
{
struct seeprom_descriptor sd;
struct seeprom_config *sc;
int have_seeprom;
int have_autoterm;
sd.sd_ahc = ahc;
sd.sd_control_offset = SEECTL;
sd.sd_status_offset = SEECTL;
sd.sd_dataout_offset = SEECTL;
sc = ahc->seep_config;
/*
* For some multi-channel devices, the c46 is simply too
* small to work. For the other controller types, we can
* get our information from either SEEPROM type. Set the
* type to start our probe with accordingly.
*/
if (ahc->flags & AHC_LARGE_SEEPROM)
sd.sd_chip = C56_66;
else
sd.sd_chip = C46;
sd.sd_MS = SEEMS;
sd.sd_RDY = SEERDY;
sd.sd_CS = SEECS;
sd.sd_CK = SEECK;
sd.sd_DO = SEEDO;
sd.sd_DI = SEEDI;
have_seeprom = ahc_acquire_seeprom(ahc, &sd);
if (have_seeprom) {
if (bootverbose)
printk("%s: Reading SEEPROM...", ahc_name(ahc));
for (;;) {
u_int start_addr;
start_addr = 32 * (ahc->channel - 'A');
have_seeprom = ahc_read_seeprom(&sd, (uint16_t *)sc,
start_addr,
sizeof(*sc)/2);
if (have_seeprom)
have_seeprom = ahc_verify_cksum(sc);
if (have_seeprom != 0 || sd.sd_chip == C56_66) {
if (bootverbose) {
if (have_seeprom == 0)
printk ("checksum error\n");
else
printk ("done.\n");
}
break;
}
sd.sd_chip = C56_66;
}
ahc_release_seeprom(&sd);
/* Remember the SEEPROM type for later */
if (sd.sd_chip == C56_66)
ahc->flags |= AHC_LARGE_SEEPROM;
}
if (!have_seeprom) {
/*
* Pull scratch ram settings and treat them as
* if they are the contents of an seeprom if
* the 'ADPT' signature is found in SCB2.
* We manually compose the data as 16bit values
* to avoid endian issues.
*/
ahc_outb(ahc, SCBPTR, 2);
if (ahc_inb(ahc, SCB_BASE) == 'A'
&& ahc_inb(ahc, SCB_BASE + 1) == 'D'
&& ahc_inb(ahc, SCB_BASE + 2) == 'P'
&& ahc_inb(ahc, SCB_BASE + 3) == 'T') {
uint16_t *sc_data;
int i;
sc_data = (uint16_t *)sc;
for (i = 0; i < 32; i++, sc_data++) {
int j;
j = i * 2;
*sc_data = ahc_inb(ahc, SRAM_BASE + j)
| ahc_inb(ahc, SRAM_BASE + j + 1) << 8;
}
have_seeprom = ahc_verify_cksum(sc);
if (have_seeprom)
ahc->flags |= AHC_SCB_CONFIG_USED;
}
/*
* Clear any SCB parity errors in case this data and
* its associated parity was not initialized by the BIOS
*/
ahc_outb(ahc, CLRINT, CLRPARERR);
ahc_outb(ahc, CLRINT, CLRBRKADRINT);
}
if (!have_seeprom) {
if (bootverbose)
printk("%s: No SEEPROM available.\n", ahc_name(ahc));
ahc->flags |= AHC_USEDEFAULTS;
kfree(ahc->seep_config);
ahc->seep_config = NULL;
sc = NULL;
} else {
ahc_parse_pci_eeprom(ahc, sc);
}
/*
* Cards that have the external logic necessary to talk to
* a SEEPROM, are almost certain to have the remaining logic
* necessary for auto-termination control. This assumption
* hasn't failed yet...
*/
have_autoterm = have_seeprom;
/*
* Some low-cost chips have SEEPROM and auto-term control built
* in, instead of using a GAL. They can tell us directly
* if the termination logic is enabled.
*/
if ((ahc->features & AHC_SPIOCAP) != 0) {
if ((ahc_inb(ahc, SPIOCAP) & SSPIOCPS) == 0)
have_autoterm = FALSE;
}
if (have_autoterm) {
ahc->flags |= AHC_HAS_TERM_LOGIC;
ahc_acquire_seeprom(ahc, &sd);
configure_termination(ahc, &sd, sc->adapter_control, sxfrctl1);
ahc_release_seeprom(&sd);
} else if (have_seeprom) {
*sxfrctl1 &= ~STPWEN;
if ((sc->adapter_control & CFSTERM) != 0)
*sxfrctl1 |= STPWEN;
if (bootverbose)
printk("%s: Low byte termination %sabled\n",
ahc_name(ahc),
(*sxfrctl1 & STPWEN) ? "en" : "dis");
}
}
static void
ahc_parse_pci_eeprom(struct ahc_softc *ahc, struct seeprom_config *sc)
{
/*
* Put the data we've collected down into SRAM
* where ahc_init will find it.
*/
int i;
int max_targ = sc->max_targets & CFMAXTARG;
u_int scsi_conf;
uint16_t discenable;
uint16_t ultraenb;
discenable = 0;
ultraenb = 0;
if ((sc->adapter_control & CFULTRAEN) != 0) {
/*
* Determine if this adapter has a "newstyle"
* SEEPROM format.
*/
for (i = 0; i < max_targ; i++) {
if ((sc->device_flags[i] & CFSYNCHISULTRA) != 0) {
ahc->flags |= AHC_NEWEEPROM_FMT;
break;
}
}
}
for (i = 0; i < max_targ; i++) {
u_int scsirate;
uint16_t target_mask;
target_mask = 0x01 << i;
if (sc->device_flags[i] & CFDISC)
discenable |= target_mask;
if ((ahc->flags & AHC_NEWEEPROM_FMT) != 0) {
if ((sc->device_flags[i] & CFSYNCHISULTRA) != 0)
ultraenb |= target_mask;
} else if ((sc->adapter_control & CFULTRAEN) != 0) {
ultraenb |= target_mask;
}
if ((sc->device_flags[i] & CFXFER) == 0x04
&& (ultraenb & target_mask) != 0) {
/* Treat 10MHz as a non-ultra speed */
sc->device_flags[i] &= ~CFXFER;
ultraenb &= ~target_mask;
}
if ((ahc->features & AHC_ULTRA2) != 0) {
u_int offset;
if (sc->device_flags[i] & CFSYNCH)
offset = MAX_OFFSET_ULTRA2;
else
offset = 0;
ahc_outb(ahc, TARG_OFFSET + i, offset);
/*
* The ultra enable bits contain the
* high bit of the ultra2 sync rate
* field.
*/
scsirate = (sc->device_flags[i] & CFXFER)
| ((ultraenb & target_mask) ? 0x8 : 0x0);
if (sc->device_flags[i] & CFWIDEB)
scsirate |= WIDEXFER;
} else {
scsirate = (sc->device_flags[i] & CFXFER) << 4;
if (sc->device_flags[i] & CFSYNCH)
scsirate |= SOFS;
if (sc->device_flags[i] & CFWIDEB)
scsirate |= WIDEXFER;
}
ahc_outb(ahc, TARG_SCSIRATE + i, scsirate);
}
ahc->our_id = sc->brtime_id & CFSCSIID;
scsi_conf = (ahc->our_id & 0x7);
if (sc->adapter_control & CFSPARITY)
scsi_conf |= ENSPCHK;
if (sc->adapter_control & CFRESETB)
scsi_conf |= RESET_SCSI;
ahc->flags |= (sc->adapter_control & CFBOOTCHAN) >> CFBOOTCHANSHIFT;
if (sc->bios_control & CFEXTEND)
ahc->flags |= AHC_EXTENDED_TRANS_A;
if (sc->bios_control & CFBIOSEN)
ahc->flags |= AHC_BIOS_ENABLED;
if (ahc->features & AHC_ULTRA
&& (ahc->flags & AHC_NEWEEPROM_FMT) == 0) {
/* Should we enable Ultra mode? */
if (!(sc->adapter_control & CFULTRAEN))
/* Treat us as a non-ultra card */
ultraenb = 0;
}
if (sc->signature == CFSIGNATURE
|| sc->signature == CFSIGNATURE2) {
uint32_t devconfig;
/* Honor the STPWLEVEL settings */
devconfig = ahc_pci_read_config(ahc->dev_softc,
DEVCONFIG, /*bytes*/4);
devconfig &= ~STPWLEVEL;
if ((sc->bios_control & CFSTPWLEVEL) != 0)
devconfig |= STPWLEVEL;
ahc_pci_write_config(ahc->dev_softc, DEVCONFIG,
devconfig, /*bytes*/4);
}
/* Set SCSICONF info */
ahc_outb(ahc, SCSICONF, scsi_conf);
ahc_outb(ahc, DISC_DSB, ~(discenable & 0xff));
ahc_outb(ahc, DISC_DSB + 1, ~((discenable >> 8) & 0xff));
ahc_outb(ahc, ULTRA_ENB, ultraenb & 0xff);
ahc_outb(ahc, ULTRA_ENB + 1, (ultraenb >> 8) & 0xff);
}
static void
configure_termination(struct ahc_softc *ahc,
struct seeprom_descriptor *sd,
u_int adapter_control,
u_int *sxfrctl1)
{
uint8_t brddat;
brddat = 0;
/*
* Update the settings in sxfrctl1 to match the
* termination settings
*/
*sxfrctl1 = 0;
/*
* SEECS must be on for the GALS to latch
* the data properly. Be sure to leave MS
* on or we will release the seeprom.
*/
SEEPROM_OUTB(sd, sd->sd_MS | sd->sd_CS);
if ((adapter_control & CFAUTOTERM) != 0
|| (ahc->features & AHC_NEW_TERMCTL) != 0) {
int internal50_present;
int internal68_present;
int externalcable_present;
int eeprom_present;
int enableSEC_low;
int enableSEC_high;
int enablePRI_low;
int enablePRI_high;
int sum;
enableSEC_low = 0;
enableSEC_high = 0;
enablePRI_low = 0;
enablePRI_high = 0;
if ((ahc->features & AHC_NEW_TERMCTL) != 0) {
ahc_new_term_detect(ahc, &enableSEC_low,
&enableSEC_high,
&enablePRI_low,
&enablePRI_high,
&eeprom_present);
if ((adapter_control & CFSEAUTOTERM) == 0) {
if (bootverbose)
printk("%s: Manual SE Termination\n",
ahc_name(ahc));
enableSEC_low = (adapter_control & CFSELOWTERM);
enableSEC_high =
(adapter_control & CFSEHIGHTERM);
}
if ((adapter_control & CFAUTOTERM) == 0) {
if (bootverbose)
printk("%s: Manual LVD Termination\n",
ahc_name(ahc));
enablePRI_low = (adapter_control & CFSTERM);
enablePRI_high = (adapter_control & CFWSTERM);
}
/* Make the table calculations below happy */
internal50_present = 0;
internal68_present = 1;
externalcable_present = 1;
} else if ((ahc->features & AHC_SPIOCAP) != 0) {
aic785X_cable_detect(ahc, &internal50_present,
&externalcable_present,
&eeprom_present);
/* Can never support a wide connector. */
internal68_present = 0;
} else {
aic787X_cable_detect(ahc, &internal50_present,
&internal68_present,
&externalcable_present,
&eeprom_present);
}
if ((ahc->features & AHC_WIDE) == 0)
internal68_present = 0;
if (bootverbose
&& (ahc->features & AHC_ULTRA2) == 0) {
printk("%s: internal 50 cable %s present",
ahc_name(ahc),
internal50_present ? "is":"not");
if ((ahc->features & AHC_WIDE) != 0)
printk(", internal 68 cable %s present",
internal68_present ? "is":"not");
printk("\n%s: external cable %s present\n",
ahc_name(ahc),
externalcable_present ? "is":"not");
}
if (bootverbose)
printk("%s: BIOS eeprom %s present\n",
ahc_name(ahc), eeprom_present ? "is" : "not");
if ((ahc->flags & AHC_INT50_SPEEDFLEX) != 0) {
/*
* The 50 pin connector is a separate bus,
* so force it to always be terminated.
* In the future, perform current sensing
* to determine if we are in the middle of
* a properly terminated bus.
*/
internal50_present = 0;
}
/*
* Now set the termination based on what
* we found.
* Flash Enable = BRDDAT7
* Secondary High Term Enable = BRDDAT6
* Secondary Low Term Enable = BRDDAT5 (7890)
* Primary High Term Enable = BRDDAT4 (7890)
*/
if ((ahc->features & AHC_ULTRA2) == 0
&& (internal50_present != 0)
&& (internal68_present != 0)
&& (externalcable_present != 0)) {
printk("%s: Illegal cable configuration!!. "
"Only two connectors on the "
"adapter may be used at a "
"time!\n", ahc_name(ahc));
/*
* Pretend there are no cables in the hope
* that having all of the termination on
* gives us a more stable bus.
*/
internal50_present = 0;
internal68_present = 0;
externalcable_present = 0;
}
if ((ahc->features & AHC_WIDE) != 0
&& ((externalcable_present == 0)
|| (internal68_present == 0)
|| (enableSEC_high != 0))) {
brddat |= BRDDAT6;
if (bootverbose) {
if ((ahc->flags & AHC_INT50_SPEEDFLEX) != 0)
printk("%s: 68 pin termination "
"Enabled\n", ahc_name(ahc));
else
printk("%s: %sHigh byte termination "
"Enabled\n", ahc_name(ahc),
enableSEC_high ? "Secondary "
: "");
}
}
sum = internal50_present + internal68_present
+ externalcable_present;
if (sum < 2 || (enableSEC_low != 0)) {
if ((ahc->features & AHC_ULTRA2) != 0)
brddat |= BRDDAT5;
else
*sxfrctl1 |= STPWEN;
if (bootverbose) {
if ((ahc->flags & AHC_INT50_SPEEDFLEX) != 0)
printk("%s: 50 pin termination "
"Enabled\n", ahc_name(ahc));
else
printk("%s: %sLow byte termination "
"Enabled\n", ahc_name(ahc),
enableSEC_low ? "Secondary "
: "");
}
}
if (enablePRI_low != 0) {
*sxfrctl1 |= STPWEN;
if (bootverbose)
printk("%s: Primary Low Byte termination "
"Enabled\n", ahc_name(ahc));
}
/*
* Setup STPWEN before setting up the rest of
* the termination per the tech note on the U160 cards.
*/
ahc_outb(ahc, SXFRCTL1, *sxfrctl1);
if (enablePRI_high != 0) {
brddat |= BRDDAT4;
if (bootverbose)
printk("%s: Primary High Byte "
"termination Enabled\n",
ahc_name(ahc));
}
write_brdctl(ahc, brddat);
} else {
if ((adapter_control & CFSTERM) != 0) {
*sxfrctl1 |= STPWEN;
if (bootverbose)
printk("%s: %sLow byte termination Enabled\n",
ahc_name(ahc),
(ahc->features & AHC_ULTRA2) ? "Primary "
: "");
}
if ((adapter_control & CFWSTERM) != 0
&& (ahc->features & AHC_WIDE) != 0) {
brddat |= BRDDAT6;
if (bootverbose)
printk("%s: %sHigh byte termination Enabled\n",
ahc_name(ahc),
(ahc->features & AHC_ULTRA2)
? "Secondary " : "");
}
/*
* Setup STPWEN before setting up the rest of
* the termination per the tech note on the U160 cards.
*/
ahc_outb(ahc, SXFRCTL1, *sxfrctl1);
if ((ahc->features & AHC_WIDE) != 0)
write_brdctl(ahc, brddat);
}
SEEPROM_OUTB(sd, sd->sd_MS); /* Clear CS */
}
static void
ahc_new_term_detect(struct ahc_softc *ahc, int *enableSEC_low,
int *enableSEC_high, int *enablePRI_low,
int *enablePRI_high, int *eeprom_present)
{
uint8_t brdctl;
/*
* BRDDAT7 = Eeprom
* BRDDAT6 = Enable Secondary High Byte termination
* BRDDAT5 = Enable Secondary Low Byte termination
* BRDDAT4 = Enable Primary high byte termination
* BRDDAT3 = Enable Primary low byte termination
*/
brdctl = read_brdctl(ahc);
*eeprom_present = brdctl & BRDDAT7;
*enableSEC_high = (brdctl & BRDDAT6);
*enableSEC_low = (brdctl & BRDDAT5);
*enablePRI_high = (brdctl & BRDDAT4);
*enablePRI_low = (brdctl & BRDDAT3);
}
static void
aic787X_cable_detect(struct ahc_softc *ahc, int *internal50_present,
int *internal68_present, int *externalcable_present,
int *eeprom_present)
{
uint8_t brdctl;
/*
* First read the status of our cables.
* Set the rom bank to 0 since the
* bank setting serves as a multiplexor
* for the cable detection logic.
* BRDDAT5 controls the bank switch.
*/
write_brdctl(ahc, 0);
/*
* Now read the state of the internal
* connectors. BRDDAT6 is INT50 and
* BRDDAT7 is INT68.
*/
brdctl = read_brdctl(ahc);
*internal50_present = (brdctl & BRDDAT6) ? 0 : 1;
*internal68_present = (brdctl & BRDDAT7) ? 0 : 1;
/*
* Set the rom bank to 1 and determine
* the other signals.
*/
write_brdctl(ahc, BRDDAT5);
/*
* Now read the state of the external
* connectors. BRDDAT6 is EXT68 and
* BRDDAT7 is EPROMPS.
*/
brdctl = read_brdctl(ahc);
*externalcable_present = (brdctl & BRDDAT6) ? 0 : 1;
*eeprom_present = (brdctl & BRDDAT7) ? 1 : 0;
}
static void
aic785X_cable_detect(struct ahc_softc *ahc, int *internal50_present,
int *externalcable_present, int *eeprom_present)
{
uint8_t brdctl;
uint8_t spiocap;
spiocap = ahc_inb(ahc, SPIOCAP);
spiocap &= ~SOFTCMDEN;
spiocap |= EXT_BRDCTL;
ahc_outb(ahc, SPIOCAP, spiocap);
ahc_outb(ahc, BRDCTL, BRDRW|BRDCS);
ahc_flush_device_writes(ahc);
ahc_delay(500);
ahc_outb(ahc, BRDCTL, 0);
ahc_flush_device_writes(ahc);
ahc_delay(500);
brdctl = ahc_inb(ahc, BRDCTL);
*internal50_present = (brdctl & BRDDAT5) ? 0 : 1;
*externalcable_present = (brdctl & BRDDAT6) ? 0 : 1;
*eeprom_present = (ahc_inb(ahc, SPIOCAP) & EEPROM) ? 1 : 0;
}
int
ahc_acquire_seeprom(struct ahc_softc *ahc, struct seeprom_descriptor *sd)
{
int wait;
if ((ahc->features & AHC_SPIOCAP) != 0
&& (ahc_inb(ahc, SPIOCAP) & SEEPROM) == 0)
return (0);
/*
* Request access of the memory port. When access is
* granted, SEERDY will go high. We use a 1 second
* timeout which should be near 1 second more than
* is needed. Reason: after the chip reset, there
* should be no contention.
*/
SEEPROM_OUTB(sd, sd->sd_MS);
wait = 1000; /* 1 second timeout in msec */
while (--wait && ((SEEPROM_STATUS_INB(sd) & sd->sd_RDY) == 0)) {
ahc_delay(1000); /* delay 1 msec */
}
if ((SEEPROM_STATUS_INB(sd) & sd->sd_RDY) == 0) {
SEEPROM_OUTB(sd, 0);
return (0);
}
return(1);
}
void
ahc_release_seeprom(struct seeprom_descriptor *sd)
{
/* Release access to the memory port and the serial EEPROM. */
SEEPROM_OUTB(sd, 0);
}
static void
write_brdctl(struct ahc_softc *ahc, uint8_t value)
{
uint8_t brdctl;
if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7895) {
brdctl = BRDSTB;
if (ahc->channel == 'B')
brdctl |= BRDCS;
} else if ((ahc->features & AHC_ULTRA2) != 0) {
brdctl = 0;
} else {
brdctl = BRDSTB|BRDCS;
}
ahc_outb(ahc, BRDCTL, brdctl);
ahc_flush_device_writes(ahc);
brdctl |= value;
ahc_outb(ahc, BRDCTL, brdctl);
ahc_flush_device_writes(ahc);
if ((ahc->features & AHC_ULTRA2) != 0)
brdctl |= BRDSTB_ULTRA2;
else
brdctl &= ~BRDSTB;
ahc_outb(ahc, BRDCTL, brdctl);
ahc_flush_device_writes(ahc);
if ((ahc->features & AHC_ULTRA2) != 0)
brdctl = 0;
else
brdctl &= ~BRDCS;
ahc_outb(ahc, BRDCTL, brdctl);
}
static uint8_t
read_brdctl(struct ahc_softc *ahc)
{
uint8_t brdctl;
uint8_t value;
if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7895) {
brdctl = BRDRW;
if (ahc->channel == 'B')
brdctl |= BRDCS;
} else if ((ahc->features & AHC_ULTRA2) != 0) {
brdctl = BRDRW_ULTRA2;
} else {
brdctl = BRDRW|BRDCS;
}
ahc_outb(ahc, BRDCTL, brdctl);
ahc_flush_device_writes(ahc);
value = ahc_inb(ahc, BRDCTL);
ahc_outb(ahc, BRDCTL, 0);
return (value);
}
static void
ahc_pci_intr(struct ahc_softc *ahc)
{
u_int error;
u_int status1;
error = ahc_inb(ahc, ERROR);
if ((error & PCIERRSTAT) == 0)
return;
status1 = ahc_pci_read_config(ahc->dev_softc,
PCIR_STATUS + 1, /*bytes*/1);
printk("%s: PCI error Interrupt at seqaddr = 0x%x\n",
ahc_name(ahc),
ahc_inb(ahc, SEQADDR0) | (ahc_inb(ahc, SEQADDR1) << 8));
if (status1 & DPE) {
ahc->pci_target_perr_count++;
printk("%s: Data Parity Error Detected during address "
"or write data phase\n", ahc_name(ahc));
}
if (status1 & SSE) {
printk("%s: Signal System Error Detected\n", ahc_name(ahc));
}
if (status1 & RMA) {
printk("%s: Received a Master Abort\n", ahc_name(ahc));
}
if (status1 & RTA) {
printk("%s: Received a Target Abort\n", ahc_name(ahc));
}
if (status1 & STA) {
printk("%s: Signaled a Target Abort\n", ahc_name(ahc));
}
if (status1 & DPR) {
printk("%s: Data Parity Error has been reported via PERR#\n",
ahc_name(ahc));
}
/* Clear latched errors. */
ahc_pci_write_config(ahc->dev_softc, PCIR_STATUS + 1,
status1, /*bytes*/1);
if ((status1 & (DPE|SSE|RMA|RTA|STA|DPR)) == 0) {
printk("%s: Latched PCIERR interrupt with "
"no status bits set\n", ahc_name(ahc));
} else {
ahc_outb(ahc, CLRINT, CLRPARERR);
}
if (ahc->pci_target_perr_count > AHC_PCI_TARGET_PERR_THRESH) {
printk(
"%s: WARNING WARNING WARNING WARNING\n"
"%s: Too many PCI parity errors observed as a target.\n"
"%s: Some device on this bus is generating bad parity.\n"
"%s: This is an error *observed by*, not *generated by*, this controller.\n"
"%s: PCI parity error checking has been disabled.\n"
"%s: WARNING WARNING WARNING WARNING\n",
ahc_name(ahc), ahc_name(ahc), ahc_name(ahc),
ahc_name(ahc), ahc_name(ahc), ahc_name(ahc));
ahc->seqctl |= FAILDIS;
ahc_outb(ahc, SEQCTL, ahc->seqctl);
}
ahc_unpause(ahc);
}
static int
ahc_pci_chip_init(struct ahc_softc *ahc)
{
ahc_outb(ahc, DSCOMMAND0, ahc->bus_softc.pci_softc.dscommand0);
ahc_outb(ahc, DSPCISTATUS, ahc->bus_softc.pci_softc.dspcistatus);
if ((ahc->features & AHC_DT) != 0) {
u_int sfunct;
sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE;
ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE);
ahc_outb(ahc, OPTIONMODE, ahc->bus_softc.pci_softc.optionmode);
ahc_outw(ahc, TARGCRCCNT, ahc->bus_softc.pci_softc.targcrccnt);
ahc_outb(ahc, SFUNCT, sfunct);
ahc_outb(ahc, CRCCONTROL1,
ahc->bus_softc.pci_softc.crccontrol1);
}
if ((ahc->features & AHC_MULTI_FUNC) != 0)
ahc_outb(ahc, SCBBADDR, ahc->bus_softc.pci_softc.scbbaddr);
if ((ahc->features & AHC_ULTRA2) != 0)
ahc_outb(ahc, DFF_THRSH, ahc->bus_softc.pci_softc.dff_thrsh);
return (ahc_chip_init(ahc));
}
#ifdef CONFIG_PM
void
ahc_pci_resume(struct ahc_softc *ahc)
{
/*
* We assume that the OS has restored our register
* mappings, etc. Just update the config space registers
* that the OS doesn't know about and rely on our chip
* reset handler to handle the rest.
*/
ahc_pci_write_config(ahc->dev_softc, DEVCONFIG,
ahc->bus_softc.pci_softc.devconfig, /*bytes*/4);
ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND,
ahc->bus_softc.pci_softc.command, /*bytes*/1);
ahc_pci_write_config(ahc->dev_softc, CSIZE_LATTIME,
ahc->bus_softc.pci_softc.csize_lattime, /*bytes*/1);
if ((ahc->flags & AHC_HAS_TERM_LOGIC) != 0) {
struct seeprom_descriptor sd;
u_int sxfrctl1;
sd.sd_ahc = ahc;
sd.sd_control_offset = SEECTL;
sd.sd_status_offset = SEECTL;
sd.sd_dataout_offset = SEECTL;
ahc_acquire_seeprom(ahc, &sd);
configure_termination(ahc, &sd,
ahc->seep_config->adapter_control,
&sxfrctl1);
ahc_release_seeprom(&sd);
}
}
#endif
static int
ahc_aic785X_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
uint8_t rev;
pci = ahc->dev_softc;
ahc->channel = 'A';
ahc->chip = AHC_AIC7850;
ahc->features = AHC_AIC7850_FE;
ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG;
rev = ahc_pci_read_config(pci, PCIR_REVID, /*bytes*/1);
if (rev >= 1)
ahc->bugs |= AHC_PCI_2_1_RETRY_BUG;
ahc->instruction_ram_size = 512;
return (0);
}
static int
ahc_aic7860_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
uint8_t rev;
pci = ahc->dev_softc;
ahc->channel = 'A';
ahc->chip = AHC_AIC7860;
ahc->features = AHC_AIC7860_FE;
ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG;
rev = ahc_pci_read_config(pci, PCIR_REVID, /*bytes*/1);
if (rev >= 1)
ahc->bugs |= AHC_PCI_2_1_RETRY_BUG;
ahc->instruction_ram_size = 512;
return (0);
}
static int
ahc_apa1480_setup(struct ahc_softc *ahc)
{
int error;
error = ahc_aic7860_setup(ahc);
if (error != 0)
return (error);
ahc->features |= AHC_REMOVABLE;
return (0);
}
static int
ahc_aic7870_setup(struct ahc_softc *ahc)
{
ahc->channel = 'A';
ahc->chip = AHC_AIC7870;
ahc->features = AHC_AIC7870_FE;
ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG;
ahc->instruction_ram_size = 512;
return (0);
}
static int
ahc_aic7870h_setup(struct ahc_softc *ahc)
{
int error = ahc_aic7870_setup(ahc);
ahc->features |= AHC_HVD;
return error;
}
static int
ahc_aha394X_setup(struct ahc_softc *ahc)
{
int error;
error = ahc_aic7870_setup(ahc);
if (error == 0)
error = ahc_aha394XX_setup(ahc);
return (error);
}
static int
ahc_aha394Xh_setup(struct ahc_softc *ahc)
{
int error = ahc_aha394X_setup(ahc);
ahc->features |= AHC_HVD;
return error;
}
static int
ahc_aha398X_setup(struct ahc_softc *ahc)
{
int error;
error = ahc_aic7870_setup(ahc);
if (error == 0)
error = ahc_aha398XX_setup(ahc);
return (error);
}
static int
ahc_aha494X_setup(struct ahc_softc *ahc)
{
int error;
error = ahc_aic7870_setup(ahc);
if (error == 0)
error = ahc_aha494XX_setup(ahc);
return (error);
}
static int
ahc_aha494Xh_setup(struct ahc_softc *ahc)
{
int error = ahc_aha494X_setup(ahc);
ahc->features |= AHC_HVD;
return error;
}
static int
ahc_aic7880_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
uint8_t rev;
pci = ahc->dev_softc;
ahc->channel = 'A';
ahc->chip = AHC_AIC7880;
ahc->features = AHC_AIC7880_FE;
ahc->bugs |= AHC_TMODE_WIDEODD_BUG;
rev = ahc_pci_read_config(pci, PCIR_REVID, /*bytes*/1);
if (rev >= 1) {
ahc->bugs |= AHC_PCI_2_1_RETRY_BUG;
} else {
ahc->bugs |= AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG;
}
ahc->instruction_ram_size = 512;
return (0);
}
static int
ahc_aic7880h_setup(struct ahc_softc *ahc)
{
int error = ahc_aic7880_setup(ahc);
ahc->features |= AHC_HVD;
return error;
}
static int
ahc_aha2940Pro_setup(struct ahc_softc *ahc)
{
ahc->flags |= AHC_INT50_SPEEDFLEX;
return (ahc_aic7880_setup(ahc));
}
static int
ahc_aha394XU_setup(struct ahc_softc *ahc)
{
int error;
error = ahc_aic7880_setup(ahc);
if (error == 0)
error = ahc_aha394XX_setup(ahc);
return (error);
}
static int
ahc_aha394XUh_setup(struct ahc_softc *ahc)
{
int error = ahc_aha394XU_setup(ahc);
ahc->features |= AHC_HVD;
return error;
}
static int
ahc_aha398XU_setup(struct ahc_softc *ahc)
{
int error;
error = ahc_aic7880_setup(ahc);
if (error == 0)
error = ahc_aha398XX_setup(ahc);
return (error);
}
static int
ahc_aic7890_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
uint8_t rev;
pci = ahc->dev_softc;
ahc->channel = 'A';
ahc->chip = AHC_AIC7890;
ahc->features = AHC_AIC7890_FE;
ahc->flags |= AHC_NEWEEPROM_FMT;
rev = ahc_pci_read_config(pci, PCIR_REVID, /*bytes*/1);
if (rev == 0)
ahc->bugs |= AHC_AUTOFLUSH_BUG|AHC_CACHETHEN_BUG;
ahc->instruction_ram_size = 768;
return (0);
}
static int
ahc_aic7892_setup(struct ahc_softc *ahc)
{
ahc->channel = 'A';
ahc->chip = AHC_AIC7892;
ahc->features = AHC_AIC7892_FE;
ahc->flags |= AHC_NEWEEPROM_FMT;
ahc->bugs |= AHC_SCBCHAN_UPLOAD_BUG;
ahc->instruction_ram_size = 1024;
return (0);
}
static int
ahc_aic7895_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
uint8_t rev;
pci = ahc->dev_softc;
ahc->channel = ahc_get_pci_function(pci) == 1 ? 'B' : 'A';
/*
* The 'C' revision of the aic7895 has a few additional features.
*/
rev = ahc_pci_read_config(pci, PCIR_REVID, /*bytes*/1);
if (rev >= 4) {
ahc->chip = AHC_AIC7895C;
ahc->features = AHC_AIC7895C_FE;
} else {
u_int command;
ahc->chip = AHC_AIC7895;
ahc->features = AHC_AIC7895_FE;
/*
* The BIOS disables the use of MWI transactions
* since it does not have the MWI bug work around
* we have. Disabling MWI reduces performance, so
* turn it on again.
*/
command = ahc_pci_read_config(pci, PCIR_COMMAND, /*bytes*/1);
command |= PCIM_CMD_MWRICEN;
ahc_pci_write_config(pci, PCIR_COMMAND, command, /*bytes*/1);
ahc->bugs |= AHC_PCI_MWI_BUG;
}
/*
* XXX Does CACHETHEN really not work??? What about PCI retry?
* on C level chips. Need to test, but for now, play it safe.
*/
ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_PCI_2_1_RETRY_BUG
| AHC_CACHETHEN_BUG;
#if 0
uint32_t devconfig;
/*
* Cachesize must also be zero due to stray DAC
* problem when sitting behind some bridges.
*/
ahc_pci_write_config(pci, CSIZE_LATTIME, 0, /*bytes*/1);
devconfig = ahc_pci_read_config(pci, DEVCONFIG, /*bytes*/1);
devconfig |= MRDCEN;
ahc_pci_write_config(pci, DEVCONFIG, devconfig, /*bytes*/1);
#endif
ahc->flags |= AHC_NEWEEPROM_FMT;
ahc->instruction_ram_size = 512;
return (0);
}
static int
ahc_aic7895h_setup(struct ahc_softc *ahc)
{
int error = ahc_aic7895_setup(ahc);
ahc->features |= AHC_HVD;
return error;
}
static int
ahc_aic7896_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
pci = ahc->dev_softc;
ahc->channel = ahc_get_pci_function(pci) == 1 ? 'B' : 'A';
ahc->chip = AHC_AIC7896;
ahc->features = AHC_AIC7896_FE;
ahc->flags |= AHC_NEWEEPROM_FMT;
ahc->bugs |= AHC_CACHETHEN_DIS_BUG;
ahc->instruction_ram_size = 768;
return (0);
}
static int
ahc_aic7899_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
pci = ahc->dev_softc;
ahc->channel = ahc_get_pci_function(pci) == 1 ? 'B' : 'A';
ahc->chip = AHC_AIC7899;
ahc->features = AHC_AIC7899_FE;
ahc->flags |= AHC_NEWEEPROM_FMT;
ahc->bugs |= AHC_SCBCHAN_UPLOAD_BUG;
ahc->instruction_ram_size = 1024;
return (0);
}
static int
ahc_aha29160C_setup(struct ahc_softc *ahc)
{
int error;
error = ahc_aic7899_setup(ahc);
if (error != 0)
return (error);
ahc->features |= AHC_REMOVABLE;
return (0);
}
static int
ahc_raid_setup(struct ahc_softc *ahc)
{
printk("RAID functionality unsupported\n");
return (ENXIO);
}
static int
ahc_aha394XX_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
pci = ahc->dev_softc;
switch (ahc_get_pci_slot(pci)) {
case AHC_394X_SLOT_CHANNEL_A:
ahc->channel = 'A';
break;
case AHC_394X_SLOT_CHANNEL_B:
ahc->channel = 'B';
break;
default:
printk("adapter at unexpected slot %d\n"
"unable to map to a channel\n",
ahc_get_pci_slot(pci));
ahc->channel = 'A';
}
return (0);
}
static int
ahc_aha398XX_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
pci = ahc->dev_softc;
switch (ahc_get_pci_slot(pci)) {
case AHC_398X_SLOT_CHANNEL_A:
ahc->channel = 'A';
break;
case AHC_398X_SLOT_CHANNEL_B:
ahc->channel = 'B';
break;
case AHC_398X_SLOT_CHANNEL_C:
ahc->channel = 'C';
break;
default:
printk("adapter at unexpected slot %d\n"
"unable to map to a channel\n",
ahc_get_pci_slot(pci));
ahc->channel = 'A';
break;
}
ahc->flags |= AHC_LARGE_SEEPROM;
return (0);
}
static int
ahc_aha494XX_setup(struct ahc_softc *ahc)
{
ahc_dev_softc_t pci;
pci = ahc->dev_softc;
switch (ahc_get_pci_slot(pci)) {
case AHC_494X_SLOT_CHANNEL_A:
ahc->channel = 'A';
break;
case AHC_494X_SLOT_CHANNEL_B:
ahc->channel = 'B';
break;
case AHC_494X_SLOT_CHANNEL_C:
ahc->channel = 'C';
break;
case AHC_494X_SLOT_CHANNEL_D:
ahc->channel = 'D';
break;
default:
printk("adapter at unexpected slot %d\n"
"unable to map to a channel\n",
ahc_get_pci_slot(pci));
ahc->channel = 'A';
}
ahc->flags |= AHC_LARGE_SEEPROM;
return (0);
}
|
evolver56k/xpenology
|
drivers/scsi/aic7xxx/aic7xxx_pci.c
|
C
|
gpl-2.0
| 61,833
|
/*
* Copyright (C) 2011-2014 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/>
*
* 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/>.
*/
#include "Common.h"
#include "DatabaseEnv.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Opcodes.h"
#include "Log.h"
#include "UpdateMask.h"
#include "World.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "Pet.h"
#include "Unit.h"
#include "Totem.h"
#include "Spell.h"
#include "DynamicObject.h"
#include "Guild.h"
#include "Group.h"
#include "UpdateData.h"
#include "MapManager.h"
#include "ObjectAccessor.h"
#include "CellImpl.h"
#include "SharedDefines.h"
#include "LootMgr.h"
#include "VMapFactory.h"
#include "Battleground.h"
#include "Util.h"
#include "TemporarySummon.h"
#include "Vehicle.h"
#include "SpellAuraEffects.h"
#include "ScriptMgr.h"
#include "ConditionMgr.h"
#include "DisableMgr.h"
#include "SpellScript.h"
#include "InstanceScript.h"
#include "SpellInfo.h"
#include "DB2Stores.h"
#include "Battlefield.h"
#include "BattlefieldMgr.h"
extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
SpellDestination::SpellDestination()
{
_position.Relocate(0, 0, 0, 0);
_transportGUID = 0;
_transportOffset.Relocate(0, 0, 0, 0);
}
SpellDestination::SpellDestination(float x, float y, float z, float orientation, uint32 mapId)
{
_position.Relocate(x, y, z, orientation);
_transportGUID = 0;
_position.m_mapId = mapId;
}
SpellDestination::SpellDestination(Position const& pos)
{
_position.Relocate(pos);
_transportGUID = 0;
}
SpellDestination::SpellDestination(WorldObject const& wObj)
{
_transportGUID = wObj.GetTransGUID();
_transportOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO());
_position.Relocate(wObj);
_position.SetOrientation(wObj.GetOrientation());
}
SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0), m_strTarget()
{
m_objectTarget = NULL;
m_itemTarget = NULL;
m_objectTargetGUID = 0;
m_itemTargetGUID = 0;
m_itemTargetEntry = 0;
m_targetMask = 0;
}
SpellCastTargets::SpellCastTargets(Unit* caster, uint32 targetMask, uint64 targetGuid, uint64 itemTargetGuid, uint64 srcTransportGuid, uint64 destTransportGuid, Position srcPos, Position destPos, float elevation, float missileSpeed, std::string targetString) :
m_targetMask(targetMask), m_objectTargetGUID(targetGuid), m_itemTargetGUID(itemTargetGuid), m_elevation(elevation), m_speed(missileSpeed), m_strTarget(targetString)
{
m_objectTarget = NULL;
m_itemTarget = NULL;
m_itemTargetEntry = 0;
m_src._transportGUID = srcTransportGuid;
if (m_src._transportGUID)
m_src._transportOffset.Relocate(srcPos);
else
m_src._position.Relocate(srcPos);
m_dst._transportGUID = destTransportGuid;
if (m_dst._transportGUID)
m_dst._transportOffset.Relocate(destPos);
else
m_dst._position.Relocate(destPos);
Update(caster);
}
SpellCastTargets::~SpellCastTargets() { }
void SpellCastTargets::Read(ByteBuffer& data, Unit* caster)
{
data >> m_targetMask;
if (m_targetMask == TARGET_FLAG_NONE)
return;
if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_UNIT_MINIPET | TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_CORPSE_ALLY))
data.readPackGUID(m_objectTargetGUID);
if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM))
data.readPackGUID(m_itemTargetGUID);
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
{
data.readPackGUID(m_src._transportGUID);
if (m_src._transportGUID)
data >> m_src._transportOffset.PositionXYZStream();
else
data >> m_src._position.PositionXYZStream();
}
else
{
m_src._transportGUID = caster->GetTransGUID();
if (m_src._transportGUID)
m_src._transportOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO());
else
m_src._position.Relocate(caster);
}
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
{
data.readPackGUID(m_dst._transportGUID);
if (m_dst._transportGUID)
data >> m_dst._transportOffset.PositionXYZStream();
else
data >> m_dst._position.PositionXYZStream();
}
else
{
m_dst._transportGUID = caster->GetTransGUID();
if (m_dst._transportGUID)
m_dst._transportOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO());
else
m_dst._position.Relocate(caster);
}
if (m_targetMask & TARGET_FLAG_STRING)
data >> m_strTarget;
Update(caster);
}
void SpellCastTargets::Write(ByteBuffer& data)
{
data << uint32(m_targetMask);
if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_CORPSE_ALLY | TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_UNIT_MINIPET))
data.appendPackGUID(m_objectTargetGUID);
if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM))
{
if (m_itemTarget)
data.append(m_itemTarget->GetPackGUID());
else
data << uint8(0);
}
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
{
data.appendPackGUID(m_src._transportGUID); // relative position guid here - transport for example
if (m_src._transportGUID)
data << m_src._transportOffset.PositionXYZStream();
else
data << m_src._position.PositionXYZStream();
}
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
{
data.appendPackGUID(m_dst._transportGUID); // relative position guid here - transport for example
if (m_dst._transportGUID)
data << m_dst._transportOffset.PositionXYZStream();
else
data << m_dst._position.PositionXYZStream();
}
if (m_targetMask & TARGET_FLAG_STRING)
data << m_strTarget;
}
uint64 SpellCastTargets::GetUnitTargetGUID() const
{
switch (GUID_HIPART(m_objectTargetGUID))
{
case HIGHGUID_PLAYER:
case HIGHGUID_VEHICLE:
case HIGHGUID_UNIT:
case HIGHGUID_PET:
return m_objectTargetGUID;
default:
return 0LL;
}
}
Unit* SpellCastTargets::GetUnitTarget() const
{
if (m_objectTarget)
return m_objectTarget->ToUnit();
return NULL;
}
void SpellCastTargets::SetUnitTarget(Unit* target)
{
if (!target)
return;
m_objectTarget = target;
m_objectTargetGUID = target->GetGUID();
m_targetMask |= TARGET_FLAG_UNIT;
}
uint64 SpellCastTargets::GetGOTargetGUID() const
{
switch (GUID_HIPART(m_objectTargetGUID))
{
case HIGHGUID_TRANSPORT:
case HIGHGUID_MO_TRANSPORT:
case HIGHGUID_GAMEOBJECT:
return m_objectTargetGUID;
default:
return 0LL;
}
}
GameObject* SpellCastTargets::GetGOTarget() const
{
if (m_objectTarget)
return m_objectTarget->ToGameObject();
return NULL;
}
void SpellCastTargets::SetGOTarget(GameObject* target)
{
if (!target)
return;
m_objectTarget = target;
m_objectTargetGUID = target->GetGUID();
m_targetMask |= TARGET_FLAG_GAMEOBJECT;
}
uint64 SpellCastTargets::GetCorpseTargetGUID() const
{
switch (GUID_HIPART(m_objectTargetGUID))
{
case HIGHGUID_CORPSE:
return m_objectTargetGUID;
default:
return 0LL;
}
}
Corpse* SpellCastTargets::GetCorpseTarget() const
{
if (m_objectTarget)
return m_objectTarget->ToCorpse();
return NULL;
}
WorldObject* SpellCastTargets::GetObjectTarget() const
{
return m_objectTarget;
}
uint64 SpellCastTargets::GetObjectTargetGUID() const
{
return m_objectTargetGUID;
}
void SpellCastTargets::RemoveObjectTarget()
{
m_objectTarget = NULL;
m_objectTargetGUID = 0LL;
m_targetMask &= ~(TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK);
}
void SpellCastTargets::SetItemTarget(Item* item)
{
if (!item)
return;
m_itemTarget = item;
m_itemTargetGUID = item->GetGUID();
m_itemTargetEntry = item->GetEntry();
m_targetMask |= TARGET_FLAG_ITEM;
}
void SpellCastTargets::SetTradeItemTarget(Player* caster)
{
m_itemTargetGUID = uint64(TRADE_SLOT_NONTRADED);
m_itemTargetEntry = 0;
m_targetMask |= TARGET_FLAG_TRADE_ITEM;
Update(caster);
}
void SpellCastTargets::UpdateTradeSlotItem()
{
if (m_itemTarget && (m_targetMask & TARGET_FLAG_TRADE_ITEM))
{
m_itemTargetGUID = m_itemTarget->GetGUID();
m_itemTargetEntry = m_itemTarget->GetEntry();
}
}
SpellDestination const* SpellCastTargets::GetSrc() const
{
return &m_src;
}
Position const* SpellCastTargets::GetSrcPos() const
{
return &m_src._position;
}
void SpellCastTargets::SetSrc(float x, float y, float z)
{
m_src = SpellDestination(x, y, z);
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::SetSrc(Position const& pos)
{
m_src = SpellDestination(pos);
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::SetSrc(WorldObject const& wObj)
{
m_src = SpellDestination(wObj);
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::ModSrc(Position const& pos)
{
ASSERT(m_targetMask & TARGET_FLAG_SOURCE_LOCATION);
if (m_src._transportGUID)
{
Position offset;
m_src._position.GetPositionOffsetTo(pos, offset);
m_src._transportOffset.RelocateOffset(offset);
}
m_src._position.Relocate(pos);
}
void SpellCastTargets::RemoveSrc()
{
m_targetMask &= ~(TARGET_FLAG_SOURCE_LOCATION);
}
SpellDestination const* SpellCastTargets::GetDst() const
{
return &m_dst;
}
WorldLocation const* SpellCastTargets::GetDstPos() const
{
return &m_dst._position;
}
void SpellCastTargets::SetDst(float x, float y, float z, float orientation, uint32 mapId)
{
m_dst = SpellDestination(x, y, z, orientation, mapId);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(Position const& pos)
{
m_dst = SpellDestination(pos);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(WorldObject const& wObj)
{
m_dst = SpellDestination(wObj);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(SpellCastTargets const& spellTargets)
{
m_dst = spellTargets.m_dst;
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::ModDst(Position const& pos)
{
ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION);
if (m_dst._transportGUID)
{
Position offset;
m_dst._position.GetPositionOffsetTo(pos, offset);
m_dst._transportOffset.RelocateOffset(offset);
}
m_dst._position.Relocate(pos);
}
void SpellCastTargets::RemoveDst()
{
m_targetMask &= ~(TARGET_FLAG_DEST_LOCATION);
}
void SpellCastTargets::Update(Unit* caster)
{
m_objectTarget = m_objectTargetGUID ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : NULL;
m_itemTarget = NULL;
if (caster->GetTypeId() == TYPEID_PLAYER)
{
Player* player = caster->ToPlayer();
if (m_targetMask & TARGET_FLAG_ITEM)
m_itemTarget = player->GetItemByGuid(m_itemTargetGUID);
else if (m_targetMask & TARGET_FLAG_TRADE_ITEM)
if (m_itemTargetGUID == TRADE_SLOT_NONTRADED) // here it is not guid but slot. Also prevents hacking slots
if (TradeData* pTrade = player->GetTradeData())
m_itemTarget = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED);
if (m_itemTarget)
m_itemTargetEntry = m_itemTarget->GetEntry();
}
// update positions by transport move
if (HasSrc() && m_src._transportGUID)
{
if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_src._transportGUID))
{
m_src._position.Relocate(transport);
m_src._position.RelocateOffset(m_src._transportOffset);
}
}
if (HasDst() && m_dst._transportGUID)
{
if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_dst._transportGUID))
{
m_dst._position.Relocate(transport);
m_dst._position.RelocateOffset(m_dst._transportOffset);
}
}
}
void SpellCastTargets::OutDebug() const
{
if (!m_targetMask)
TC_LOG_INFO("spells", "No targets");
TC_LOG_INFO("spells", "target mask: %u", m_targetMask);
if (m_targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK))
TC_LOG_INFO("spells", "Object target: " UI64FMTD, m_objectTargetGUID);
if (m_targetMask & TARGET_FLAG_ITEM)
TC_LOG_INFO("spells", "Item target: " UI64FMTD, m_itemTargetGUID);
if (m_targetMask & TARGET_FLAG_TRADE_ITEM)
TC_LOG_INFO("spells", "Trade item target: " UI64FMTD, m_itemTargetGUID);
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
TC_LOG_INFO("spells", "Source location: transport guid:" UI64FMTD " trans offset: %s position: %s", m_src._transportGUID, m_src._transportOffset.ToString().c_str(), m_src._position.ToString().c_str());
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
TC_LOG_INFO("spells", "Destination location: transport guid:" UI64FMTD " trans offset: %s position: %s", m_dst._transportGUID, m_dst._transportOffset.ToString().c_str(), m_dst._position.ToString().c_str());
if (m_targetMask & TARGET_FLAG_STRING)
TC_LOG_INFO("spells", "String: %s", m_strTarget.c_str());
TC_LOG_INFO("spells", "speed: %f", m_speed);
TC_LOG_INFO("spells", "elevation: %f", m_elevation);
}
SpellValue::SpellValue(SpellInfo const* proto)
{
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
EffectBasePoints[i] = proto->Effects[i].BasePoints;
MaxAffectedTargets = proto->MaxAffectedTargets;
RadiusMod = 1.0f;
AuraStackAmount = 1;
}
Spell::Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, uint64 originalCasterGUID, bool skipCheck) :
m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, caster)),
m_caster((info->AttributesEx6 & SPELL_ATTR6_CAST_BY_CHARMER && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster)
, m_spellValue(new SpellValue(m_spellInfo)), m_preGeneratedPath(PathGenerator(m_caster))
{
m_customError = SPELL_CUSTOM_ERROR_NONE;
m_skipCheck = skipCheck;
m_selfContainer = NULL;
m_referencedFromCurrentSpell = false;
m_executedCurrently = false;
m_needComboPoints = m_spellInfo->NeedsComboPoints();
m_comboPointGain = 0;
m_delayStart = 0;
m_delayAtDamageCount = 0;
m_applyMultiplierMask = 0;
m_auraScaleMask = 0;
// Get data for type of attack
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE:
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND)
m_attackType = OFF_ATTACK;
else
m_attackType = BASE_ATTACK;
break;
case SPELL_DAMAGE_CLASS_RANGED:
m_attackType = m_spellInfo->IsRangedWeaponSpell() ? RANGED_ATTACK : BASE_ATTACK;
break;
default:
// Wands
if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG)
m_attackType = RANGED_ATTACK;
else
m_attackType = BASE_ATTACK;
break;
}
m_spellSchoolMask = info->GetSchoolMask(); // Can be override for some spell (wand shoot for example)
if (m_attackType == RANGED_ATTACK)
// wand case
if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK))
m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetTemplate()->DamageType);
if (originalCasterGUID)
m_originalCasterGUID = originalCasterGUID;
else
m_originalCasterGUID = m_caster->GetGUID();
if (m_originalCasterGUID == m_caster->GetGUID())
m_originalCaster = m_caster;
else
{
m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
if (m_originalCaster && !m_originalCaster->IsInWorld())
m_originalCaster = NULL;
}
m_spellState = SPELL_STATE_NULL;
_triggeredCastFlags = triggerFlags;
if (info->AttributesEx4 & SPELL_ATTR4_TRIGGERED)
_triggeredCastFlags = TRIGGERED_FULL_MASK;
m_CastItem = NULL;
m_castItemGUID = 0;
unitTarget = NULL;
itemTarget = NULL;
gameObjTarget = NULL;
focusObject = NULL;
m_cast_count = 0;
m_glyphIndex = 0;
m_preCastSpell = 0;
m_triggeredByAuraSpell = NULL;
m_spellAura = NULL;
//Auto Shot & Shoot (wand)
m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell();
m_runesState = 0;
m_powerCost = 0; // setup to correct value in Spell::prepare, must not be used before.
m_casttime = 0; // setup to correct value in Spell::prepare, must not be used before.
m_timer = 0; // will set to castime in prepare
m_channelTargetEffectMask = 0;
// Determine if spell can be reflected back to the caster
// Patch 1.2 notes: Spell Reflection no longer reflects abilities
m_canReflect = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->Attributes & SPELL_ATTR0_ABILITY)
&& !(m_spellInfo->AttributesEx & SPELL_ATTR1_CANT_BE_REFLECTED) && !(m_spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
&& !m_spellInfo->IsPassive() && !m_spellInfo->IsPositive();
CleanupTargetList();
memset(m_effectExecuteData, 0, MAX_SPELL_EFFECTS * sizeof(ByteBuffer*));
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
m_destTargets[i] = SpellDestination(*m_caster);
}
Spell::~Spell()
{
// unload scripts
while (!m_loadedScripts.empty())
{
std::list<SpellScript*>::iterator itr = m_loadedScripts.begin();
(*itr)->_Unload();
delete (*itr);
m_loadedScripts.erase(itr);
}
if (m_referencedFromCurrentSpell && m_selfContainer && *m_selfContainer == this)
{
// Clean the reference to avoid later crash.
// If this error is repeating, we may have to add an ASSERT to better track down how we get into this case.
TC_LOG_ERROR("spells", "SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id);
*m_selfContainer = NULL;
}
if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER)
ASSERT(m_caster->ToPlayer()->m_spellModTakingSpell != this);
delete m_spellValue;
CheckEffectExecuteData();
}
void Spell::InitExplicitTargets(SpellCastTargets const& targets)
{
m_targets = targets;
// this function tries to correct spell explicit targets for spell
// client doesn't send explicit targets correctly sometimes - we need to fix such spells serverside
// this also makes sure that we correctly send explicit targets to client (removes redundant data)
uint32 neededTargets = m_spellInfo->GetExplicitTargetMask();
if (WorldObject* target = m_targets.GetObjectTarget())
{
// check if object target is valid with needed target flags
// for unit case allow corpse target mask because player with not released corpse is a unit target
if ((target->ToUnit() && !(neededTargets & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK)))
|| (target->ToGameObject() && !(neededTargets & TARGET_FLAG_GAMEOBJECT_MASK))
|| (target->ToCorpse() && !(neededTargets & TARGET_FLAG_CORPSE_MASK)))
m_targets.RemoveObjectTarget();
}
else
{
// try to select correct unit target if not provided by client or by serverside cast
if (neededTargets & (TARGET_FLAG_UNIT_MASK))
{
Unit* unit = NULL;
// try to use player selection as a target
if (Player* playerCaster = m_caster->ToPlayer())
{
// selection has to be found and to be valid target for the spell
if (Unit* selectedUnit = ObjectAccessor::GetUnit(*m_caster, playerCaster->GetTarget()))
if (m_spellInfo->CheckExplicitTarget(m_caster, selectedUnit) == SPELL_CAST_OK)
unit = selectedUnit;
}
// try to use attacked unit as a target
else if ((m_caster->GetTypeId() == TYPEID_UNIT) && neededTargets & (TARGET_FLAG_UNIT_ENEMY | TARGET_FLAG_UNIT))
unit = m_caster->GetVictim();
// didn't find anything - let's use self as target
if (!unit && neededTargets & (TARGET_FLAG_UNIT_RAID | TARGET_FLAG_UNIT_PARTY | TARGET_FLAG_UNIT_ALLY))
unit = m_caster;
m_targets.SetUnitTarget(unit);
}
}
// check if spell needs dst target
if (neededTargets & TARGET_FLAG_DEST_LOCATION)
{
// and target isn't set
if (!m_targets.HasDst())
{
// try to use unit target if provided
if (WorldObject* target = targets.GetObjectTarget())
m_targets.SetDst(*target);
// or use self if not available
else
m_targets.SetDst(*m_caster);
}
}
else
m_targets.RemoveDst();
if (neededTargets & TARGET_FLAG_SOURCE_LOCATION)
{
if (!targets.HasSrc())
m_targets.SetSrc(*m_caster);
}
else
m_targets.RemoveSrc();
}
void Spell::SelectExplicitTargets()
{
// here go all explicit target changes made to explicit targets after spell prepare phase is finished
if (Unit* target = m_targets.GetUnitTarget())
{
// check for explicit target redirection, for Grounding Totem for example
if (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT_ENEMY
|| (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT && !m_spellInfo->IsPositive()))
{
Unit* redirect;
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MAGIC:
redirect = m_caster->GetMagicHitRedirectTarget(target, m_spellInfo);
break;
case SPELL_DAMAGE_CLASS_MELEE:
case SPELL_DAMAGE_CLASS_RANGED:
redirect = m_caster->GetMeleeHitRedirectTarget(target, m_spellInfo);
break;
default:
redirect = NULL;
break;
}
if (redirect && (redirect != target))
m_targets.SetUnitTarget(redirect);
}
}
}
void Spell::SelectSpellTargets()
{
// select targets for cast phase
SelectExplicitTargets();
uint32 processedAreaEffectsMask = 0;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// not call for empty effect.
// Also some spells use not used effect targets for store targets for dummy effect in triggered spells
if (!m_spellInfo->Effects[i].IsEffect())
continue;
// set expected type of implicit targets to be sent to client
uint32 implicitTargetMask = GetTargetFlagMask(m_spellInfo->Effects[i].TargetA.GetObjectType()) | GetTargetFlagMask(m_spellInfo->Effects[i].TargetB.GetObjectType());
if (implicitTargetMask & TARGET_FLAG_UNIT)
m_targets.SetTargetFlag(TARGET_FLAG_UNIT);
if (implicitTargetMask & (TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_GAMEOBJECT_ITEM))
m_targets.SetTargetFlag(TARGET_FLAG_GAMEOBJECT);
SelectEffectImplicitTargets(SpellEffIndex(i), m_spellInfo->Effects[i].TargetA, processedAreaEffectsMask);
SelectEffectImplicitTargets(SpellEffIndex(i), m_spellInfo->Effects[i].TargetB, processedAreaEffectsMask);
// Select targets of effect based on effect type
// those are used when no valid target could be added for spell effect based on spell target type
// some spell effects use explicit target as a default target added to target map (like SPELL_EFFECT_LEARN_SPELL)
// some spell effects add target to target map only when target type specified (like SPELL_EFFECT_WEAPON)
// some spell effects don't add anything to target map (confirmed with sniffs) (like SPELL_EFFECT_DESTROY_ALL_TOTEMS)
SelectEffectTypeImplicitTargets(i);
if (m_targets.HasDst())
AddDestTarget(*m_targets.GetDst(), i);
if (m_spellInfo->IsChanneled())
{
uint8 mask = (1 << i);
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->effectMask & mask)
{
m_channelTargetEffectMask |= mask;
break;
}
}
}
else if (m_auraScaleMask)
{
bool checkLvl = !m_UniqueTargetInfo.empty();
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();)
{
// remove targets which did not pass min level check
if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask)
{
// Do not check for selfcast
if (!ihit->scaleAura && ihit->targetGUID != m_caster->GetGUID())
{
m_UniqueTargetInfo.erase(ihit++);
continue;
}
}
++ihit;
}
if (checkLvl && m_UniqueTargetInfo.empty())
{
SendCastResult(SPELL_FAILED_LOWLEVEL);
finish(false);
}
}
}
if (m_targets.HasDst())
{
if (m_targets.HasTraj())
{
float speed = m_targets.GetSpeedXY();
if (speed > 0.0f)
m_delayMoment = (uint64)floor(m_targets.GetDist2d() / speed * 1000.0f);
}
else if (m_spellInfo->Speed > 0.0f)
{
float dist = m_caster->GetDistance(*m_targets.GetDstPos());
if (!(m_spellInfo->AttributesEx9 & SPELL_ATTR9_SPECIAL_DELAY_CALCULATION))
m_delayMoment = uint64(floor(dist / m_spellInfo->Speed * 1000.0f));
else
m_delayMoment = uint64(m_spellInfo->Speed * 1000.0f);
}
}
}
void Spell::SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32& processedEffectMask)
{
if (!targetType.GetTarget())
return;
uint32 effectMask = 1 << effIndex;
// set the same target list for all effects
// some spells appear to need this, however this requires more research
switch (targetType.GetSelectionCategory())
{
case TARGET_SELECT_CATEGORY_NEARBY:
case TARGET_SELECT_CATEGORY_CONE:
case TARGET_SELECT_CATEGORY_AREA:
// targets for effect already selected
if (effectMask & processedEffectMask)
return;
// choose which targets we can select at once
for (uint32 j = effIndex + 1; j < MAX_SPELL_EFFECTS; ++j)
{
SpellEffectInfo const* effects = GetSpellInfo()->Effects;
if (effects[j].IsEffect() &&
effects[effIndex].TargetA.GetTarget() == effects[j].TargetA.GetTarget() &&
effects[effIndex].TargetB.GetTarget() == effects[j].TargetB.GetTarget() &&
effects[effIndex].ImplicitTargetConditions == effects[j].ImplicitTargetConditions &&
effects[effIndex].CalcRadius(m_caster) == effects[j].CalcRadius(m_caster) &&
CheckScriptEffectImplicitTargets(effIndex, j))
{
effectMask |= 1 << j;
}
}
processedEffectMask |= effectMask;
break;
default:
break;
}
switch (targetType.GetSelectionCategory())
{
case TARGET_SELECT_CATEGORY_CHANNEL:
SelectImplicitChannelTargets(effIndex, targetType);
break;
case TARGET_SELECT_CATEGORY_NEARBY:
SelectImplicitNearbyTargets(effIndex, targetType, effectMask);
break;
case TARGET_SELECT_CATEGORY_CONE:
SelectImplicitConeTargets(effIndex, targetType, effectMask);
break;
case TARGET_SELECT_CATEGORY_AREA:
SelectImplicitAreaTargets(effIndex, targetType, effectMask);
break;
case TARGET_SELECT_CATEGORY_DEFAULT:
switch (targetType.GetObjectType())
{
case TARGET_OBJECT_TYPE_SRC:
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_CASTER:
m_targets.SetSrc(*m_caster);
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_SRC");
break;
}
break;
case TARGET_OBJECT_TYPE_DEST:
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_CASTER:
SelectImplicitCasterDestTargets(effIndex, targetType);
break;
case TARGET_REFERENCE_TYPE_TARGET:
SelectImplicitTargetDestTargets(effIndex, targetType);
break;
case TARGET_REFERENCE_TYPE_DEST:
SelectImplicitDestDestTargets(effIndex, targetType);
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_DEST");
break;
}
break;
default:
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_CASTER:
SelectImplicitCasterObjectTargets(effIndex, targetType);
break;
case TARGET_REFERENCE_TYPE_TARGET:
SelectImplicitTargetObjectTargets(effIndex, targetType);
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT");
break;
}
break;
}
break;
case TARGET_SELECT_CATEGORY_NYI:
TC_LOG_DEBUG("spells", "SPELL: target type %u, found in spellID %u, effect %u is not implemented yet!", m_spellInfo->Id, effIndex, targetType.GetTarget());
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target category");
break;
}
}
void Spell::SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER)
{
ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target reference type");
return;
}
Spell* channeledSpell = m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL);
if (!channeledSpell)
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitChannelTargets: cannot find channel spell for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
return;
}
switch (targetType.GetTarget())
{
case TARGET_UNIT_CHANNEL_TARGET:
{
WorldObject* target = ObjectAccessor::GetUnit(*m_caster, m_originalCaster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT));
CallScriptObjectTargetSelectHandlers(target, effIndex);
// unit target may be no longer avalible - teleported out of map for example
if (target && target->ToUnit())
AddUnitTarget(target->ToUnit(), 1 << effIndex);
else
TC_LOG_DEBUG("spells", "SPELL: cannot find channel spell target for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
break;
}
case TARGET_DEST_CHANNEL_TARGET:
if (channeledSpell->m_targets.HasDst())
m_targets.SetDst(channeledSpell->m_targets);
else if (WorldObject* target = ObjectAccessor::GetWorldObject(*m_caster, m_originalCaster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT)))
{
CallScriptObjectTargetSelectHandlers(target, effIndex);
if (target)
m_targets.SetDst(*target);
}
else
TC_LOG_DEBUG("spells", "SPELL: cannot find channel spell destination for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
break;
case TARGET_DEST_CHANNEL_CASTER:
m_targets.SetDst(*channeledSpell->GetCaster());
break;
default:
ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target type");
break;
}
}
void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask)
{
if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER)
{
ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target reference type");
return;
}
float range = 0.0f;
switch (targetType.GetCheckType())
{
case TARGET_CHECK_ENEMY:
range = m_spellInfo->GetMaxRange(false, m_caster, this);
break;
case TARGET_CHECK_ALLY:
case TARGET_CHECK_PARTY:
case TARGET_CHECK_RAID:
case TARGET_CHECK_RAID_CLASS:
range = m_spellInfo->GetMaxRange(true, m_caster, this);
break;
case TARGET_CHECK_ENTRY:
case TARGET_CHECK_DEFAULT:
range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive(), m_caster, this);
break;
default:
ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented selection check type");
break;
}
ConditionList* condList = m_spellInfo->Effects[effIndex].ImplicitTargetConditions;
// handle emergency case - try to use other provided targets if no conditions provided
if (targetType.GetCheckType() == TARGET_CHECK_ENTRY && (!condList || condList->empty()))
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: no conditions entry for target with TARGET_CHECK_ENTRY of spell ID %u, effect %u - selecting default targets", m_spellInfo->Id, effIndex);
switch (targetType.GetObjectType())
{
case TARGET_OBJECT_TYPE_GOBJ:
if (m_spellInfo->RequiresSpellFocus)
{
if (focusObject)
AddGOTarget(focusObject, effMask);
return;
}
break;
case TARGET_OBJECT_TYPE_DEST:
if (m_spellInfo->RequiresSpellFocus)
{
if (focusObject)
m_targets.SetDst(*focusObject);
return;
}
break;
default:
break;
}
}
WorldObject* target = SearchNearbyTarget(range, targetType.GetObjectType(), targetType.GetCheckType(), condList);
if (!target)
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: cannot find nearby target for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
return;
}
CallScriptObjectTargetSelectHandlers(target, effIndex);
switch (targetType.GetObjectType())
{
case TARGET_OBJECT_TYPE_UNIT:
if (Unit* unitTarget = target->ToUnit())
AddUnitTarget(unitTarget, effMask, true, false);
break;
case TARGET_OBJECT_TYPE_GOBJ:
if (GameObject* gobjTarget = target->ToGameObject())
AddGOTarget(gobjTarget, effMask);
break;
case TARGET_OBJECT_TYPE_DEST:
m_targets.SetDst(*target);
break;
default:
ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target object type");
break;
}
SelectImplicitChainTargets(effIndex, targetType, target, effMask);
}
void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask)
{
if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER)
{
ASSERT(false && "Spell::SelectImplicitConeTargets: received not implemented target reference type");
return;
}
std::list<WorldObject*> targets;
SpellTargetObjectTypes objectType = targetType.GetObjectType();
SpellTargetCheckTypes selectionType = targetType.GetCheckType();
ConditionList* condList = m_spellInfo->Effects[effIndex].ImplicitTargetConditions;
float coneAngle = M_PI/2;
float radius = m_spellInfo->Effects[effIndex].CalcRadius(m_caster) * m_spellValue->RadiusMod;
if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList))
{
Trinity::WorldObjectSpellConeTargetCheck check(coneAngle, radius, m_caster, m_spellInfo, selectionType, condList);
Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellConeTargetCheck> searcher(m_caster, targets, check, containerTypeMask);
SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellConeTargetCheck> >(searcher, containerTypeMask, m_caster, m_caster, radius);
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex);
if (!targets.empty())
{
// Other special target selection goes here
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
Trinity::Containers::RandomResizeList(targets, maxTargets);
// for compability with older code - add only unit and go targets
/// @todo remove this
std::list<Unit*> unitTargets;
std::list<GameObject*> gObjTargets;
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
{
if (Unit* unitTarget = (*itr)->ToUnit())
unitTargets.push_back(unitTarget);
else if (GameObject* gObjTarget = (*itr)->ToGameObject())
gObjTargets.push_back(gObjTarget);
}
for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr)
AddUnitTarget(*itr, effMask, false);
for (std::list<GameObject*>::iterator itr = gObjTargets.begin(); itr != gObjTargets.end(); ++itr)
AddGOTarget(*itr, effMask);
}
}
}
void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask)
{
Unit* referer = NULL;
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_SRC:
case TARGET_REFERENCE_TYPE_DEST:
case TARGET_REFERENCE_TYPE_CASTER:
referer = m_caster;
break;
case TARGET_REFERENCE_TYPE_TARGET:
referer = m_targets.GetUnitTarget();
break;
case TARGET_REFERENCE_TYPE_LAST:
{
// find last added target for this effect
for (std::list<TargetInfo>::reverse_iterator ihit = m_UniqueTargetInfo.rbegin(); ihit != m_UniqueTargetInfo.rend(); ++ihit)
{
if (ihit->effectMask & (1<<effIndex))
{
referer = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
break;
}
}
break;
}
default:
ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type");
return;
}
if (!referer)
return;
Position const* center = NULL;
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_SRC:
center = m_targets.GetSrcPos();
break;
case TARGET_REFERENCE_TYPE_DEST:
center = m_targets.GetDstPos();
break;
case TARGET_REFERENCE_TYPE_CASTER:
case TARGET_REFERENCE_TYPE_TARGET:
case TARGET_REFERENCE_TYPE_LAST:
center = referer;
break;
default:
ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type");
return;
}
std::list<WorldObject*> targets;
float radius = m_spellInfo->Effects[effIndex].CalcRadius(m_caster) * m_spellValue->RadiusMod;
SearchAreaTargets(targets, radius, center, referer, targetType.GetObjectType(), targetType.GetCheckType(), m_spellInfo->Effects[effIndex].ImplicitTargetConditions);
// Custom entries
/// @todo remove those
switch (m_spellInfo->Id)
{
case 46584: // Raise Dead
{
if (Player* playerCaster = m_caster->ToPlayer())
{
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
{
switch ((*itr)->GetTypeId())
{
case TYPEID_UNIT:
case TYPEID_PLAYER:
{
Unit* unitTarget = (*itr)->ToUnit();
if (unitTarget->IsAlive() || !playerCaster->isHonorOrXPTarget(unitTarget)
|| ((unitTarget->GetCreatureTypeMask() & (1 << (CREATURE_TYPE_HUMANOID-1))) == 0)
|| (unitTarget->GetDisplayId() != unitTarget->GetNativeDisplayId()))
break;
AddUnitTarget(unitTarget, effMask, false);
// no break;
}
case TYPEID_CORPSE: // wont work until corpses are allowed in target lists, but at least will send dest in packet
m_targets.SetDst(*(*itr));
return; // nothing more to do here
default:
break;
}
}
}
return; // don't add targets to target map
}
// Corpse Explosion
case 49158:
case 51325:
case 51326:
case 51327:
case 51328:
// check if our target is not valid (spell can target ghoul or dead unit)
if (!(m_targets.GetUnitTarget() && m_targets.GetUnitTarget()->GetDisplayId() == m_targets.GetUnitTarget()->GetNativeDisplayId() &&
((m_targets.GetUnitTarget()->GetEntry() == 26125 && m_targets.GetUnitTarget()->GetOwnerGUID() == m_caster->GetGUID())
|| m_targets.GetUnitTarget()->isDead())))
{
// remove existing targets
CleanupTargetList();
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
{
switch ((*itr)->GetTypeId())
{
case TYPEID_UNIT:
case TYPEID_PLAYER:
if (!(*itr)->ToUnit()->isDead())
break;
AddUnitTarget((*itr)->ToUnit(), 1 << effIndex, false);
return;
default:
break;
}
}
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true);
SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW);
finish(false);
}
return;
default:
break;
}
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex);
std::list<Unit*> unitTargets;
std::list<GameObject*> gObjTargets;
// for compability with older code - add only unit and go targets
/// @todo remove this
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
{
if (Unit* unitTarget = (*itr)->ToUnit())
unitTargets.push_back(unitTarget);
else if (GameObject* gObjTarget = (*itr)->ToGameObject())
gObjTargets.push_back(gObjTarget);
}
if (!unitTargets.empty())
{
// Special target selection for smart heals and energizes
uint32 maxSize = 0;
int32 power = -1;
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (m_spellInfo->Id)
{
case 52759: // Ancestral Awakening
case 71610: // Echoes of Light (Althor's Abacus normal version)
case 71641: // Echoes of Light (Althor's Abacus heroic version)
maxSize = 1;
power = POWER_HEALTH;
break;
case 54968: // Glyph of Holy Light
maxSize = m_spellInfo->MaxAffectedTargets;
power = POWER_HEALTH;
break;
case 57669: // Replenishment
// In arenas Replenishment may only affect the caster
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->InArena())
{
unitTargets.clear();
unitTargets.push_back(m_caster);
break;
}
maxSize = 10;
power = POWER_MANA;
break;
default:
break;
}
break;
case SPELLFAMILY_PRIEST:
if (m_spellInfo->SpellFamilyFlags[0] == 0x10000000) // Circle of Healing
{
maxSize = m_caster->HasAura(55675) ? 6 : 5; // Glyph of Circle of Healing
power = POWER_HEALTH;
}
else if (m_spellInfo->Id == 64844) // Divine Hymn
{
maxSize = 3;
power = POWER_HEALTH;
}
else if (m_spellInfo->Id == 64904) // Hymn of Hope
{
maxSize = 3;
power = POWER_MANA;
}
else
break;
// Remove targets outside caster's raid
for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end();)
{
if (!(*itr)->IsInRaidWith(m_caster))
itr = unitTargets.erase(itr);
else
++itr;
}
break;
case SPELLFAMILY_DRUID:
if (m_spellInfo->SpellFamilyFlags[1] == 0x04000000) // Wild Growth
{
maxSize = m_caster->HasAura(62970) ? 6 : 5; // Glyph of Wild Growth
power = POWER_HEALTH;
}
else
break;
// Remove targets outside caster's raid
for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end();)
if (!(*itr)->IsInRaidWith(m_caster))
itr = unitTargets.erase(itr);
else
++itr;
break;
default:
break;
}
if (maxSize && power != -1)
{
if (Powers(power) == POWER_HEALTH)
{
if (unitTargets.size() > maxSize)
{
unitTargets.sort(Trinity::HealthPctOrderPred());
unitTargets.resize(maxSize);
}
}
else
{
for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end();)
if ((*itr)->getPowerType() != (Powers)power)
itr = unitTargets.erase(itr);
else
++itr;
if (unitTargets.size() > maxSize)
{
unitTargets.sort(Trinity::PowerPctOrderPred((Powers)power));
unitTargets.resize(maxSize);
}
}
}
// Other special target selection goes here
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
Trinity::Containers::RandomResizeList(unitTargets, maxTargets);
for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr)
AddUnitTarget(*itr, effMask, false);
}
if (!gObjTargets.empty())
{
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
Trinity::Containers::RandomResizeList(gObjTargets, maxTargets);
for (std::list<GameObject*>::iterator itr = gObjTargets.begin(); itr != gObjTargets.end(); ++itr)
AddGOTarget(*itr, effMask);
}
}
void Spell::SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
switch (targetType.GetTarget())
{
case TARGET_DEST_CASTER:
m_targets.SetDst(*m_caster);
return;
case TARGET_DEST_HOME:
if (Player* playerCaster = m_caster->ToPlayer())
m_targets.SetDst(playerCaster->m_homebindX, playerCaster->m_homebindY, playerCaster->m_homebindZ, playerCaster->GetOrientation(), playerCaster->m_homebindMapId);
return;
case TARGET_DEST_DB:
if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id, effIndex))
{
/// @todo fix this check
if (m_spellInfo->HasEffect(SPELL_EFFECT_TELEPORT_UNITS) || m_spellInfo->HasEffect(SPELL_EFFECT_BIND))
m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId);
else if (st->target_mapId == m_caster->GetMapId())
m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation);
}
else
{
TC_LOG_DEBUG("spells", "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id);
WorldObject* target = m_targets.GetObjectTarget();
m_targets.SetDst(target ? *target : *m_caster);
}
return;
case TARGET_DEST_CASTER_FISHING:
{
float min_dis = m_spellInfo->GetMinRange(true);
float max_dis = m_spellInfo->GetMaxRange(true);
float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis;
float x, y, z, angle;
angle = (float)rand_norm() * static_cast<float>(M_PI * 35.0f / 180.0f) - static_cast<float>(M_PI * 17.5f / 180.0f);
m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, angle);
float ground = z;
float liquidLevel = m_caster->GetMap()->GetWaterOrGroundLevel(x, y, z, &ground);
if (liquidLevel <= ground) // When there is no liquid Map::GetWaterOrGroundLevel returns ground level
{
SendCastResult(SPELL_FAILED_NOT_HERE);
SendChannelUpdate(0);
finish(false);
return;
}
if (ground + 0.75 > liquidLevel)
{
SendCastResult(SPELL_FAILED_TOO_SHALLOW);
SendChannelUpdate(0);
finish(false);
return;
}
m_targets.SetDst(x, y, liquidLevel, m_caster->GetOrientation());
return;
}
default:
break;
}
float dist;
float angle = targetType.CalcDirectionAngle();
float objSize = m_caster->GetObjectSize();
if (targetType.GetTarget() == TARGET_DEST_CASTER_SUMMON)
dist = PET_FOLLOW_DIST;
else
dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster);
if (dist < objSize)
dist = objSize;
else if (targetType.GetTarget() == TARGET_DEST_CASTER_RANDOM)
dist = objSize + (dist - objSize) * (float)rand_norm();
Position pos;
if (targetType.GetTarget() == TARGET_DEST_CASTER_FRONT_LEAP)
m_caster->GetFirstCollisionPosition(pos, dist, angle);
else
m_caster->GetNearPosition(pos, dist, angle);
m_targets.SetDst(*m_caster);
m_targets.ModDst(pos);
}
void Spell::SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
WorldObject* target = m_targets.GetObjectTarget();
switch (targetType.GetTarget())
{
case TARGET_DEST_TARGET_ENEMY:
case TARGET_DEST_TARGET_ANY:
m_targets.SetDst(*target);
return;
default:
break;
}
float angle = targetType.CalcDirectionAngle();
float objSize = target->GetObjectSize();
float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster);
if (dist < objSize)
dist = objSize;
else if (targetType.GetTarget() == TARGET_DEST_TARGET_RANDOM)
dist = objSize + (dist - objSize) * (float)rand_norm();
Position pos;
target->GetNearPosition(pos, dist, angle);
m_targets.SetDst(*target);
m_targets.ModDst(pos);
}
void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
// set destination to caster if no dest provided
// can only happen if previous destination target could not be set for some reason
// (not found nearby target, or channel target for example
// maybe we should abort the spell in such case?
if (!m_targets.HasDst())
m_targets.SetDst(*m_caster);
switch (targetType.GetTarget())
{
case TARGET_DEST_DYNOBJ_ENEMY:
case TARGET_DEST_DYNOBJ_ALLY:
case TARGET_DEST_DYNOBJ_NONE:
case TARGET_DEST_DEST:
return;
case TARGET_DEST_TRAJ:
SelectImplicitTrajTargets();
return;
default:
break;
}
float angle = targetType.CalcDirectionAngle();
float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster);
if (targetType.GetTarget() == TARGET_DEST_DEST_RANDOM)
dist *= (float)rand_norm();
Position pos = *m_targets.GetDstPos();
m_caster->MovePosition(pos, dist, angle);
m_targets.ModDst(pos);
}
void Spell::SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
WorldObject* target = NULL;
bool checkIfValid = true;
switch (targetType.GetTarget())
{
case TARGET_UNIT_CASTER:
target = m_caster;
checkIfValid = false;
break;
case TARGET_UNIT_MASTER:
target = m_caster->GetCharmerOrOwner();
break;
case TARGET_UNIT_PET:
target = m_caster->GetGuardianPet();
break;
case TARGET_UNIT_SUMMONER:
if (m_caster->IsSummon())
target = m_caster->ToTempSummon()->GetSummoner();
break;
case TARGET_UNIT_VEHICLE:
target = m_caster->GetVehicleBase();
break;
case TARGET_UNIT_PASSENGER_0:
case TARGET_UNIT_PASSENGER_1:
case TARGET_UNIT_PASSENGER_2:
case TARGET_UNIT_PASSENGER_3:
case TARGET_UNIT_PASSENGER_4:
case TARGET_UNIT_PASSENGER_5:
case TARGET_UNIT_PASSENGER_6:
case TARGET_UNIT_PASSENGER_7:
if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsVehicle())
target = m_caster->GetVehicleKit()->GetPassenger(targetType.GetTarget() - TARGET_UNIT_PASSENGER_0);
break;
default:
break;
}
CallScriptObjectTargetSelectHandlers(target, effIndex);
if (target && target->ToUnit())
AddUnitTarget(target->ToUnit(), 1 << effIndex, checkIfValid);
}
void Spell::SelectImplicitTargetObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
ASSERT((m_targets.GetObjectTarget() || m_targets.GetItemTarget()) && "Spell::SelectImplicitTargetObjectTargets - no explicit object or item target available!");
WorldObject* target = m_targets.GetObjectTarget();
CallScriptObjectTargetSelectHandlers(target, effIndex);
if (target)
{
if (Unit* unit = target->ToUnit())
AddUnitTarget(unit, 1 << effIndex, true, false);
else if (GameObject* gobj = target->ToGameObject())
AddGOTarget(gobj, 1 << effIndex);
SelectImplicitChainTargets(effIndex, targetType, target, 1 << effIndex);
}
// Script hook can remove object target and we would wrongly land here
else if (Item* item = m_targets.GetItemTarget())
AddItemTarget(item, 1 << effIndex);
}
void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, WorldObject* target, uint32 effMask)
{
uint32 maxTargets = m_spellInfo->Effects[effIndex].ChainTarget;
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this);
if (maxTargets > 1)
{
// mark damage multipliers as used
for (uint32 k = effIndex; k < MAX_SPELL_EFFECTS; ++k)
if (effMask & (1 << k))
m_damageMultipliers[k] = 1.0f;
m_applyMultiplierMask |= effMask;
std::list<WorldObject*> targets;
SearchChainTargets(targets, maxTargets - 1, target, targetType.GetObjectType(), targetType.GetCheckType()
, m_spellInfo->Effects[effIndex].ImplicitTargetConditions, targetType.GetTarget() == TARGET_UNIT_TARGET_CHAINHEAL_ALLY);
// Chain primary target is added earlier
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex);
// for backward compability
std::list<Unit*> unitTargets;
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
if (Unit* unitTarget = (*itr)->ToUnit())
unitTargets.push_back(unitTarget);
for (std::list<Unit*>::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr)
AddUnitTarget(*itr, effMask, false);
}
}
float tangent(float x)
{
x = tan(x);
//if (x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x;
//if (x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max();
//if (x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max();
if (x < 100000.0f && x > -100000.0f) return x;
if (x >= 100000.0f) return 100000.0f;
if (x <= 100000.0f) return -100000.0f;
return 0.0f;
}
#define DEBUG_TRAJ(a) //a
void Spell::SelectImplicitTrajTargets()
{
if (!m_targets.HasTraj())
return;
float dist2d = m_targets.GetDist2d();
if (!dist2d)
return;
float srcToDestDelta = m_targets.GetDstPos()->m_positionZ - m_targets.GetSrcPos()->m_positionZ;
std::list<WorldObject*> targets;
Trinity::WorldObjectSpellTrajTargetCheck check(dist2d, m_targets.GetSrcPos(), m_caster, m_spellInfo);
Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellTrajTargetCheck> searcher(m_caster, targets, check, GRID_MAP_TYPE_MASK_ALL);
SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellTrajTargetCheck> > (searcher, GRID_MAP_TYPE_MASK_ALL, m_caster, m_targets.GetSrcPos(), dist2d);
if (targets.empty())
return;
targets.sort(Trinity::ObjectDistanceOrderPred(m_caster));
float b = tangent(m_targets.GetElevation());
float a = (srcToDestDelta - dist2d * b) / (dist2d * dist2d);
if (a > -0.0001f)
a = 0;
DEBUG_TRAJ(TC_LOG_ERROR("spells", "Spell::SelectTrajTargets: a %f b %f", a, b);)
float bestDist = m_spellInfo->GetMaxRange(false);
std::list<WorldObject*>::const_iterator itr = targets.begin();
for (; itr != targets.end(); ++itr)
{
if (Unit* unitTarget = (*itr)->ToUnit())
if (m_caster == *itr || m_caster->IsOnVehicle(unitTarget) || (unitTarget)->GetVehicle())//(*itr)->IsOnVehicle(m_caster))
continue;
const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3)
/// @todo all calculation should be based on src instead of m_caster
const float objDist2d = m_targets.GetSrcPos()->GetExactDist2d(*itr) * std::cos(m_targets.GetSrcPos()->GetRelativeAngle(*itr));
const float dz = (*itr)->GetPositionZ() - m_targets.GetSrcPos()->m_positionZ;
DEBUG_TRAJ(TC_LOG_ERROR("spells", "Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);)
float dist = objDist2d - size;
float height = dist * (a * dist + b);
DEBUG_TRAJ(TC_LOG_ERROR("spells", "Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)
if (dist < bestDist && height < dz + size && height > dz - size)
{
bestDist = dist > 0 ? dist : 0;
break;
}
#define CHECK_DIST {\
DEBUG_TRAJ(TC_LOG_ERROR("spells", "Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\
if (dist > bestDist)\
continue;\
if (dist < objDist2d + size && dist > objDist2d - size)\
{\
bestDist = dist;\
break;\
}\
}
if (!a)
{
height = dz - size;
dist = height / b;
CHECK_DIST;
height = dz + size;
dist = height / b;
CHECK_DIST;
continue;
}
height = dz - size;
float sqrt1 = b * b + 4 * a * height;
if (sqrt1 > 0)
{
sqrt1 = sqrt(sqrt1);
dist = (sqrt1 - b) / (2 * a);
CHECK_DIST;
}
height = dz + size;
float sqrt2 = b * b + 4 * a * height;
if (sqrt2 > 0)
{
sqrt2 = sqrt(sqrt2);
dist = (sqrt2 - b) / (2 * a);
CHECK_DIST;
dist = (-sqrt2 - b) / (2 * a);
CHECK_DIST;
}
if (sqrt1 > 0)
{
dist = (-sqrt1 - b) / (2 * a);
CHECK_DIST;
}
}
if (m_targets.GetSrcPos()->GetExactDist2d(m_targets.GetDstPos()) > bestDist)
{
float x = m_targets.GetSrcPos()->m_positionX + std::cos(m_caster->GetOrientation()) * bestDist;
float y = m_targets.GetSrcPos()->m_positionY + std::sin(m_caster->GetOrientation()) * bestDist;
float z = m_targets.GetSrcPos()->m_positionZ + bestDist * (a * bestDist + b);
if (itr != targets.end())
{
float distSq = (*itr)->GetExactDistSq(x, y, z);
float sizeSq = (*itr)->GetObjectSize();
sizeSq *= sizeSq;
DEBUG_TRAJ(TC_LOG_ERROR("spells", "Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
if (distSq > sizeSq)
{
float factor = 1 - sqrt(sizeSq / distSq);
x += factor * ((*itr)->GetPositionX() - x);
y += factor * ((*itr)->GetPositionY() - y);
z += factor * ((*itr)->GetPositionZ() - z);
distSq = (*itr)->GetExactDistSq(x, y, z);
DEBUG_TRAJ(TC_LOG_ERROR("spells", "Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
}
}
Position trajDst;
trajDst.Relocate(x, y, z, m_caster->GetOrientation());
m_targets.ModDst(trajDst);
}
if (Vehicle* veh = m_caster->GetVehicleKit())
veh->SetLastShootPos(*m_targets.GetDstPos());
}
void Spell::SelectEffectTypeImplicitTargets(uint8 effIndex)
{
// special case for SPELL_EFFECT_SUMMON_RAF_FRIEND and SPELL_EFFECT_SUMMON_PLAYER
/// @todo this is a workaround - target shouldn't be stored in target map for those spells
switch (m_spellInfo->Effects[effIndex].Effect)
{
case SPELL_EFFECT_SUMMON_RAF_FRIEND:
case SPELL_EFFECT_SUMMON_PLAYER:
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->GetTarget())
{
WorldObject* target = ObjectAccessor::FindPlayer(m_caster->GetTarget());
CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex));
if (target && target->ToPlayer())
AddUnitTarget(target->ToUnit(), 1 << effIndex, false);
}
return;
default:
break;
}
// select spell implicit targets based on effect type
if (!m_spellInfo->Effects[effIndex].GetImplicitTargetType())
return;
uint32 targetMask = m_spellInfo->Effects[effIndex].GetMissingTargetMask();
if (!targetMask)
return;
WorldObject* target = NULL;
switch (m_spellInfo->Effects[effIndex].GetImplicitTargetType())
{
// add explicit object target or self to the target map
case EFFECT_IMPLICIT_TARGET_EXPLICIT:
// player which not released his spirit is Unit, but target flag for it is TARGET_FLAG_CORPSE_MASK
if (targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK))
{
if (Unit* unitTarget = m_targets.GetUnitTarget())
target = unitTarget;
else if (targetMask & TARGET_FLAG_CORPSE_MASK)
{
if (Corpse* corpseTarget = m_targets.GetCorpseTarget())
{
/// @todo this is a workaround - corpses should be added to spell target map too, but we can't do that so we add owner instead
if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID()))
target = owner;
}
}
else //if (targetMask & TARGET_FLAG_UNIT_MASK)
target = m_caster;
}
if (targetMask & TARGET_FLAG_ITEM_MASK)
{
if (Item* itemTarget = m_targets.GetItemTarget())
AddItemTarget(itemTarget, 1 << effIndex);
return;
}
if (targetMask & TARGET_FLAG_GAMEOBJECT_MASK)
target = m_targets.GetGOTarget();
break;
// add self to the target map
case EFFECT_IMPLICIT_TARGET_CASTER:
if (targetMask & TARGET_FLAG_UNIT_MASK)
target = m_caster;
break;
default:
break;
}
CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex));
if (target)
{
if (target->ToUnit())
AddUnitTarget(target->ToUnit(), 1 << effIndex, false);
else if (target->ToGameObject())
AddGOTarget(target->ToGameObject(), 1 << effIndex);
}
}
uint32 Spell::GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionList* condList)
{
// this function selects which containers need to be searched for spell target
uint32 retMask = GRID_MAP_TYPE_MASK_ALL;
// filter searchers based on searched object type
switch (objType)
{
case TARGET_OBJECT_TYPE_UNIT:
case TARGET_OBJECT_TYPE_UNIT_AND_DEST:
case TARGET_OBJECT_TYPE_CORPSE:
case TARGET_OBJECT_TYPE_CORPSE_ENEMY:
case TARGET_OBJECT_TYPE_CORPSE_ALLY:
retMask &= GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_CREATURE;
break;
case TARGET_OBJECT_TYPE_GOBJ:
case TARGET_OBJECT_TYPE_GOBJ_ITEM:
retMask &= GRID_MAP_TYPE_MASK_GAMEOBJECT;
break;
default:
break;
}
if (!(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_DEAD))
retMask &= ~GRID_MAP_TYPE_MASK_CORPSE;
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_PLAYERS)
retMask &= GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_PLAYER;
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_GHOSTS)
retMask &= GRID_MAP_TYPE_MASK_PLAYER;
if (condList)
retMask &= sConditionMgr->GetSearcherTypeMaskForConditionList(*condList);
return retMask;
}
template<class SEARCHER>
void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius)
{
if (!containerMask)
return;
// search world and grid for possible targets
bool searchInGrid = containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_GAMEOBJECT);
bool searchInWorld = containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE);
if (searchInGrid || searchInWorld)
{
float x, y;
x = pos->GetPositionX();
y = pos->GetPositionY();
CellCoord p(Trinity::ComputeCellCoord(x, y));
Cell cell(p);
cell.SetNoCreate();
Map& map = *(referer->GetMap());
if (searchInWorld)
{
TypeContainerVisitor<SEARCHER, WorldTypeMapContainer> world_object_notifier(searcher);
cell.Visit(p, world_object_notifier, map, radius, x, y);
}
if (searchInGrid)
{
TypeContainerVisitor<SEARCHER, GridTypeMapContainer > grid_object_notifier(searcher);
cell.Visit(p, grid_object_notifier, map, radius, x, y);
}
}
}
WorldObject* Spell::SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList)
{
WorldObject* target = NULL;
uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList);
if (!containerTypeMask)
return NULL;
Trinity::WorldObjectSpellNearbyTargetCheck check(range, m_caster, m_spellInfo, selectionType, condList);
Trinity::WorldObjectLastSearcher<Trinity::WorldObjectSpellNearbyTargetCheck> searcher(m_caster, target, check, containerTypeMask);
SearchTargets<Trinity::WorldObjectLastSearcher<Trinity::WorldObjectSpellNearbyTargetCheck> > (searcher, containerTypeMask, m_caster, m_caster, range);
return target;
}
void Spell::SearchAreaTargets(std::list<WorldObject*>& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList)
{
uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList);
if (!containerTypeMask)
return;
Trinity::WorldObjectSpellAreaTargetCheck check(range, position, m_caster, referer, m_spellInfo, selectionType, condList);
Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellAreaTargetCheck> searcher(m_caster, targets, check, containerTypeMask);
SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellAreaTargetCheck> > (searcher, containerTypeMask, m_caster, position, range);
}
void Spell::SearchChainTargets(std::list<WorldObject*>& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, ConditionList* condList, bool isChainHeal)
{
// max dist for jump target selection
float jumpRadius = 0.0f;
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_RANGED:
// 7.5y for multi shot
jumpRadius = 7.5f;
break;
case SPELL_DAMAGE_CLASS_MELEE:
// 5y for swipe, cleave and similar
jumpRadius = 5.0f;
break;
case SPELL_DAMAGE_CLASS_NONE:
case SPELL_DAMAGE_CLASS_MAGIC:
// 12.5y for chain heal spell since 3.2 patch
if (isChainHeal)
jumpRadius = 12.5f;
// 10y as default for magic chain spells
else
jumpRadius = 10.0f;
break;
}
// chain lightning/heal spells and similar - allow to jump at larger distance and go out of los
bool isBouncingFar = (m_spellInfo->AttributesEx4 & SPELL_ATTR4_AREA_TARGET_CHAIN
|| m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE
|| m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC);
// max dist which spell can reach
float searchRadius = jumpRadius;
if (isBouncingFar)
searchRadius *= chainTargets;
std::list<WorldObject*> tempTargets;
SearchAreaTargets(tempTargets, searchRadius, target, m_caster, objectType, selectType, condList);
tempTargets.remove(target);
// remove targets which are always invalid for chain spells
// for some spells allow only chain targets in front of caster (swipe for example)
if (!isBouncingFar)
{
for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end();)
{
std::list<WorldObject*>::iterator checkItr = itr++;
if (!m_caster->HasInArc(static_cast<float>(M_PI), *checkItr))
tempTargets.erase(checkItr);
}
}
while (chainTargets)
{
// try to get unit for next chain jump
std::list<WorldObject*>::iterator foundItr = tempTargets.end();
// get unit with highest hp deficit in dist
if (isChainHeal)
{
uint32 maxHPDeficit = 0;
for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr)
{
if (Unit* unitTarget = (*itr)->ToUnit())
{
uint32 deficit = unitTarget->GetMaxHealth() - unitTarget->GetHealth();
if ((deficit > maxHPDeficit || foundItr == tempTargets.end()) && target->IsWithinDist(unitTarget, jumpRadius) && target->IsWithinLOSInMap(unitTarget))
{
foundItr = itr;
maxHPDeficit = deficit;
}
}
}
}
// get closest object
else
{
for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr)
{
if (foundItr == tempTargets.end())
{
if ((!isBouncingFar || target->IsWithinDist(*itr, jumpRadius)) && target->IsWithinLOSInMap(*itr))
foundItr = itr;
}
else if (target->GetDistanceOrder(*itr, *foundItr) && target->IsWithinLOSInMap(*itr))
foundItr = itr;
}
}
// not found any valid target - chain ends
if (foundItr == tempTargets.end())
break;
target = *foundItr;
tempTargets.erase(foundItr);
targets.push_back(target);
--chainTargets;
}
}
GameObject* Spell::SearchSpellFocus()
{
GameObject* focus = NULL;
Trinity::GameObjectFocusCheck check(m_caster, m_spellInfo->RequiresSpellFocus);
Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> searcher(m_caster, focus, check);
SearchTargets<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> > (searcher, GRID_MAP_TYPE_MASK_GAMEOBJECT, m_caster, m_caster, m_caster->GetVisibilityRange());
return focus;
}
void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/)
{
//==========================================================================================
// Now fill data for trigger system, need know:
// can spell trigger another or not (m_canTrigger)
// Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_procEx)
//==========================================================================================
m_procVictim = m_procAttacker = 0;
// Get data for type of attack and fill base info for trigger
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE:
m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS;
if (m_attackType == OFF_ATTACK)
m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK;
else
m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS;
break;
case SPELL_DAMAGE_CLASS_RANGED:
// Auto attack
if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG)
{
m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK;
}
else // Ranged spell attack
{
m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS;
m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS;
}
break;
default:
if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON &&
m_spellInfo->EquippedItemSubClassMask & (1<<ITEM_SUBCLASS_WEAPON_WAND)
&& m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) // Wands auto attack
{
m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK;
}
// For other spells trigger procflags are set in Spell::DoAllEffectOnTarget
// Because spell positivity is dependant on target
}
m_procEx = PROC_EX_NONE;
// Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER &&
(m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow
m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc
m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap
{
m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION;
}
/* Effects which are result of aura proc from triggered spell cannot proc
to prevent chain proc of these spells */
// Hellfire Effect - trigger as DOT
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040)
{
m_procAttacker = PROC_FLAG_DONE_PERIODIC;
m_procVictim = PROC_FLAG_TAKEN_PERIODIC;
}
// Ranged autorepeat attack is set as triggered spell - ignore it
if (!(m_procAttacker & PROC_FLAG_DONE_RANGED_AUTO_ATTACK))
{
if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS &&
(m_spellInfo->AttributesEx2 & SPELL_ATTR2_TRIGGERED_CAN_TRIGGER_PROC ||
m_spellInfo->AttributesEx3 & SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_PROC_2))
m_procEx |= PROC_EX_INTERNAL_CANT_PROC;
else if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS)
m_procEx |= PROC_EX_INTERNAL_TRIGGERED;
}
// Totem casts require spellfamilymask defined in spell_proc_event to proc
if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsTotem() && m_caster->IsControlledByPlayer())
m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY;
}
void Spell::CleanupTargetList()
{
m_UniqueTargetInfo.clear();
m_UniqueGOTargetInfo.clear();
m_UniqueItemInfo.clear();
m_delayMoment = 0;
}
void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= true*/, bool implicit /*= true*/)
{
for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
if (!m_spellInfo->Effects[effIndex].IsEffect() || !CheckEffectTarget(target, effIndex))
effectMask &= ~(1 << effIndex);
// no effects left
if (!effectMask)
return;
if (checkIfValid)
if (m_spellInfo->CheckTarget(m_caster, target, implicit) != SPELL_CAST_OK)
return;
// Check for effect immune skip if immuned
for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
if (target->IsImmunedToSpellEffect(m_spellInfo, effIndex))
effectMask &= ~(1 << effIndex);
uint64 targetGUID = target->GetGUID();
// Lookup target in already in list
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (targetGUID == ihit->targetGUID) // Found in list
{
ihit->effectMask |= effectMask; // Immune effects removed from mask
ihit->scaleAura = false;
if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != target)
{
SpellInfo const* auraSpell = m_spellInfo->GetFirstRankSpell();
if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel)
ihit->scaleAura = true;
}
return;
}
}
// This is new target calculate data for him
// Get spell hit result on target
TargetInfo targetInfo;
targetInfo.targetGUID = targetGUID; // Store target GUID
targetInfo.effectMask = effectMask; // Store all effects not immune
targetInfo.processed = false; // Effects not apply on target
targetInfo.alive = target->IsAlive();
targetInfo.damage = 0;
targetInfo.crit = false;
targetInfo.scaleAura = false;
if (m_auraScaleMask && targetInfo.effectMask == m_auraScaleMask && m_caster != target)
{
SpellInfo const* auraSpell = m_spellInfo->GetFirstRankSpell();
if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel)
targetInfo.scaleAura = true;
}
// Calculate hit result
if (m_originalCaster)
{
targetInfo.missCondition = m_originalCaster->SpellHitResult(target, m_spellInfo, m_canReflect);
if (m_skipCheck && targetInfo.missCondition != SPELL_MISS_IMMUNE)
targetInfo.missCondition = SPELL_MISS_NONE;
}
else
targetInfo.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE;
// Spell have speed - need calculate incoming time
// Incoming time is zero for self casts. At least I think so.
if (m_spellInfo->Speed > 0.0f && m_caster != target)
{
// calculate spell incoming interval
/// @todo this is a hack
float dist = m_caster->GetDistance(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ());
if (dist < 5.0f)
dist = 5.0f;
if (!(m_spellInfo->AttributesEx9 & SPELL_ATTR9_SPECIAL_DELAY_CALCULATION))
targetInfo.timeDelay = uint64(floor(dist / m_spellInfo->Speed * 1000.0f));
else
targetInfo.timeDelay = uint64(m_spellInfo->Speed * 1000.0f);
// Calculate minimum incoming time
if (m_delayMoment == 0 || m_delayMoment > targetInfo.timeDelay)
m_delayMoment = targetInfo.timeDelay;
}
else
targetInfo.timeDelay = 0LL;
// If target reflect spell back to caster
if (targetInfo.missCondition == SPELL_MISS_REFLECT)
{
// Calculate reflected spell result on caster
targetInfo.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
if (targetInfo.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
targetInfo.reflectResult = SPELL_MISS_PARRY;
// Increase time interval for reflected spells by 1.5
targetInfo.timeDelay += targetInfo.timeDelay >> 1;
}
else
targetInfo.reflectResult = SPELL_MISS_NONE;
// Add target to list
m_UniqueTargetInfo.push_back(targetInfo);
}
void Spell::AddGOTarget(GameObject* go, uint32 effectMask)
{
for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
{
if (!m_spellInfo->Effects[effIndex].IsEffect())
effectMask &= ~(1 << effIndex);
else
{
switch (m_spellInfo->Effects[effIndex].Effect)
{
case SPELL_EFFECT_GAMEOBJECT_DAMAGE:
case SPELL_EFFECT_GAMEOBJECT_REPAIR:
case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE:
if (go->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING)
effectMask &= ~(1 << effIndex);
break;
default:
break;
}
}
}
if (!effectMask)
return;
uint64 targetGUID = go->GetGUID();
// Lookup target in already in list
for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
{
if (targetGUID == ihit->targetGUID) // Found in list
{
ihit->effectMask |= effectMask; // Add only effect mask
return;
}
}
// This is new target calculate data for him
GOTargetInfo target;
target.targetGUID = targetGUID;
target.effectMask = effectMask;
target.processed = false; // Effects not apply on target
// Spell have speed - need calculate incoming time
if (m_spellInfo->Speed > 0.0f)
{
// calculate spell incoming interval
float dist = m_caster->GetDistance(go->GetPositionX(), go->GetPositionY(), go->GetPositionZ());
if (dist < 5.0f)
dist = 5.0f;
if (!(m_spellInfo->AttributesEx9 & SPELL_ATTR9_SPECIAL_DELAY_CALCULATION))
target.timeDelay = uint64(floor(dist / m_spellInfo->Speed * 1000.0f));
else
target.timeDelay = uint64(m_spellInfo->Speed * 1000.0f);
if (m_delayMoment == 0 || m_delayMoment > target.timeDelay)
m_delayMoment = target.timeDelay;
}
else
target.timeDelay = 0LL;
// Add target to list
m_UniqueGOTargetInfo.push_back(target);
}
void Spell::AddItemTarget(Item* item, uint32 effectMask)
{
for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
if (!m_spellInfo->Effects[effIndex].IsEffect())
effectMask &= ~(1 << effIndex);
// no effects left
if (!effectMask)
return;
// Lookup target in already in list
for (std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
{
if (item == ihit->item) // Found in list
{
ihit->effectMask |= effectMask; // Add only effect mask
return;
}
}
// This is new target add data
ItemTargetInfo target;
target.item = item;
target.effectMask = effectMask;
m_UniqueItemInfo.push_back(target);
}
void Spell::AddDestTarget(SpellDestination const& dest, uint32 effIndex)
{
m_destTargets[effIndex] = dest;
}
void Spell::DoAllEffectOnTarget(TargetInfo* target)
{
if (!target || target->processed)
return;
target->processed = true; // Target checked in apply effects procedure
// Get mask of effects for target
uint8 mask = target->effectMask;
Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
if (!unit)
{
uint8 farMask = 0;
// create far target mask
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_spellInfo->Effects[i].IsFarUnitTargetEffect())
if ((1 << i) & mask)
farMask |= (1 << i);
if (!farMask)
return;
// find unit in world
unit = ObjectAccessor::FindUnit(target->targetGUID);
if (!unit)
return;
// do far effects on the unit
// can't use default call because of threading, do stuff as fast as possible
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (farMask & (1 << i))
HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_HIT_TARGET);
return;
}
if (unit->IsAlive() != target->alive)
return;
if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsPositive() && (getMSTime() - target->timeDelay) <= unit->m_lastSanctuaryTime)
return; // No missinfo in that case
// Get original caster (if exist) and calculate damage/healing from him data
Unit* caster = m_originalCaster ? m_originalCaster : m_caster;
// Skip if m_originalCaster not avaiable
if (!caster)
return;
SpellMissInfo missInfo = target->missCondition;
// Need init unitTarget by default unit (can changed in code on reflect)
// Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
unitTarget = unit;
// Reset damage/healing counter
m_damage = target->damage;
m_healing = -target->damage;
// Fill base trigger info
uint32 procAttacker = m_procAttacker;
uint32 procVictim = m_procVictim;
uint32 procEx = m_procEx;
m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied
//Spells with this flag cannot trigger if effect is casted on self
bool canEffectTrigger = !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && CanExecuteTriggersOnHit(mask);
Unit* spellHitTarget = NULL;
if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
spellHitTarget = unit;
else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
{
if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
{
spellHitTarget = m_caster;
if (m_caster->GetTypeId() == TYPEID_UNIT)
m_caster->ToCreature()->LowerPlayerDamageReq(target->damage);
}
}
if (spellHitTarget)
{
SpellMissInfo missInfo2 = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura);
if (missInfo2 != SPELL_MISS_NONE)
{
if (missInfo2 != SPELL_MISS_MISS)
m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo2);
m_damage = 0;
spellHitTarget = NULL;
}
}
// Do not take combo points on dodge and miss
if (missInfo != SPELL_MISS_NONE && m_needComboPoints &&
m_targets.GetUnitTargetGUID() == target->targetGUID)
{
m_needComboPoints = false;
// Restore spell mods for a miss/dodge/parry Cold Blood
/// @todo check how broad this rule should be
if (m_caster->GetTypeId() == TYPEID_PLAYER && (missInfo == SPELL_MISS_MISS ||
missInfo == SPELL_MISS_DODGE || missInfo == SPELL_MISS_PARRY))
m_caster->ToPlayer()->RestoreSpellMods(this, 14177);
}
// Trigger info was not filled in spell::preparedatafortriggersystem - we do it now
if (canEffectTrigger && !procAttacker && !procVictim)
{
bool positive = true;
if (m_damage > 0)
positive = false;
else if (!m_healing)
{
for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
// If at least one effect negative spell is negative hit
if (mask & (1<<i) && !m_spellInfo->IsPositiveEffect(i))
{
positive = false;
break;
}
}
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MAGIC:
if (positive)
{
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS;
procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS;
}
else
{
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG;
procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG;
}
break;
case SPELL_DAMAGE_CLASS_NONE:
if (positive)
{
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS;
procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS;
}
else
{
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG;
procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG;
}
break;
}
}
CallScriptOnHitHandlers();
// All calculated do it!
// Do healing and triggers
if (m_healing > 0)
{
bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask);
uint32 addhealth = m_healing;
if (crit)
{
procEx |= PROC_EX_CRITICAL_HIT;
addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
}
else
procEx |= PROC_EX_NORMAL_HIT;
int32 gain = caster->HealBySpell(unitTarget, m_spellInfo, addhealth, crit);
unitTarget->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
m_healing = gain;
// Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
}
// Do damage and triggers
else if (m_damage > 0)
{
// Fill base damage struct (unitTarget - is real spell target)
SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
// Add bonuses and fill damageInfo struct
caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit);
caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
// Send log damage message to client
caster->SendSpellNonMeleeDamageLog(&damageInfo);
procEx |= createProcExtendMask(&damageInfo, missInfo);
procVictim |= PROC_FLAG_TAKEN_DAMAGE;
// Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
{
caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
if (caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 &&
(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED))
caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx);
}
m_damage = damageInfo.damage;
caster->DealSpellDamage(&damageInfo, true);
}
// Passive spell hits/misses or active spells only misses (only triggers)
else
{
// Fill base damage struct (unitTarget - is real spell target)
SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
procEx |= createProcExtendMask(&damageInfo, missInfo);
// Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
// Failed Pickpocket, reveal rogue
if (missInfo == SPELL_MISS_RESIST && m_spellInfo->AttributesCu & SPELL_ATTR0_CU_PICKPOCKET && unitTarget->GetTypeId() == TYPEID_UNIT)
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
if (unitTarget->ToCreature()->IsAIEnabled)
unitTarget->ToCreature()->AI()->AttackStart(m_caster);
}
}
if (missInfo != SPELL_MISS_EVADE && !m_caster->IsFriendlyTo(unit) && (!m_spellInfo->IsPositive() || m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL)))
{
m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO));
if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC)
if (!unit->IsStandState())
unit->SetStandState(UNIT_STAND_STATE_STAND);
}
if (spellHitTarget)
{
//AI functions
if (spellHitTarget->GetTypeId() == TYPEID_UNIT)
if (spellHitTarget->ToCreature()->IsAIEnabled)
spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo);
if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled)
m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo);
// Needs to be called after dealing damage/healing to not remove breaking on damage auras
DoTriggersOnSpellHit(spellHitTarget, mask);
// if target is fallged for pvp also flag caster if a player
if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->UpdatePvP(true);
CallScriptAfterHitHandlers();
}
}
SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleAura)
{
if (!unit || !effectMask)
return SPELL_MISS_EVADE;
// For delayed spells immunity may be applied between missile launch and hit - check immunity for that case
if (m_spellInfo->Speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo)))
return SPELL_MISS_IMMUNE;
// disable effects to which unit is immune
SpellMissInfo returnVal = SPELL_MISS_IMMUNE;
for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber)
if (effectMask & (1 << effectNumber))
if (unit->IsImmunedToSpellEffect(m_spellInfo, effectNumber))
effectMask &= ~(1 << effectNumber);
if (!effectMask)
return returnVal;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers();
if (Player* player = unit->ToPlayer())
{
player->StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, 0, m_caster);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
}
if (Player* player = m_caster->ToPlayer())
{
player->StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, 0, unit);
}
if (m_caster != unit)
{
// Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
if (m_spellInfo->Speed > 0.0f && unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
return SPELL_MISS_EVADE;
if (m_caster->_IsValidAttackTarget(unit, m_spellInfo))
{
unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL);
/// @todo This is a hack. But we do not know what types of stealth should be interrupted by CC
if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) && unit->IsControlledByPlayer())
unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH);
}
else if (m_caster->IsFriendlyTo(unit))
{
// for delayed spells ignore negative spells (after duel end) for friendly targets
/// @todo this cause soul transfer bugged
// 63881 - Malady of the Mind jump spell (Yogg-Saron)
if (m_spellInfo->Speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->IsPositive() && m_spellInfo->Id != 63881)
return SPELL_MISS_EVADE;
// assisting case, healing and resurrection
if (unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER))
{
m_caster->SetContestedPvP();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->UpdatePvP(true);
}
if (unit->IsInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO))
{
m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit);
unit->getHostileRefManager().threatAssist(m_caster, 0.0f);
}
}
}
// Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo, m_triggeredByAuraSpell);
if (m_diminishGroup)
{
m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup);
// Increase Diminishing on unit, current informations for actually casts will use values above
if ((type == DRTYPE_PLAYER &&
(unit->GetCharmerOrOwnerPlayerOrPlayerItself() || (unit->GetTypeId() == TYPEID_UNIT && unit->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH))) ||
type == DRTYPE_ALL)
unit->IncrDiminishing(m_diminishGroup);
}
uint8 aura_effmask = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (effectMask & (1 << i) && m_spellInfo->Effects[i].IsUnitOwnedAuraEffect())
aura_effmask |= 1 << i;
if (aura_effmask)
{
// Select rank for aura with level requirements only in specific cases
// Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target
SpellInfo const* aurSpellInfo = m_spellInfo;
int32 basePoints[3];
if (scaleAura)
{
aurSpellInfo = m_spellInfo->GetAuraRankForLevel(unitTarget->getLevel());
ASSERT(aurSpellInfo);
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
basePoints[i] = aurSpellInfo->Effects[i].BasePoints;
if (m_spellInfo->Effects[i].Effect != aurSpellInfo->Effects[i].Effect)
{
aurSpellInfo = m_spellInfo;
break;
}
}
}
if (m_originalCaster)
{
bool refresh = false;
m_spellAura = Aura::TryRefreshStackOrCreate(aurSpellInfo, effectMask, unit,
m_originalCaster, (aurSpellInfo == m_spellInfo)? &m_spellValue->EffectBasePoints[0] : &basePoints[0], m_CastItem, 0, &refresh);
if (m_spellAura)
{
// Set aura stack amount to desired value
if (m_spellValue->AuraStackAmount > 1)
{
if (!refresh)
m_spellAura->SetStackAmount(m_spellValue->AuraStackAmount);
else
m_spellAura->ModStackAmount(m_spellValue->AuraStackAmount);
}
// Now Reduce spell duration using data received at spell hit
int32 duration = m_spellAura->GetMaxDuration();
int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup, aurSpellInfo);
float diminishMod = unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel, limitduration);
// unit is immune to aura if it was diminished to 0 duration
if (diminishMod == 0.0f)
{
m_spellAura->Remove();
bool found = false;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (effectMask & (1 << i) && m_spellInfo->Effects[i].Effect != SPELL_EFFECT_APPLY_AURA)
found = true;
if (!found)
return SPELL_MISS_IMMUNE;
}
else
{
((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup);
bool positive = m_spellAura->GetSpellInfo()->IsPositive();
if (AuraApplication* aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID()))
positive = aurApp->IsPositive();
duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive, effectMask);
if (duration > 0)
{
// Haste modifies duration of channeled spells
if (m_spellInfo->IsChanneled())
{
if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION)
m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this);
}
else if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION)
{
int32 origDuration = duration;
duration = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (AuraEffect const* eff = m_spellAura->GetEffect(i))
if (int32 amplitude = eff->GetAmplitude()) // amplitude is hastened by UNIT_FIELD_MOD_CASTING_SPEED
duration = std::max(std::max(origDuration / amplitude, 1) * amplitude, duration);
// if there is no periodic effect
if (!duration)
duration = int32(origDuration * m_originalCaster->GetFloatValue(UNIT_FIELD_MOD_CASTING_SPEED));
}
}
if (duration != m_spellAura->GetMaxDuration())
{
m_spellAura->SetMaxDuration(duration);
m_spellAura->SetDuration(duration);
}
m_spellAura->_RegisterForTargets();
}
}
}
}
for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber)
if (effectMask & (1 << effectNumber))
HandleEffects(unit, NULL, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET);
return SPELL_MISS_NONE;
}
void Spell::DoTriggersOnSpellHit(Unit* unit, uint32 effMask)
{
// Apply additional spell effects to target
/// @todo move this code to scripts
if (m_preCastSpell)
{
// Paladin immunity shields
if (m_preCastSpell == 61988)
{
// Cast Forbearance
m_caster->CastSpell(unit, 25771, true);
// Cast Avenging Wrath Marker
unit->CastSpell(unit, 61987, true);
}
// Avenging Wrath
if (m_preCastSpell == 61987)
// Cast the serverside immunity shield marker
m_caster->CastSpell(unit, 61988, true);
if (sSpellMgr->GetSpellInfo(m_preCastSpell))
// Blizz seems to just apply aura without bothering to cast
m_caster->AddAura(m_preCastSpell, unit);
}
// handle SPELL_AURA_ADD_TARGET_TRIGGER auras
// this is executed after spell proc spells on target hit
// spells are triggered for each hit spell target
// info confirmed with retail sniffs of permafrost and shadow weaving
if (!m_hitTriggerSpells.empty())
{
int _duration = 0;
for (HitTriggerSpellList::const_iterator i = m_hitTriggerSpells.begin(); i != m_hitTriggerSpells.end(); ++i)
{
if (CanExecuteTriggersOnHit(effMask, i->triggeredByAura) && roll_chance_i(i->chance))
{
m_caster->CastSpell(unit, i->triggeredSpell, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_TARGET_CHECK));
TC_LOG_DEBUG("spells", "Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->triggeredSpell->Id);
// SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration
// set duration of current aura to the triggered spell
if (i->triggeredSpell->GetDuration() == -1)
{
if (Aura* triggeredAur = unit->GetAura(i->triggeredSpell->Id, m_caster->GetGUID()))
{
// get duration from aura-only once
if (!_duration)
{
Aura* aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID());
_duration = aur ? aur->GetDuration() : -1;
}
triggeredAur->SetDuration(_duration);
}
}
}
}
}
// trigger linked auras remove/apply
/// @todo remove/cleanup this, as this table is not documented and people are doing stupid things with it
if (std::vector<int32> const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT))
{
for (std::vector<int32>::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i)
{
if (*i < 0)
unit->RemoveAurasDueToSpell(-(*i));
else
unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID());
}
}
}
void Spell::DoAllEffectOnTarget(GOTargetInfo* target)
{
if (target->processed) // Check target
return;
target->processed = true; // Target checked in apply effects procedure
uint32 effectMask = target->effectMask;
if (!effectMask)
return;
GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
if (!go)
return;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers();
for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber)
if (effectMask & (1 << effectNumber))
HandleEffects(NULL, NULL, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET);
CallScriptOnHitHandlers();
CallScriptAfterHitHandlers();
}
void Spell::DoAllEffectOnTarget(ItemTargetInfo* target)
{
uint32 effectMask = target->effectMask;
if (!target->item || !effectMask)
return;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers();
for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber)
if (effectMask & (1 << effectNumber))
HandleEffects(NULL, target->item, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET);
CallScriptOnHitHandlers();
CallScriptAfterHitHandlers();
}
bool Spell::UpdateChanneledTargetList()
{
// Not need check return true
if (m_channelTargetEffectMask == 0)
return true;
uint8 channelTargetEffectMask = m_channelTargetEffectMask;
uint8 channelAuraMask = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA)
channelAuraMask |= 1<<i;
channelAuraMask &= channelTargetEffectMask;
float range = 0;
if (channelAuraMask)
{
range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive());
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
}
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask))
{
Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
if (!unit)
continue;
if (IsValidDeadOrAliveTarget(unit))
{
if (channelAuraMask & ihit->effectMask)
{
if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID))
{
if (m_caster != unit && !m_caster->IsWithinDistInMap(unit, range))
{
ihit->effectMask &= ~aurApp->GetEffectMask();
unit->RemoveAura(aurApp);
continue;
}
}
else // aura is dispelled
continue;
}
channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
}
}
}
// is all effects from m_needAliveTargetMask have alive targets
return channelTargetEffectMask == 0;
}
void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura)
{
if (m_CastItem)
m_castItemGUID = m_CastItem->GetGUID();
else
m_castItemGUID = 0;
InitExplicitTargets(*targets);
// Fill aura scaling information
if (m_caster->IsControlledByPlayer() && !m_spellInfo->IsPassive() && m_spellInfo->SpellLevel && !m_spellInfo->IsChanneled() && !(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_SCALING))
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA)
{
// Change aura with ranks only if basepoints are taken from spellInfo and aura is positive
if (m_spellInfo->IsPositiveEffect(i))
{
m_auraScaleMask |= (1 << i);
if (m_spellValue->EffectBasePoints[i] != m_spellInfo->Effects[i].BasePoints)
{
m_auraScaleMask = 0;
break;
}
}
}
}
}
m_spellState = SPELL_STATE_PREPARING;
if (triggeredByAura)
m_triggeredByAuraSpell = triggeredByAura->GetSpellInfo();
// create and add update event for this spell
SpellEvent* Event = new SpellEvent(this);
m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
//Prevent casting at cast another spell (ServerSide check)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS) && m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
{
SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
finish(false);
return;
}
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, m_caster))
{
SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
finish(false);
return;
}
LoadScripts();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
// Fill cost data (not use power for item casts
m_powerCost = m_CastItem ? 0 : m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask);
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
// Set combo point requirement
if ((_triggeredCastFlags & TRIGGERED_IGNORE_COMBO_POINTS) || m_CastItem || !m_caster->m_movedPlayer)
m_needComboPoints = false;
SpellCastResult result = CheckCast(true);
// target is checked in too many locations and with different results to handle each of them
// handle just the general SPELL_FAILED_BAD_TARGETS result which is the default result for most DBC target checks
if (_triggeredCastFlags & TRIGGERED_IGNORE_TARGET_CHECK && result == SPELL_FAILED_BAD_TARGETS)
result = SPELL_CAST_OK;
if (result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
{
// Periodic auras should be interrupted when aura triggers a spell which can't be cast
// for example bladestorm aura should be removed on disarm as of patch 3.3.5
// channeled periodic spells should be affected by this (arcane missiles, penance, etc)
// a possible alternative sollution for those would be validating aura target on unit state change
if (triggeredByAura && triggeredByAura->IsPeriodic() && !triggeredByAura->GetBase()->IsPassive())
{
SendChannelUpdate(0);
triggeredByAura->GetBase()->SetDuration(0);
}
SendCastResult(result);
finish(false);
return;
}
// Prepare data for triggers
prepareDataForTriggerSystem(triggeredByAura);
if (Player* player = m_caster->ToPlayer())
{
if (!player->GetCommandStatus(CHEAT_CASTTIME))
{
player->SetSpellModTakingSpell(this, true);
// calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
m_casttime = m_spellInfo->CalcCastTime(player->getLevel(), this);
player->SetSpellModTakingSpell(this, false);
}
else
m_casttime = 0; // Set cast time to 0 if .cheat casttime is enabled.
}
else
m_casttime = m_spellInfo->CalcCastTime(m_caster->getLevel(), this);
// don't allow channeled spells / spells with cast time to be casted while moving
// (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in)
// don't cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect
if (((m_spellInfo->IsChanneled() || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->isMoving() &&
m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && !m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo))
{
SendCastResult(SPELL_FAILED_MOVING);
finish(false);
return;
}
// set timer base at cast time
ReSetTimer();
TC_LOG_DEBUG("spells", "Spell::prepare: spell id %u source %u caster %d customCastFlags %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, _triggeredCastFlags, m_targets.GetTargetMask());
//Containers for channeled spells have to be set
/// @todoApply this to all casted spells if needed
// Why check duration? 29350: channelled triggers channelled
if ((_triggeredCastFlags & TRIGGERED_CAST_DIRECTLY) && (!m_spellInfo->IsChanneled() || !m_spellInfo->GetMaxDuration()))
cast(true);
else
{
// stealth must be removed at cast starting (at show channel bar)
// skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_INTERRUPT_FLAGS) && m_spellInfo->IsBreakingStealth())
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST);
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_spellInfo->Effects[i].GetUsedTargetObjectType() == TARGET_OBJECT_TYPE_UNIT)
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK);
break;
}
}
m_caster->SetCurrentCastedSpell(this);
SendSpellStart();
// set target for proper facing
if ((m_casttime || m_spellInfo->IsChanneled()) && !(_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING))
if (m_caster->GetTypeId() == TYPEID_UNIT && m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget())
m_caster->ToCreature()->FocusTarget(this, m_targets.GetObjectTarget());
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_GCD))
TriggerGlobalCooldown();
//item: first cast may destroy item and second cast causes crash
if (!m_casttime && !m_spellInfo->StartRecoveryTime && !m_castItemGUID && GetCurrentContainer() == CURRENT_GENERIC_SPELL)
cast(true);
}
}
void Spell::cancel()
{
if (m_spellState == SPELL_STATE_FINISHED)
return;
uint32 oldState = m_spellState;
m_spellState = SPELL_STATE_FINISHED;
m_autoRepeat = false;
switch (oldState)
{
case SPELL_STATE_PREPARING:
CancelGlobalCooldown();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->RestoreSpellMods(this);
// no break
case SPELL_STATE_DELAYED:
SendInterrupted(0);
SendCastResult(SPELL_FAILED_INTERRUPTED);
break;
case SPELL_STATE_CASTING:
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if ((*ihit).missCondition == SPELL_MISS_NONE)
if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL);
SendChannelUpdate(0);
SendInterrupted(0);
SendCastResult(SPELL_FAILED_INTERRUPTED);
// spell is canceled-take mods and clear list
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->RemoveSpellMods(this);
m_appliedMods.clear();
break;
default:
break;
}
SetReferencedFromCurrent(false);
if (m_selfContainer && *m_selfContainer == this)
*m_selfContainer = NULL;
m_caster->RemoveDynObject(m_spellInfo->Id);
if (m_spellInfo->IsChanneled()) // if not channeled then the object for the current cast wasn't summoned yet
m_caster->RemoveGameObject(m_spellInfo->Id, true);
//set state back so finish will be processed
m_spellState = oldState;
finish(false);
}
void Spell::cast(bool skipCheck)
{
// update pointers base at GUIDs to prevent access to non-existed already object
UpdatePointers();
// cancel at lost explicit target during cast
if (m_targets.GetObjectTargetGUID() && !m_targets.GetObjectTarget())
{
cancel();
return;
}
if (Player* playerCaster = m_caster->ToPlayer())
{
// now that we've done the basic check, now run the scripts
// should be done before the spell is actually executed
sScriptMgr->OnPlayerSpellCast(playerCaster, this, skipCheck);
// As of 3.0.2 pets begin attacking their owner's target immediately
// Let any pets know we've attacked something. Check DmgClass for harmful spells only
// This prevents spells such as Hunter's Mark from triggering pet attack
if (this->GetSpellInfo()->DmgClass != SPELL_DAMAGE_CLASS_NONE)
if (Pet* playerPet = playerCaster->GetPet())
if (playerPet->IsAlive() && playerPet->isControlled() && (m_targets.GetTargetMask() & TARGET_FLAG_UNIT))
playerPet->AI()->OwnerAttacked(m_targets.GetObjectTarget()->ToUnit());
}
SetExecutedCurrently(true);
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING))
if (m_caster->GetTypeId() == TYPEID_UNIT && m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget())
m_caster->SetInFront(m_targets.GetObjectTarget());
// Should this be done for original caster?
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
// Set spell which will drop charges for triggered cast spells
// if not successfully casted, will be remove in finish(false)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
}
CallScriptBeforeCastHandlers();
// skip check if done already (for instant cast spells for example)
if (!skipCheck)
{
SpellCastResult castResult = CheckCast(false);
if (castResult != SPELL_CAST_OK)
{
SendCastResult(castResult);
SendInterrupted(0);
//restore spell mods
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
m_caster->ToPlayer()->RestoreSpellMods(this);
// cleanup after mod system
// triggered spell pointer can be not removed in some cases
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
}
finish(false);
SetExecutedCurrently(false);
return;
}
// additional check after cast bar completes (must not be in CheckCast)
// if trade not complete then remember it in trade data
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (TradeData* my_trade = m_caster->ToPlayer()->GetTradeData())
{
if (!my_trade->IsInAcceptProcess())
{
// Spell will be casted at completing the trade. Silently ignore at this place
my_trade->SetSpell(m_spellInfo->Id, m_CastItem);
SendCastResult(SPELL_FAILED_DONT_REPORT);
SendInterrupted(0);
m_caster->ToPlayer()->RestoreSpellMods(this);
// cleanup after mod system
// triggered spell pointer can be not removed in some cases
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
finish(false);
SetExecutedCurrently(false);
return;
}
}
}
}
}
SelectSpellTargets();
// Spell may be finished after target map check
if (m_spellState == SPELL_STATE_FINISHED)
{
SendInterrupted(0);
//restore spell mods
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
m_caster->ToPlayer()->RestoreSpellMods(this);
// cleanup after mod system
// triggered spell pointer can be not removed in some cases
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
}
finish(false);
SetExecutedCurrently(false);
return;
}
PrepareTriggersExecutedOnHit();
CallScriptOnCastHandlers();
// traded items have trade slot instead of guid in m_itemTargetGUID
// set to real guid to be sent later to the client
m_targets.UpdateTradeSlotItem();
if (Player* player = m_caster->ToPlayer())
{
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM) && m_CastItem)
{
player->StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_ITEM, m_CastItem->GetEntry());
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
}
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
}
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST))
{
// Powers have to be taken before SendSpellGo
TakePower();
TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
}
else if (Item* targetItem = m_targets.GetItemTarget())
{
/// Not own traded item (in trader trade slot) req. reagents including triggered spell case
if (targetItem->GetOwnerGUID() != m_caster->GetGUID())
TakeReagents();
}
// CAST SPELL
SendSpellCooldown();
PrepareScriptHitHandlers();
HandleLaunchPhase();
// we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
SendSpellGo();
// Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
if ((m_spellInfo->Speed > 0.0f && !m_spellInfo->IsChanneled()) || m_spellInfo->AttributesEx4 & SPELL_ATTR4_UNK4)
{
// Remove used for cast item if need (it can be already NULL after TakeReagents call
// in case delayed spell remove item at cast delay start
TakeCastItem();
// Okay, maps created, now prepare flags
m_immediateHandled = false;
m_spellState = SPELL_STATE_DELAYED;
SetDelayStart(0);
if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
m_caster->ClearUnitState(UNIT_STATE_CASTING);
}
else
{
// Immediate spell, no big deal
handle_immediate();
}
CallScriptAfterCastHandlers();
if (const std::vector<int32> *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id))
{
for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
if (*i < 0)
m_caster->RemoveAurasDueToSpell(-(*i));
else
m_caster->CastSpell(m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster, *i, true);
}
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
//Clear spell cooldowns after every spell is cast if .cheat cooldown is enabled.
if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_COOLDOWN))
m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true);
}
SetExecutedCurrently(false);
}
void Spell::handle_immediate()
{
// start channeling if applicable
if (m_spellInfo->IsChanneled())
{
int32 duration = m_spellInfo->GetDuration();
if (duration > 0)
{
// First mod_duration then haste - see Missile Barrage
// Apply duration mod
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
// Apply haste mods
if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION)
m_caster->ModSpellCastTime(m_spellInfo, duration, this);
m_spellState = SPELL_STATE_CASTING;
m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags);
SendChannelStart(duration);
}
else if (duration == -1)
{
m_spellState = SPELL_STATE_CASTING;
m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags);
SendChannelStart(duration);
}
}
PrepareTargetProcessing();
// process immediate effects (items, ground, etc.) also initialize some variables
_handle_immediate_phase();
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
for (std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
FinishTargetProcessing();
// spell is finished, perform some last features of the spell here
_handle_finish_phase();
// Remove used for cast item if need (it can be already NULL after TakeReagents call
TakeCastItem();
// handle ammo consumption for thrown weapons
if (m_spellInfo->IsRangedWeaponSpell() && m_spellInfo->IsChanneled())
TakeAmmo();
if (m_spellState != SPELL_STATE_CASTING)
finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
}
uint64 Spell::handle_delayed(uint64 t_offset)
{
UpdatePointers();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
uint64 next_time = 0;
PrepareTargetProcessing();
if (!m_immediateHandled)
{
_handle_immediate_phase();
m_immediateHandled = true;
}
bool single_missile = (m_targets.HasDst());
// now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->processed == false)
{
if (single_missile || ihit->timeDelay <= t_offset)
{
ihit->timeDelay = t_offset;
DoAllEffectOnTarget(&(*ihit));
}
else if (next_time == 0 || ihit->timeDelay < next_time)
next_time = ihit->timeDelay;
}
}
// now recheck gameobject targeting correctness
for (std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
{
if (ighit->processed == false)
{
if (single_missile || ighit->timeDelay <= t_offset)
DoAllEffectOnTarget(&(*ighit));
else if (next_time == 0 || ighit->timeDelay < next_time)
next_time = ighit->timeDelay;
}
}
FinishTargetProcessing();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
// All targets passed - need finish phase
if (next_time == 0)
{
// spell is finished, perform some last features of the spell here
_handle_finish_phase();
finish(true); // successfully finish spell cast
// return zero, spell is finished now
return 0;
}
else
{
// spell is unfinished, return next execution time
return next_time;
}
}
void Spell::_handle_immediate_phase()
{
m_spellAura = NULL;
// initialize Diminishing Returns Data
m_diminishLevel = DIMINISHING_LEVEL_1;
m_diminishGroup = DIMINISHING_NONE;
// handle some immediate features of the spell here
HandleThreatSpells();
PrepareScriptHitHandlers();
// handle effects with SPELL_EFFECT_HANDLE_HIT mode
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
// don't do anything for empty effect
if (!m_spellInfo->Effects[j].IsEffect())
continue;
// call effect handlers to handle destination hit
HandleEffects(NULL, NULL, NULL, j, SPELL_EFFECT_HANDLE_HIT);
}
// process items
for (std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
if (!m_originalCaster)
return;
// Handle procs on cast
/// @todo finish new proc system:P
if (m_UniqueTargetInfo.empty() && m_targets.HasDst())
{
uint32 procAttacker = m_procAttacker;
if (!procAttacker)
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS;
// Proc the spells that have DEST target
m_originalCaster->ProcDamageAndSpell(NULL, procAttacker, 0, m_procEx | PROC_EX_NORMAL_HIT, 0, BASE_ATTACK, m_spellInfo, m_triggeredByAuraSpell);
}
}
void Spell::_handle_finish_phase()
{
if (m_caster->m_movedPlayer)
{
// Take for real after all targets are processed
if (m_needComboPoints)
m_caster->m_movedPlayer->ClearComboPoints();
// Real add combo points from effects
if (m_comboPointGain)
m_caster->m_movedPlayer->GainSpellComboPoints(m_comboPointGain);
if (m_spellInfo->PowerType == POWER_HOLY_POWER && m_caster->m_movedPlayer->getClass() == CLASS_PALADIN)
HandleHolyPower(m_caster->m_movedPlayer);
if (m_spellInfo->PowerType == POWER_CHI && m_caster->m_movedPlayer->getClass() == CLASS_MONK)
HandleChiPower(m_caster->m_movedPlayer);
}
if (m_caster->m_extraAttacks && GetSpellInfo()->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS))
m_caster->HandleProcExtraAttackFor(m_caster->GetVictim());
/// @todo trigger proc phase finish here
}
void Spell::SendSpellCooldown()
{
Player* _player = m_caster->ToPlayer();
if (!_player)
return;
// mana/health/etc potions, disabled by client (until combat out as declarate)
if (m_CastItem && (m_CastItem->IsPotion() || m_spellInfo->IsCooldownStartedOnEvent()))
{
// need in some way provided data for Spell::finish SendCooldownEvent
_player->SetLastPotionId(m_CastItem->GetEntry());
return;
}
// have infinity cooldown but set at aura apply // do not set cooldown for triggered spells (needed by reincarnation)
if (m_spellInfo->IsCooldownStartedOnEvent() || m_spellInfo->IsPassive() || (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD))
return;
_player->AddSpellAndCategoryCooldowns(m_spellInfo, m_CastItem ? m_CastItem->GetEntry() : 0, this);
}
void Spell::update(uint32 difftime)
{
// update pointers based at it's GUIDs
UpdatePointers();
if (m_targets.GetUnitTargetGUID() && !m_targets.GetUnitTarget())
{
TC_LOG_DEBUG("spells", "Spell %u is cancelled due to removal of target.", m_spellInfo->Id);
cancel();
return;
}
// check if the player caster has moved before the spell finished
// with the exception of spells affected with SPELL_AURA_CAST_WHILE_WALKING effect
if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) &&
(m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR)) &&
!m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo))
{
// don't cancel for melee, autorepeat, triggered and instant spells
if (!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered())
cancel();
}
switch (m_spellState)
{
case SPELL_STATE_PREPARING:
{
if (m_timer > 0)
{
if (difftime >= (uint32)m_timer)
m_timer = 0;
else
m_timer -= difftime;
}
if (m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
// don't CheckCast for instant spells - done in spell::prepare, skip duplicate checks, needed for range checks for example
cast(!m_casttime);
break;
}
case SPELL_STATE_CASTING:
{
if (m_timer)
{
// check if there are alive targets left
if (!UpdateChanneledTargetList())
{
TC_LOG_DEBUG("spells", "Channeled spell %d is removed due to lack of targets", m_spellInfo->Id);
SendChannelUpdate(0);
finish();
}
if (m_timer > 0)
{
if (difftime >= (uint32)m_timer)
m_timer = 0;
else
m_timer -= difftime;
}
}
if (m_timer == 0)
{
SendChannelUpdate(0);
finish();
}
break;
}
default:
break;
}
}
void Spell::finish(bool ok)
{
if (!m_caster)
return;
if (m_spellState == SPELL_STATE_FINISHED)
return;
m_spellState = SPELL_STATE_FINISHED;
if (m_spellInfo->IsChanneled())
m_caster->UpdateInterruptMask();
if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
m_caster->ClearUnitState(UNIT_STATE_CASTING);
// Unsummon summon as possessed creatures on spell cancel
if (m_spellInfo->IsChanneled() && m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (Unit* charm = m_caster->GetCharm())
if (charm->GetTypeId() == TYPEID_UNIT
&& charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET)
&& charm->GetUInt32Value(UNIT_FIELD_CREATED_BY_SPELL) == m_spellInfo->Id)
((Puppet*)charm)->UnSummon();
}
if (Creature* creatureCaster = m_caster->ToCreature())
creatureCaster->ReleaseFocus(this);
if (!ok)
return;
if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsSummon())
{
// Unsummon statue
uint32 spell = m_caster->GetUInt32Value(UNIT_FIELD_CREATED_BY_SPELL);
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell);
if (spellInfo && spellInfo->SpellIconID == 2056)
{
TC_LOG_DEBUG("spells", "Statue %d is unsummoned in spell %d finish", m_caster->GetGUIDLow(), m_spellInfo->Id);
m_caster->setDeathState(JUST_DIED);
return;
}
}
if (IsAutoActionResetSpell())
{
bool found = false;
Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET);
for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i)
{
if ((*i)->IsAffectingSpell(m_spellInfo))
{
found = true;
break;
}
}
if (!found && !(m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS))
{
m_caster->resetAttackTimer(BASE_ATTACK);
if (m_caster->haveOffhandWeapon())
m_caster->resetAttackTimer(OFF_ATTACK);
m_caster->resetAttackTimer(RANGED_ATTACK);
}
}
// potions disabled by client, send event "not in combat" if need
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (!m_triggeredByAuraSpell)
m_caster->ToPlayer()->UpdatePotionCooldown(this);
// triggered spell pointer can be not set in some cases
// this is needed for proper apply of triggered spell mods
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
// Take mods after trigger spell (needed for 14177 to affect 48664)
// mods are taken only on succesfull cast and independantly from targets of the spell
m_caster->ToPlayer()->RemoveSpellMods(this);
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
}
// Stop Attack for some spells
if (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET)
m_caster->AttackStop();
}
void Spell::SendCastResult(SpellCastResult result)
{
if (result == SPELL_CAST_OK)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
if (m_caster->ToPlayer()->GetSession()->PlayerLoading()) // don't send cast results at loading time
return;
SendCastResult(m_caster->ToPlayer(), m_spellInfo, m_cast_count, result, m_customError);
}
void Spell::SendPetCastResult(SpellCastResult result)
{
if (result == SPELL_CAST_OK)
return;
Unit* owner = m_caster->GetCharmerOrOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
SendCastResult(owner->ToPlayer(), m_spellInfo, m_cast_count, result, SPELL_CUSTOM_ERROR_NONE, SMSG_PET_CAST_FAILED);
}
void Spell::SendCastResult(Player* caster, SpellInfo const* spellInfo, uint8 cast_count, SpellCastResult result, SpellCustomErrors customError /*= SPELL_CUSTOM_ERROR_NONE*/, Opcodes opcode /*= SMSG_CAST_FAILED*/)
{
if (result == SPELL_CAST_OK)
return;
WorldPacket data(opcode, (4+1+1));
data << uint32(spellInfo->Id);
data << uint32(result); // problem
data << uint8(cast_count);
size_t pos = data.bitwpos();
data.WriteBit(1);
data.WriteBit(1);
data.FlushBits();
size_t dataPos = data.wpos();
switch (result)
{
case SPELL_FAILED_NOT_READY:
data << uint32(0); // unknown (value 1 update cooldowns on client flag)
break;
case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
data << uint32(spellInfo->RequiresSpellFocus); // SpellFocusObject.dbc id
break;
case SPELL_FAILED_REQUIRES_AREA: // AreaTable.dbc id
// hardcode areas limitation case
switch (spellInfo->Id)
{
case 41617: // Cenarion Mana Salve
case 41619: // Cenarion Healing Salve
data << uint32(3905);
break;
case 41618: // Bottled Nethergon Energy
case 41620: // Bottled Nethergon Vapor
data << uint32(3842);
break;
case 45373: // Bloodberry Elixir
data << uint32(4075);
break;
default: // default case (don't must be)
data << uint32(0);
break;
}
break;
case SPELL_FAILED_TOTEMS:
if (spellInfo->Totem[0])
data << uint32(spellInfo->Totem[0]);
if (spellInfo->Totem[1])
data << uint32(spellInfo->Totem[1]);
break;
case SPELL_FAILED_TOTEM_CATEGORY:
if (spellInfo->TotemCategory[0])
data << uint32(spellInfo->TotemCategory[0]);
if (spellInfo->TotemCategory[1])
data << uint32(spellInfo->TotemCategory[1]);
break;
case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
case SPELL_FAILED_EQUIPPED_ITEM_CLASS_MAINHAND:
case SPELL_FAILED_EQUIPPED_ITEM_CLASS_OFFHAND:
data << uint32(spellInfo->EquippedItemClass);
data << uint32(spellInfo->EquippedItemSubClassMask);
break;
case SPELL_FAILED_TOO_MANY_OF_ITEM:
{
uint32 item = 0;
for (int8 eff = 0; eff < MAX_SPELL_EFFECTS; eff++)
if (spellInfo->Effects[eff].ItemType)
item = spellInfo->Effects[eff].ItemType;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item);
if (proto && proto->ItemLimitCategory)
data << uint32(proto->ItemLimitCategory);
break;
}
case SPELL_FAILED_PREVENTED_BY_MECHANIC:
data << uint32(spellInfo->GetAllEffectsMechanicMask()); // SpellMechanic.dbc id
break;
case SPELL_FAILED_NEED_EXOTIC_AMMO:
data << uint32(spellInfo->EquippedItemSubClassMask); // seems correct...
break;
case SPELL_FAILED_NEED_MORE_ITEMS:
data << uint32(0); // Item id
data << uint32(0); // Item count?
break;
case SPELL_FAILED_MIN_SKILL:
data << uint32(0); // SkillLine.dbc id
data << uint32(0); // required skill value
break;
case SPELL_FAILED_FISHING_TOO_LOW:
data << uint32(0); // required fishing skill
break;
case SPELL_FAILED_CUSTOM_ERROR:
data << uint32(customError);
break;
case SPELL_FAILED_SILENCED:
data << uint32(0); // Unknown
break;
case SPELL_FAILED_REAGENTS:
{
uint32 missingItem = 0;
for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++)
{
if (spellInfo->Reagent[i] <= 0)
continue;
uint32 itemid = spellInfo->Reagent[i];
uint32 itemcount = spellInfo->ReagentCount[i];
if (!caster->HasItemCount(itemid, itemcount))
{
missingItem = itemid;
break;
}
}
data << uint32(missingItem); // first missing item
break;
}
// TODO: SPELL_FAILED_NOT_STANDING
default:
break;
}
if (int32 diff = data.wpos() - dataPos)
{
if ((diff / 4) == 1)
data.PutBits(pos, 0, 1);
else
data.PutBits(pos, 0, 2); // 1 and 1
}
caster->GetSession()->SendPacket(&data);
}
void Spell::SendSpellStart()
{
if (!IsNeedSendToClient())
return;
uint32 castFlags = CAST_FLAG_HAS_TRAJECTORY;
if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell)
castFlags |= CAST_FLAG_PENDING;
if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
(m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsPet()))
&& m_spellInfo->PowerType != POWER_HEALTH)
castFlags |= CAST_FLAG_POWER_LEFT_SELF;
if (m_spellInfo->RuneCostID && m_spellInfo->PowerType == POWER_RUNES)
castFlags |= CAST_FLAG_UNKNOWN_19;
ObjectGuid casterGuid = m_CastItem ? m_CastItem->GetGUID() : m_caster->GetGUID();
ObjectGuid casterUnitGuid = m_caster->GetGUID();
ObjectGuid targetGuid = m_targets.GetObjectTargetGUID();
ObjectGuid itemTargetGuid = m_targets.GetItemTargetGUID();
ObjectGuid unkGuid = 0;
bool hasDestLocation = (m_targets.GetTargetMask() & TARGET_FLAG_DEST_LOCATION) && m_targets.GetDst();
bool hasSourceLocation = (m_targets.GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) && m_targets.GetSrc();
bool hasTargetString = m_targets.GetTargetMask() & TARGET_FLAG_STRING;
bool hasPredictedHeal = castFlags & CAST_FLAG_HEAL_PREDICTION;
bool hasPredictedType = castFlags & CAST_FLAG_HEAL_PREDICTION;
bool hasTargetMask = m_targets.GetTargetMask() != 0;
bool hasCastImmunities = castFlags & CAST_FLAG_IMMUNITY;
bool hasCastSchoolImmunities = castFlags & CAST_FLAG_IMMUNITY;
bool hasElevation = castFlags & CAST_FLAG_ADJUST_MISSILE;
bool hasVisualChain = castFlags & CAST_FLAG_VISUAL_CHAIN;
bool hasAmmoInventoryType = castFlags & CAST_FLAG_PROJECTILE;
bool hasAmmoDisplayId = castFlags & CAST_FLAG_PROJECTILE;
uint8 runeCooldownPassedCount = (castFlags & CAST_FLAG_RUNE_LIST) && m_caster->GetTypeId() == TYPEID_PLAYER ? MAX_RUNES : 0;
uint8 predictedPowerCount = castFlags & CAST_FLAG_POWER_LEFT_SELF ? 1 : 0;
WorldPacket data(SMSG_SPELL_START, 25);
data.WriteBits(0, 24); // Miss Count (not used currently in SMSG_SPELL_START)
data.WriteBit(casterGuid[5]);
//for (uint32 i = 0; i < missCount; ++i)
//{
//}
data.WriteBit(1); // Unk read int8
data.WriteBit(0); // Fake Bit
data.WriteBit(casterUnitGuid[4]);
data.WriteBit(casterGuid[2]);
data.WriteBits(runeCooldownPassedCount, 3); // Rune Cooldown Passed Count
data.WriteBit(casterUnitGuid[2]);
data.WriteBit(casterUnitGuid[6]);
data.WriteBits(0, 25); // MissType Count (not used currently in SMSG_SPELL_START)
data.WriteBits(0, 13); // Unknown Bits
data.WriteBit(casterGuid[4]);
data.WriteBits(0, 24); // Hit Count (not used currently in SMSG_SPELL_START)
data.WriteBit(casterUnitGuid[7]);
//for (uint32 i = 0; i < hitCount; ++i)
//{
//}
data.WriteBit(hasSourceLocation);
data.WriteBits(predictedPowerCount, 21);
data.WriteBit(itemTargetGuid[3]);
data.WriteBit(itemTargetGuid[0]);
data.WriteBit(itemTargetGuid[1]);
data.WriteBit(itemTargetGuid[7]);
data.WriteBit(itemTargetGuid[2]);
data.WriteBit(itemTargetGuid[6]);
data.WriteBit(itemTargetGuid[4]);
data.WriteBit(itemTargetGuid[5]);
data.WriteBit(!hasElevation);
data.WriteBit(!hasTargetString);
data.WriteBit(!hasAmmoInventoryType);
data.WriteBit(hasDestLocation);
data.WriteBit(1); // Unk Read32
data.WriteBit(casterGuid[3]);
if (hasDestLocation)
{
ObjectGuid destTransportGuid = m_targets.GetDst()->_transportGUID;
data.WriteBit(destTransportGuid[1]);
data.WriteBit(destTransportGuid[6]);
data.WriteBit(destTransportGuid[2]);
data.WriteBit(destTransportGuid[7]);
data.WriteBit(destTransportGuid[0]);
data.WriteBit(destTransportGuid[3]);
data.WriteBit(destTransportGuid[5]);
data.WriteBit(destTransportGuid[4]);
}
data.WriteBit(!hasAmmoDisplayId);
if (hasSourceLocation)
{
ObjectGuid srcTransportGuid = m_targets.GetSrc()->_transportGUID;
data.WriteBit(srcTransportGuid[4]);
data.WriteBit(srcTransportGuid[3]);
data.WriteBit(srcTransportGuid[5]);
data.WriteBit(srcTransportGuid[1]);
data.WriteBit(srcTransportGuid[7]);
data.WriteBit(srcTransportGuid[0]);
data.WriteBit(srcTransportGuid[6]);
data.WriteBit(srcTransportGuid[2]);
}
data.WriteBit(0); // Fake Bit
data.WriteBit(casterGuid[6]);
data.WriteBit(unkGuid[2]);
data.WriteBit(unkGuid[1]);
data.WriteBit(unkGuid[7]);
data.WriteBit(unkGuid[6]);
data.WriteBit(unkGuid[0]);
data.WriteBit(unkGuid[5]);
data.WriteBit(unkGuid[3]);
data.WriteBit(unkGuid[4]);
data.WriteBit(!hasTargetMask);
if (hasTargetMask)
data.WriteBits(m_targets.GetTargetMask(), 20);
data.WriteBit(casterGuid[1]);
data.WriteBit(!hasPredictedHeal);
data.WriteBit(1); // Unk read int8
data.WriteBit(!hasCastSchoolImmunities);
data.WriteBit(casterUnitGuid[5]);
data.WriteBit(0); // Fake Bit
data.WriteBits(0, 20); // Extra Target Count (not used currently in SMSG_SPELL_START)
//for (uint32 i = 0; i < extraTargetCount; ++i)
//{
//}
data.WriteBit(targetGuid[1]);
data.WriteBit(targetGuid[4]);
data.WriteBit(targetGuid[6]);
data.WriteBit(targetGuid[7]);
data.WriteBit(targetGuid[5]);
data.WriteBit(targetGuid[3]);
data.WriteBit(targetGuid[0]);
data.WriteBit(targetGuid[2]);
data.WriteBit(casterGuid[0]);
data.WriteBit(casterUnitGuid[3]);
data.WriteBit(1); // Unk uint8
if (hasTargetString)
data.WriteBits(uint32(m_targets.GetTargetString().length()), 7);
//for (uint32 i = 0; i < missTypeCount; ++i)
//{
//}
data.WriteBit(!hasCastImmunities);
data.WriteBit(casterUnitGuid[1]);
data.WriteBit(hasVisualChain);
data.WriteBit(casterGuid[7]);
data.WriteBit(!hasPredictedType);
data.WriteBit(casterUnitGuid[0]);
data.FlushBits();
data.WriteByteSeq(itemTargetGuid[1]);
data.WriteByteSeq(itemTargetGuid[7]);
data.WriteByteSeq(itemTargetGuid[6]);
data.WriteByteSeq(itemTargetGuid[0]);
data.WriteByteSeq(itemTargetGuid[4]);
data.WriteByteSeq(itemTargetGuid[2]);
data.WriteByteSeq(itemTargetGuid[3]);
data.WriteByteSeq(itemTargetGuid[5]);
//for (uint32 i = 0; i < hitCount; ++i)
//{
//}
data.WriteByteSeq(targetGuid[4]);
data.WriteByteSeq(targetGuid[5]);
data.WriteByteSeq(targetGuid[1]);
data.WriteByteSeq(targetGuid[7]);
data.WriteByteSeq(targetGuid[6]);
data.WriteByteSeq(targetGuid[3]);
data.WriteByteSeq(targetGuid[2]);
data.WriteByteSeq(targetGuid[0]);
data << uint32(m_casttime);
data.WriteByteSeq(unkGuid[4]);
data.WriteByteSeq(unkGuid[5]);
data.WriteByteSeq(unkGuid[3]);
data.WriteByteSeq(unkGuid[2]);
data.WriteByteSeq(unkGuid[1]);
data.WriteByteSeq(unkGuid[6]);
data.WriteByteSeq(unkGuid[7]);
data.WriteByteSeq(unkGuid[0]);
if (hasDestLocation)
{
float x, y, z;
ObjectGuid destTransportGuid = m_targets.GetDst()->_transportGUID;
if (destTransportGuid)
m_targets.GetDst()->_transportOffset.GetPosition(x, y, z);
else
m_targets.GetDst()->_position.GetPosition(x, y, z);
data.WriteByteSeq(destTransportGuid[4]);
data.WriteByteSeq(destTransportGuid[0]);
data.WriteByteSeq(destTransportGuid[5]);
data.WriteByteSeq(destTransportGuid[7]);
data.WriteByteSeq(destTransportGuid[1]);
data.WriteByteSeq(destTransportGuid[2]);
data.WriteByteSeq(destTransportGuid[3]);
data << y;
data << z;
data.WriteByteSeq(destTransportGuid[6]);
data << x;
}
//for (uint32 i = 0; i < extraTargetCount; ++i)
//{
//}
if (hasSourceLocation)
{
float x, y, z;
ObjectGuid srcTransportGuid = m_targets.GetSrc()->_transportGUID;
if (srcTransportGuid)
m_targets.GetSrc()->_transportOffset.GetPosition(x, y, z);
else
m_targets.GetSrc()->_position.GetPosition(x, y, z);
data.WriteByteSeq(srcTransportGuid[0]);
data.WriteByteSeq(srcTransportGuid[5]);
data.WriteByteSeq(srcTransportGuid[4]);
data.WriteByteSeq(srcTransportGuid[7]);
data.WriteByteSeq(srcTransportGuid[3]);
data.WriteByteSeq(srcTransportGuid[6]);
data << x;
data.WriteByteSeq(srcTransportGuid[2]);
data << z;
data.WriteByteSeq(srcTransportGuid[1]);
data << y;
}
data.WriteByteSeq(casterGuid[4]);
//for (uint32 i = 0; i < missCount; ++i)
//{
//}
if (hasCastSchoolImmunities)
data << uint32(0);
data.WriteByteSeq(casterGuid[2]);
if (hasCastImmunities)
data << uint32(0);
if (hasVisualChain)
{
data << uint32(0);
data << uint32(0);
}
if (predictedPowerCount > 0)
{
/*for (uint32 i = 0; i < powerUnitPowerCount; ++i)
{
data << int32(powerValue);
data << uint8(powerType);
}*/
data << uint8(m_spellInfo->PowerType);
data << int32(m_caster->GetPower((Powers)m_spellInfo->PowerType));
}
data << uint32(castFlags);
data.WriteByteSeq(casterGuid[5]);
data.WriteByteSeq(casterGuid[7]);
data.WriteByteSeq(casterGuid[1]);
data << uint8(m_cast_count);
data.WriteByteSeq(casterUnitGuid[7]);
data.WriteByteSeq(casterUnitGuid[0]);
data.WriteByteSeq(casterGuid[6]);
data.WriteByteSeq(casterGuid[0]);
data.WriteByteSeq(casterUnitGuid[1]);
if (hasAmmoInventoryType)
data << uint8(0);
if (hasPredictedHeal)
data << uint32(0);
data.WriteByteSeq(casterUnitGuid[6]);
data.WriteByteSeq(casterUnitGuid[3]);
data << uint32(m_spellInfo->Id);
if (hasAmmoDisplayId)
data << uint32(0);
data.WriteByteSeq(casterUnitGuid[4]);
data.WriteByteSeq(casterUnitGuid[5]);
data.WriteByteSeq(casterUnitGuid[2]);
if (hasTargetString)
data.WriteString(m_targets.GetTargetString());
if (hasPredictedType)
data << uint8(0);
data.WriteByteSeq(casterGuid[3]);
if (hasElevation)
data << float(m_targets.GetElevation());
for (uint8 i = 0; i < runeCooldownPassedCount; ++i)
{
// float casts ensure the division is performed on floats as we need float result
float baseCd = float(m_caster->ToPlayer()->GetRuneBaseCooldown(i));
data << uint8((baseCd - float(m_caster->ToPlayer()->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed
}
m_caster->SendMessageToSet(&data, true);
}
void Spell::SendSpellGo()
{
// not send invisible spell casting
if (!IsNeedSendToClient())
return;
//TC_LOG_DEBUG("spells", "Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
uint32 castFlags = CAST_FLAG_UNKNOWN_9;
// triggered spells with spell visual != 0
if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell)
castFlags |= CAST_FLAG_PENDING;
if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
(m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsPet()))
&& m_spellInfo->PowerType != POWER_HEALTH)
castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible
if ((m_caster->GetTypeId() == TYPEID_PLAYER)
&& (m_caster->getClass() == CLASS_DEATH_KNIGHT)
&& m_spellInfo->RuneCostID
&& m_spellInfo->PowerType == POWER_RUNES)
{
castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
}
if (m_spellInfo->HasEffect(SPELL_EFFECT_ACTIVATE_RUNE))
{
castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
}
if (m_targets.HasTraj())
castFlags |= CAST_FLAG_ADJUST_MISSILE;
ObjectGuid casterGuid = m_CastItem ? m_CastItem->GetGUID() : m_caster->GetGUID();
ObjectGuid casterUnitGuid = m_caster->GetGUID();
ObjectGuid targetGuid = m_targets.GetObjectTargetGUID();
ObjectGuid itemTargetGuid = m_targets.GetItemTargetGUID();
ObjectGuid unkGuid = 0;
bool hasDestLocation = (m_targets.GetTargetMask() & TARGET_FLAG_DEST_LOCATION) && m_targets.GetDst();
bool hasSourceLocation = (m_targets.GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) && m_targets.GetSrc();
bool hasDestUnkByte = m_targets.GetTargetMask() & TARGET_FLAG_DEST_LOCATION;
bool hasTargetString = m_targets.GetTargetMask() & TARGET_FLAG_STRING;
bool hasPredictedHeal = castFlags & CAST_FLAG_HEAL_PREDICTION;
bool hasPredictedType = castFlags & CAST_FLAG_HEAL_PREDICTION;
bool hasTargetMask = m_targets.GetTargetMask() != 0;
bool hasCastImmunities = castFlags & CAST_FLAG_IMMUNITY;
bool hasCastSchoolImmunities = castFlags & CAST_FLAG_IMMUNITY;
bool hasElevation = castFlags & CAST_FLAG_ADJUST_MISSILE;
bool hasDelayTime = castFlags & CAST_FLAG_ADJUST_MISSILE;
bool hasVisualChain = castFlags & CAST_FLAG_VISUAL_CHAIN;
bool hasAmmoInventoryType = castFlags & CAST_FLAG_PROJECTILE;
bool hasAmmoDisplayId = castFlags & CAST_FLAG_PROJECTILE;
bool hasRunesStateBefore = (castFlags & CAST_FLAG_RUNE_LIST) && m_caster->GetTypeId() == TYPEID_PLAYER;
bool hasRunesStateAfter = (castFlags & CAST_FLAG_RUNE_LIST) && m_caster->GetTypeId() == TYPEID_PLAYER;
uint8 predictedPowerCount = castFlags & CAST_FLAG_POWER_LEFT_SELF ? 1 : 0;
uint8 runeCooldownPassedCount = (castFlags & CAST_FLAG_RUNE_LIST) && m_caster->GetTypeId() == TYPEID_PLAYER ? MAX_RUNES : 0;
// This function also fill data for channeled spells:
// m_needAliveTargetMask req for stop channelig if one target die
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
// possibly SPELL_MISS_IMMUNE2 for this??
ihit->missCondition = SPELL_MISS_IMMUNE2;
}
WorldPacket data(SMSG_SPELL_GO, 25);
data.WriteBit(casterUnitGuid[2]);
data.WriteBit(1); // hasAmmoDisplayType
data.WriteBit(hasSourceLocation);
data.WriteBit(casterGuid[2]);
if (hasSourceLocation)
{
ObjectGuid srcTransportGuid = m_targets.GetSrc()->_transportGUID;
data.WriteBit(srcTransportGuid[3]);
data.WriteBit(srcTransportGuid[7]);
data.WriteBit(srcTransportGuid[4]);
data.WriteBit(srcTransportGuid[2]);
data.WriteBit(srcTransportGuid[0]);
data.WriteBit(srcTransportGuid[6]);
data.WriteBit(srcTransportGuid[1]);
data.WriteBit(srcTransportGuid[5]);
}
data.WriteBit(casterGuid[6]);
data.WriteBit(!hasDestUnkByte);
data.WriteBit(casterUnitGuid[7]);
data.WriteBits(0, 20); // Extra Target Count
size_t missTypeCountPos = data.bitwpos();
data.WriteBits(0, 25); // Miss Type Count
size_t missCountPos = data.bitwpos();
data.WriteBits(0, 24); // Miss Count
data.WriteBit(casterUnitGuid[1]);
data.WriteBit(casterGuid[0]);
data.WriteBits(0, 13); // Unknown bits
uint32 missCount = 0;
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition != SPELL_MISS_NONE)
{
ObjectGuid missGuid = ihit->targetGUID;
data.WriteBit(missGuid[1]);
data.WriteBit(missGuid[3]);
data.WriteBit(missGuid[6]);
data.WriteBit(missGuid[4]);
data.WriteBit(missGuid[5]);
data.WriteBit(missGuid[2]);
data.WriteBit(missGuid[0]);
data.WriteBit(missGuid[7]);
missCount++;
}
}
data.PutBits(missCountPos, missCount, 24);
//for (uint32 i = 0; i < extraTargetCount; ++i)
//{
//}
data.WriteBit(casterUnitGuid[5]);
data.WriteBit(0); // Fake bit
data.WriteBit(0); // Fake bit
data.WriteBit(!hasTargetString);
data.WriteBit(itemTargetGuid[7]);
data.WriteBit(itemTargetGuid[2]);
data.WriteBit(itemTargetGuid[1]);
data.WriteBit(itemTargetGuid[3]);
data.WriteBit(itemTargetGuid[6]);
data.WriteBit(itemTargetGuid[0]);
data.WriteBit(itemTargetGuid[5]);
data.WriteBit(itemTargetGuid[4]);
data.WriteBit(casterGuid[7]);
data.WriteBit(targetGuid[0]);
data.WriteBit(targetGuid[6]);
data.WriteBit(targetGuid[5]);
data.WriteBit(targetGuid[7]);
data.WriteBit(targetGuid[4]);
data.WriteBit(targetGuid[2]);
data.WriteBit(targetGuid[3]);
data.WriteBit(targetGuid[1]);
data.WriteBit(!hasRunesStateBefore);
data.WriteBits(predictedPowerCount, 21); // predictedPowerCount
data.WriteBit(casterGuid[1]);
data.WriteBit(!hasPredictedType);
data.WriteBit(!hasTargetMask);
data.WriteBit(casterUnitGuid[3]);
if (hasTargetString)
data.WriteBits(uint32(m_targets.GetTargetString().length()), 7);
data.WriteBit(1); // Missing Predict heal
data.WriteBit(0); // hasPowerData
data.WriteBit(1); // has castImmunitiy
data.WriteBit(casterUnitGuid[6]);
data.WriteBit(0); // Fake bit
data.WriteBit(hasVisualChain);
data.WriteBit(unkGuid[7]);
data.WriteBit(unkGuid[6]);
data.WriteBit(unkGuid[1]);
data.WriteBit(unkGuid[2]);
data.WriteBit(unkGuid[0]);
data.WriteBit(unkGuid[5]);
data.WriteBit(unkGuid[3]);
data.WriteBit(unkGuid[4]);
data.WriteBit(!hasDelayTime);
data.WriteBit(1); // has School Immunities
data.WriteBits(runeCooldownPassedCount, 3); // runeCooldownPassedCount
data.WriteBit(casterUnitGuid[0]);
uint32 missTypeCount = 0;
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition != SPELL_MISS_NONE)
{
data.WriteBits(ihit->missCondition, 4);
if (ihit->missCondition == SPELL_MISS_REFLECT)
data.WriteBits(ihit->reflectResult, 4);
++missTypeCount;
}
}
data.PutBits(missTypeCountPos, missTypeCount, 25);
if (hasTargetMask)
data.WriteBits(m_targets.GetTargetMask(), 20);
data.WriteBit(!hasElevation);
data.WriteBit(!hasRunesStateAfter);
data.WriteBit(casterGuid[4]);
data.WriteBit(1); // hasAmmodisplayID
data.WriteBit(hasDestLocation);
data.WriteBit(casterGuid[5]);
size_t hitCountPos = data.bitwpos();
data.WriteBits(0, 24); // Hit Count
if (hasDestLocation)
{
ObjectGuid destTransportGuid = m_targets.GetDst()->_transportGUID;
data.WriteBit(destTransportGuid[0]);
data.WriteBit(destTransportGuid[3]);
data.WriteBit(destTransportGuid[2]);
data.WriteBit(destTransportGuid[1]);
data.WriteBit(destTransportGuid[4]);
data.WriteBit(destTransportGuid[5]);
data.WriteBit(destTransportGuid[6]);
data.WriteBit(destTransportGuid[7]);
}
data.WriteBit(casterUnitGuid[4]);
uint32 hitCount = 0;
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if ((*ihit).missCondition == SPELL_MISS_NONE)
{
ObjectGuid hitGuid = ihit->targetGUID;
data.WriteBit(hitGuid[2]);
data.WriteBit(hitGuid[7]);
data.WriteBit(hitGuid[1]);
data.WriteBit(hitGuid[6]);
data.WriteBit(hitGuid[4]);
data.WriteBit(hitGuid[5]);
data.WriteBit(hitGuid[0]);
data.WriteBit(hitGuid[3]);
m_channelTargetEffectMask |= ihit->effectMask;
++hitCount;
}
}
for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
{
ObjectGuid hitGuid = ighit->targetGUID; // Always hits
data.WriteBit(hitGuid[2]);
data.WriteBit(hitGuid[7]);
data.WriteBit(hitGuid[1]);
data.WriteBit(hitGuid[6]);
data.WriteBit(hitGuid[4]);
data.WriteBit(hitGuid[5]);
data.WriteBit(hitGuid[0]);
data.WriteBit(hitGuid[3]);
++hitCount;
}
data.PutBits(hitCountPos, hitCount, 24);
data.WriteBit(casterGuid[3]);
data.FlushBits();
data.WriteByteSeq(targetGuid[5]);
data.WriteByteSeq(targetGuid[2]);
data.WriteByteSeq(targetGuid[1]);
data.WriteByteSeq(targetGuid[6]);
data.WriteByteSeq(targetGuid[0]);
data.WriteByteSeq(targetGuid[3]);
data.WriteByteSeq(targetGuid[4]);
data.WriteByteSeq(targetGuid[7]);
data.WriteByteSeq(itemTargetGuid[5]);
data.WriteByteSeq(itemTargetGuid[2]);
data.WriteByteSeq(itemTargetGuid[0]);
data.WriteByteSeq(itemTargetGuid[6]);
data.WriteByteSeq(itemTargetGuid[7]);
data.WriteByteSeq(itemTargetGuid[3]);
data.WriteByteSeq(itemTargetGuid[1]);
data.WriteByteSeq(itemTargetGuid[4]);
data.WriteByteSeq(casterGuid[2]);
//for (uint32 i = 0; i < extraTargetCount; ++i)
//{
//}
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if ((*ihit).missCondition == SPELL_MISS_NONE)
{
ObjectGuid hitGuid = ihit->targetGUID;
data.WriteByteSeq(hitGuid[0]);
data.WriteByteSeq(hitGuid[6]);
data.WriteByteSeq(hitGuid[2]);
data.WriteByteSeq(hitGuid[7]);
data.WriteByteSeq(hitGuid[5]);
data.WriteByteSeq(hitGuid[4]);
data.WriteByteSeq(hitGuid[3]);
data.WriteByteSeq(hitGuid[1]);
}
}
for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
{
ObjectGuid hitGuid = ighit->targetGUID; // Always hits
data.WriteByteSeq(hitGuid[0]);
data.WriteByteSeq(hitGuid[6]);
data.WriteByteSeq(hitGuid[2]);
data.WriteByteSeq(hitGuid[7]);
data.WriteByteSeq(hitGuid[5]);
data.WriteByteSeq(hitGuid[4]);
data.WriteByteSeq(hitGuid[3]);
data.WriteByteSeq(hitGuid[1]);
}
data.WriteByteSeq(unkGuid[6]);
data.WriteByteSeq(unkGuid[2]);
data.WriteByteSeq(unkGuid[7]);
data.WriteByteSeq(unkGuid[1]);
data.WriteByteSeq(unkGuid[4]);
data.WriteByteSeq(unkGuid[3]);
data.WriteByteSeq(unkGuid[5]);
data.WriteByteSeq(unkGuid[0]);
if (hasDelayTime)
data << uint32(m_delayMoment);
data << uint32(getMSTime());
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition != SPELL_MISS_NONE)
{
ObjectGuid missGuid = ihit->targetGUID;
data.WriteByteSeq(missGuid[4]);
data.WriteByteSeq(missGuid[2]);
data.WriteByteSeq(missGuid[0]);
data.WriteByteSeq(missGuid[6]);
data.WriteByteSeq(missGuid[7]);
data.WriteByteSeq(missGuid[5]);
data.WriteByteSeq(missGuid[1]);
data.WriteByteSeq(missGuid[3]);
}
}
if (hasDestLocation)
{
float x, y, z;
ObjectGuid destTransportGuid = m_targets.GetDst()->_transportGUID;
if (destTransportGuid)
m_targets.GetDst()->_transportOffset.GetPosition(x, y, z);
else
m_targets.GetDst()->_position.GetPosition(x, y, z);
data << z;
data << y;
data.WriteByteSeq(destTransportGuid[4]);
data.WriteByteSeq(destTransportGuid[5]);
data.WriteByteSeq(destTransportGuid[7]);
data.WriteByteSeq(destTransportGuid[6]);
data.WriteByteSeq(destTransportGuid[1]);
data.WriteByteSeq(destTransportGuid[2]);
data << x;
data.WriteByteSeq(destTransportGuid[0]);
data.WriteByteSeq(destTransportGuid[3]);
}
data.WriteByteSeq(casterGuid[6]);
data.WriteByteSeq(casterUnitGuid[7]);
data.WriteByteSeq(casterGuid[1]);
if (hasVisualChain)
{
data << uint32(0);
data << uint32(0);
}
data << uint32(castFlags);
if (hasSourceLocation)
{
float x, y, z;
ObjectGuid srcTransportGuid = m_targets.GetSrc()->_transportGUID;
if (srcTransportGuid)
m_targets.GetSrc()->_transportOffset.GetPosition(x, y, z);
else
m_targets.GetSrc()->_position.GetPosition(x, y, z);
data.WriteByteSeq(srcTransportGuid[2]);
data << y;
data << x;
data.WriteByteSeq(srcTransportGuid[6]);
data.WriteByteSeq(srcTransportGuid[5]);
data.WriteByteSeq(srcTransportGuid[1]);
data.WriteByteSeq(srcTransportGuid[7]);
data << z;
data.WriteByteSeq(srcTransportGuid[3]);
data.WriteByteSeq(srcTransportGuid[0]);
data.WriteByteSeq(srcTransportGuid[4]);
}
data.WriteByteSeq(casterUnitGuid[6]);
if (hasPredictedType)
data << uint8(0);
data.WriteByteSeq(casterGuid[4]);
data.WriteByteSeq(casterUnitGuid[1]);
if (predictedPowerCount > 0)
{
//for (uint32 i = 0; i < powerUnitPowerCount; ++i)
//{
// data << int32(powerValue);
// data << uint8(powerType);
//}
data << uint8(m_spellInfo->PowerType);
data << int32(m_caster->GetPower((Powers)m_spellInfo->PowerType));
}
if (hasRunesStateAfter)
data << uint8(m_caster->ToPlayer()->GetRunesState());
for (uint8 i = 0; i < runeCooldownPassedCount; ++i)
{
// float casts ensure the division is performed on floats as we need float result
float baseCd = float(m_caster->ToPlayer()->GetRuneBaseCooldown(i));
data << uint8((baseCd - float(m_caster->ToPlayer()->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed
}
if (hasRunesStateBefore)
data << uint8(m_runesState);
data.WriteByteSeq(casterGuid[0]);
if (hasDestUnkByte)
data << uint8(0);
data << uint8(m_cast_count);
data.WriteByteSeq(casterGuid[5]);
data.WriteByteSeq(casterUnitGuid[2]);
data.WriteByteSeq(casterGuid[3]);
data.WriteByteSeq(casterUnitGuid[5]);
if (hasTargetString)
data.WriteString(m_targets.GetTargetString());
data << uint32(m_spellInfo->Id);
if (hasElevation)
data << m_targets.GetElevation();
data.WriteByteSeq(casterUnitGuid[0]);
data.WriteByteSeq(casterUnitGuid[3]);
data.WriteByteSeq(casterUnitGuid[4]);
data.WriteByteSeq(casterGuid[7]);
// Reset m_needAliveTargetMask for non channeled spell
if (!m_spellInfo->IsChanneled())
m_channelTargetEffectMask = 0;
m_caster->SendMessageToSet(&data, true);
}
void Spell::SendLogExecute()
{
ObjectGuid guid = m_caster->GetGUID();
// TODO: Finish me
WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
/*
data.WriteBit(0);
data.WriteBit(guid[6]);
data.WriteBits(0, 19); // Count
data.WriteBit(guid[1]);
data.WriteBit(guid[4]);
data.WriteBit(guid[7]);
data.WriteBit(guid[5]);
data.WriteBit(guid[0]);
data.WriteBit(guid[2]);
data.WriteBit(guid[3]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data << uint32(m_spellInfo->Id);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[4]);
*/
data.append(m_caster->GetPackGUID());
data << uint32(m_spellInfo->Id);
uint8 effCount = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (m_effectExecuteData[i])
++effCount;
}
if (!effCount)
return;
data << uint32(effCount);
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!m_effectExecuteData[i])
continue;
data << uint32(m_spellInfo->Effects[i].Effect); // spell effect
data.append(*m_effectExecuteData[i]);
delete m_effectExecuteData[i];
m_effectExecuteData[i] = NULL;
}
m_caster->SendMessageToSet(&data, true);
}
void Spell::ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit* target, uint32 powerType, uint32 powerTaken, float gainMultiplier)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(target->GetPackGUID());
*m_effectExecuteData[effIndex] << uint32(powerTaken);
*m_effectExecuteData[effIndex] << uint32(powerType);
*m_effectExecuteData[effIndex] << float(gainMultiplier);
}
void Spell::ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit* victim, uint32 attCount)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(victim->GetPackGUID());
*m_effectExecuteData[effIndex] << uint32(attCount);
}
void Spell::ExecuteLogEffectInterruptCast(uint8 /*effIndex*/, Unit* victim, uint32 spellId)
{
ObjectGuid casterGuid = m_caster->GetGUID();
ObjectGuid targetGuid = victim->GetGUID();
WorldPacket data(SMSG_SPELLINTERRUPTLOG, 8 + 8 + 4 + 4);
data.WriteBit(targetGuid[4]);
data.WriteBit(casterGuid[5]);
data.WriteBit(casterGuid[6]);
data.WriteBit(casterGuid[1]);
data.WriteBit(casterGuid[3]);
data.WriteBit(casterGuid[0]);
data.WriteBit(targetGuid[3]);
data.WriteBit(targetGuid[5]);
data.WriteBit(targetGuid[1]);
data.WriteBit(casterGuid[4]);
data.WriteBit(casterGuid[7]);
data.WriteBit(targetGuid[7]);
data.WriteBit(targetGuid[6]);
data.WriteBit(targetGuid[2]);
data.WriteBit(casterGuid[2]);
data.WriteBit(targetGuid[0]);
data.WriteByteSeq(casterGuid[7]);
data.WriteByteSeq(casterGuid[6]);
data.WriteByteSeq(casterGuid[3]);
data.WriteByteSeq(casterGuid[2]);
data.WriteByteSeq(targetGuid[3]);
data.WriteByteSeq(targetGuid[6]);
data.WriteByteSeq(targetGuid[2]);
data.WriteByteSeq(targetGuid[4]);
data.WriteByteSeq(targetGuid[7]);
data.WriteByteSeq(targetGuid[0]);
data.WriteByteSeq(casterGuid[4]);
data << uint32(m_spellInfo->Id);
data.WriteByteSeq(targetGuid[1]);
data.WriteByteSeq(casterGuid[0]);
data.WriteByteSeq(casterGuid[5]);
data.WriteByteSeq(casterGuid[1]);
data << uint32(spellId);
data.WriteByteSeq(targetGuid[5]);
m_caster->SendMessageToSet(&data, true);
}
void Spell::ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit* victim, int32 itemId, int32 slot)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(victim->GetPackGUID());
*m_effectExecuteData[effIndex] << int32(itemId);
*m_effectExecuteData[effIndex] << int32(slot);
}
void Spell::ExecuteLogEffectOpenLock(uint8 effIndex, Object* obj)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(obj->GetPackGUID());
}
void Spell::ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry)
{
InitEffectExecuteData(effIndex);
*m_effectExecuteData[effIndex] << uint32(entry);
}
void Spell::ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry)
{
InitEffectExecuteData(effIndex);
*m_effectExecuteData[effIndex] << uint32(entry);
}
void Spell::ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject* obj)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(obj->GetPackGUID());
}
void Spell::ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject* obj)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(obj->GetPackGUID());
}
void Spell::ExecuteLogEffectResurrect(uint8 effIndex, Unit* target)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(target->GetPackGUID());
}
void Spell::SendInterrupted(uint8 result)
{
ObjectGuid guid = m_caster->GetGUID();
WorldPacket data(SMSG_SPELL_FAILURE, (8 + 4 + 1));
data.WriteBit(guid[7]);
data.WriteBit(guid[3]);
data.WriteBit(guid[6]);
data.WriteBit(guid[2]);
data.WriteBit(guid[1]);
data.WriteBit(guid[5]);
data.WriteBit(guid[0]);
data.WriteBit(guid[4]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[1]);
data << uint8(m_cast_count);
data << uint32(m_spellInfo->Id);
data << uint8(result); // problem
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[5]);
m_caster->SendMessageToSet(&data, true);
data.Initialize(SMSG_SPELL_FAILED_OTHER, (8 + 4 + 1));
data.WriteBit(guid[7]);
data.WriteBit(guid[0]);
data.WriteBit(guid[5]);
data.WriteBit(guid[6]);
data.WriteBit(guid[1]);
data.WriteBit(guid[4]);
data.WriteBit(guid[3]);
data.WriteBit(guid[2]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[1]);
data << uint8(result);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[6]);
data << uint32(m_spellInfo->Id);
data << uint8(m_cast_count);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[3]);
m_caster->SendMessageToSet(&data, true);
}
void Spell::SendChannelUpdate(uint32 time)
{
if (time == 0)
{
m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
m_caster->SetUInt32Value(UNIT_FIELD_CHANNEL_SPELL, 0);
}
WorldPacket data(MSG_CHANNEL_UPDATE, 8+4);
data.append(m_caster->GetPackGUID());
data << uint32(time);
m_caster->SendMessageToSet(&data, true);
}
void Spell::SendChannelStart(uint32 duration)
{
uint64 channelTarget = m_targets.GetObjectTargetGUID();
if (!channelTarget && !m_spellInfo->NeedsExplicitUnitTarget())
if (m_UniqueTargetInfo.size() + m_UniqueGOTargetInfo.size() == 1) // this is for TARGET_SELECT_CATEGORY_NEARBY
channelTarget = !m_UniqueTargetInfo.empty() ? m_UniqueTargetInfo.front().targetGUID : m_UniqueGOTargetInfo.front().targetGUID;
WorldPacket data(MSG_CHANNEL_START, (8+4+4));
data.append(m_caster->GetPackGUID());
data << uint32(m_spellInfo->Id);
data << uint32(duration);
data << uint8(0); // immunity (castflag & 0x04000000)
/*
if (immunity)
{
data << uint32(); // CastSchoolImmunities
data << uint32(); // CastImmunities
}
*/
data << uint8(0); // healPrediction (castflag & 0x40000000)
/*
if (healPrediction)
{
data.appendPackGUID(channelTarget); // target packguid
data << uint32(); // spellid
data << uint8(0); // unk3
if (unk3 == 2)
data.append(); // unk packed guid (unused ?)
}
*/
m_caster->SendMessageToSet(&data, true);
m_timer = duration;
if (channelTarget)
m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, channelTarget);
m_caster->SetUInt32Value(UNIT_FIELD_CHANNEL_SPELL, m_spellInfo->Id);
}
void Spell::SendResurrectRequest(Player* target)
{
// get ressurector name for creature resurrections, otherwise packet will be not accepted
// for player resurrections the name is looked up by guid
std::string const sentName(m_caster->GetTypeId() == TYPEID_PLAYER
? ""
: m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex()));
WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+sentName.size()+1+1+1+4));
data << uint64(m_caster->GetGUID());
data << uint32(sentName.size() + 1);
data << sentName;
data << uint8(0); // null terminator
data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1); // "you'll be afflicted with resurrection sickness"
// override delay sent with SMSG_CORPSE_RECLAIM_DELAY, set instant resurrection for spells with this attribute
// 4.2.2 edit : id of the spell used to resurect. (used client-side for Mass Resurect)
data << uint32(m_spellInfo->Id);
target->GetSession()->SendPacket(&data);
}
void Spell::TakeCastItem()
{
if (!m_CastItem)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
// not remove cast item at triggered spell (equipping, weapon damage, etc)
if (_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM)
return;
ItemTemplate const* proto = m_CastItem->GetTemplate();
if (!proto)
{
// This code is to avoid a crash
// I'm not sure, if this is really an error, but I guess every item needs a prototype
TC_LOG_ERROR("spells", "Cast item has no item prototype highId=%d, lowId=%d", m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
return;
}
bool expendable = false;
bool withoutCharges = false;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
if (proto->Spells[i].SpellId)
{
// item has limited charges
if (proto->Spells[i].SpellCharges)
{
if (proto->Spells[i].SpellCharges < 0)
expendable = true;
int32 charges = m_CastItem->GetSpellCharges(i);
// item has charges left
if (charges)
{
(charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
if (proto->Stackable == 1)
m_CastItem->SetSpellCharges(i, charges);
m_CastItem->SetState(ITEM_CHANGED, player);
}
// all charges used
withoutCharges = (charges == 0);
}
}
}
if (expendable && withoutCharges)
{
uint32 count = 1;
m_caster->ToPlayer()->DestroyItemCount(m_CastItem, count, true);
// prevent crash at access to deleted m_targets.GetItemTarget
if (m_CastItem == m_targets.GetItemTarget())
m_targets.SetItemTarget(NULL);
m_CastItem = NULL;
}
}
void Spell::TakePower()
{
if (m_CastItem || m_triggeredByAuraSpell)
return;
//Don't take power if the spell is cast while .cheat power is enabled.
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_POWER))
return;
}
Powers powerType = Powers(m_spellInfo->PowerType);
bool hit = true;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (powerType == POWER_RAGE || powerType == POWER_ENERGY || powerType == POWER_RUNES)
if (uint64 targetGUID = m_targets.GetUnitTargetGUID())
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if (ihit->targetGUID == targetGUID)
{
if (ihit->missCondition != SPELL_MISS_NONE)
{
hit = false;
//lower spell cost on fail (by talent aura)
if (Player* modOwner = m_caster->ToPlayer()->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost);
}
break;
}
}
if (powerType == POWER_RUNES)
{
TakeRunePower(hit);
return;
}
if (!m_powerCost)
return;
// health as power used
if (powerType == POWER_HEALTH)
{
m_caster->ModifyHealth(-(int32)m_powerCost);
return;
}
if (powerType >= MAX_POWERS)
{
TC_LOG_ERROR("spells", "Spell::TakePower: Unknown power type '%d'", powerType);
return;
}
if (hit)
m_caster->ModifyPower(powerType, -m_powerCost);
else
m_caster->ModifyPower(powerType, -irand(0, m_powerCost/4));
}
void Spell::TakeAmmo()
{
if (m_attackType == RANGED_ATTACK && m_caster->GetTypeId() == TYPEID_PLAYER)
{
Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK);
// wands don't have ammo
if (!pItem || pItem->IsBroken() || pItem->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_WAND)
return;
if (pItem->GetTemplate()->InventoryType == INVTYPE_THROWN)
{
if (pItem->GetMaxStackCount() == 1)
{
// decrease durability for non-stackable throw weapon
m_caster->ToPlayer()->DurabilityPointLossForEquipSlot(EQUIPMENT_SLOT_RANGED);
}
else
{
// decrease items amount for stackable throw weapon
uint32 count = 1;
m_caster->ToPlayer()->DestroyItemCount(pItem, count, true);
}
}
}
}
SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
{
if (m_spellInfo->PowerType != POWER_RUNES || !runeCostID)
return SPELL_CAST_OK;
Player* player = m_caster->ToPlayer();
if (!player)
return SPELL_CAST_OK;
if (player->getClass() != CLASS_DEATH_KNIGHT)
return SPELL_CAST_OK;
SpellRuneCostEntry const* src = sSpellRuneCostStore.LookupEntry(runeCostID);
if (!src)
return SPELL_CAST_OK;
if (src->NoRuneCost())
return SPELL_CAST_OK;
int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
for (uint32 i = 0; i < RUNE_DEATH; ++i)
{
runeCost[i] = src->RuneCost[i];
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
}
runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
RuneType rune = player->GetCurrentRune(i);
if ((player->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
runeCost[rune]--;
}
for (uint32 i = 0; i < RUNE_DEATH; ++i)
if (runeCost[i] > 0)
runeCost[RUNE_DEATH] += runeCost[i];
if (runeCost[RUNE_DEATH] > MAX_RUNES)
return SPELL_FAILED_NO_POWER; // not sure if result code is correct
return SPELL_CAST_OK;
}
void Spell::TakeRunePower(bool didHit)
{
if (m_caster->GetTypeId() != TYPEID_PLAYER || m_caster->getClass() != CLASS_DEATH_KNIGHT)
return;
SpellRuneCostEntry const* runeCostData = sSpellRuneCostStore.LookupEntry(m_spellInfo->RuneCostID);
if (!runeCostData || (runeCostData->NoRuneCost() && runeCostData->NoRunicPowerGain()))
return;
Player* player = m_caster->ToPlayer();
m_runesState = player->GetRunesState(); // store previous state
int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
for (uint32 i = 0; i < RUNE_DEATH; ++i)
{
runeCost[i] = runeCostData->RuneCost[i];
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
}
runeCost[RUNE_DEATH] = 0; // calculated later
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
RuneType rune = player->GetCurrentRune(i);
if (!player->GetRuneCooldown(i) && runeCost[rune] > 0)
{
player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown(i) : uint32(RUNE_MISS_COOLDOWN));
player->SetLastUsedRune(rune);
runeCost[rune]--;
}
}
runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
if (runeCost[RUNE_DEATH] > 0)
{
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
RuneType rune = player->GetCurrentRune(i);
if (!player->GetRuneCooldown(i) && rune == RUNE_DEATH)
{
player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown(i) : uint32(RUNE_MISS_COOLDOWN));
player->SetLastUsedRune(rune);
runeCost[rune]--;
// keep Death Rune type if missed
if (didHit)
player->RestoreBaseRune(i);
if (runeCost[RUNE_DEATH] == 0)
break;
}
}
}
// you can gain some runic power when use runes
if (didHit)
if (int32 rp = int32(runeCostData->runePowerGain * sWorld->getRate(RATE_POWER_RUNICPOWER_INCOME)))
player->ModifyPower(POWER_RUNIC_POWER, int32(rp));
}
void Spell::TakeReagents()
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
ItemTemplate const* castItemTemplate = m_CastItem ? m_CastItem->GetTemplate() : NULL;
// do not take reagents for these item casts
if (castItemTemplate && castItemTemplate->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST)
return;
Player* p_caster = m_caster->ToPlayer();
if (p_caster->CanNoReagentCast(m_spellInfo))
return;
for (uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x)
{
if (m_spellInfo->Reagent[x] <= 0)
continue;
uint32 itemid = m_spellInfo->Reagent[x];
uint32 itemcount = m_spellInfo->ReagentCount[x];
// if CastItem is also spell reagent
if (castItemTemplate && castItemTemplate->ItemId == itemid)
{
for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
{
// CastItem will be used up and does not count as reagent
int32 charges = m_CastItem->GetSpellCharges(s);
if (castItemTemplate->Spells[s].SpellCharges < 0 && abs(charges) < 2)
{
++itemcount;
break;
}
}
m_CastItem = NULL;
}
// if GetItemTarget is also spell reagent
if (m_targets.GetItemTargetEntry() == itemid)
m_targets.SetItemTarget(NULL);
p_caster->DestroyItemCount(itemid, itemcount, true);
}
}
void Spell::HandleThreatSpells()
{
if (m_UniqueTargetInfo.empty())
return;
if ((m_spellInfo->AttributesEx & SPELL_ATTR1_NO_THREAT) ||
(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO))
return;
float threat = 0.0f;
if (SpellThreatEntry const* threatEntry = sSpellMgr->GetSpellThreatEntry(m_spellInfo->Id))
{
if (threatEntry->apPctMod != 0.0f)
threat += threatEntry->apPctMod * m_caster->GetTotalAttackPowerValue(BASE_ATTACK);
threat += threatEntry->flatMod;
}
else if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_NO_INITIAL_THREAT) == 0)
threat += m_spellInfo->SpellLevel;
// past this point only multiplicative effects occur
if (threat == 0.0f)
return;
// since 2.0.1 threat from positive effects also is distributed among all targets, so the overall caused threat is at most the defined bonus
threat /= m_UniqueTargetInfo.size();
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition != SPELL_MISS_NONE)
continue;
Unit* target = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
if (!target)
continue;
// positive spells distribute threat among all units that are in combat with target, like healing
if (m_spellInfo->_IsPositiveSpell())
target->getHostileRefManager().threatAssist(m_caster, threat, m_spellInfo);
// for negative spells threat gets distributed among affected targets
else
{
if (!target->CanHaveThreatList())
continue;
target->AddThreat(m_caster, threat, m_spellInfo->GetSchoolMask(), m_spellInfo);
}
}
TC_LOG_DEBUG("spells", "Spell %u, added an additional %f threat for %s %u target(s)", m_spellInfo->Id, threat, m_spellInfo->_IsPositiveSpell() ? "assisting" : "harming", uint32(m_UniqueTargetInfo.size()));
}
void Spell::HandleChiPower(Player* caster)
{
if (!caster)
return;
bool hit = true;
Player* modOwner = caster->GetSpellModOwner();
m_powerCost = caster->GetPower(POWER_CHI); // AllPower - Need some DBC info for spells.
if (!m_powerCost || !modOwner)
return;
if (uint64 targetGUID = m_targets.GetUnitTargetGUID())
{
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->targetGUID == targetGUID)
{
if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS)
hit = false;
break;
}
}
// The spell did hit the target, apply aura cost mods if there are any.
if (hit)
{
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, m_powerCost);
m_caster->ModifyPower(POWER_CHI, -m_powerCost);
}
}
}
void Spell::HandleHolyPower(Player* caster)
{
if (!caster)
return;
bool hit = true;
Player* modOwner = caster->GetSpellModOwner();
m_powerCost = caster->GetPower(POWER_HOLY_POWER); // Always use all the holy power we have
if (!m_powerCost || !modOwner)
return;
if (uint64 targetGUID = m_targets.GetUnitTargetGUID())
{
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->targetGUID == targetGUID)
{
if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS)
hit = false;
break;
}
}
// The spell did hit the target, apply aura cost mods if there are any.
if (hit)
{
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, m_powerCost);
m_caster->ModifyPower(POWER_HOLY_POWER, -m_powerCost);
}
}
}
void Spell::HandleEffects(Unit* pUnitTarget, Item* pItemTarget, GameObject* pGOTarget, uint32 i, SpellEffectHandleMode mode)
{
effectHandleMode = mode;
unitTarget = pUnitTarget;
itemTarget = pItemTarget;
gameObjTarget = pGOTarget;
destTarget = &m_destTargets[i]._position;
uint8 eff = m_spellInfo->Effects[i].Effect;
TC_LOG_DEBUG("spells", "Spell: %u Effect : %u", m_spellInfo->Id, eff);
damage = CalculateDamage(i, unitTarget);
bool preventDefault = CallScriptEffectHandlers((SpellEffIndex)i, mode);
if (!preventDefault && eff < TOTAL_SPELL_EFFECTS)
{
(this->*SpellEffects[eff])((SpellEffIndex)i);
}
}
SpellCastResult Spell::CheckCast(bool strict)
{
// check death state
if (!m_caster->IsAlive() && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !((m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD) || (IsTriggered() && !m_triggeredByAuraSpell)))
return SPELL_FAILED_CASTER_DEAD;
// check cooldowns to prevent cheating
if (m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE))
{
//can cast triggered (by aura only?) spells while have this flag
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE) && m_caster->ToPlayer()->HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_ALLOW_ONLY_ABILITY))
return SPELL_FAILED_SPELL_IN_PROGRESS;
if (m_caster->ToPlayer()->HasSpellCooldown(m_spellInfo->Id))
{
if (m_triggeredByAuraSpell)
return SPELL_FAILED_DONT_REPORT;
else
return SPELL_FAILED_NOT_READY;
}
}
if (m_spellInfo->AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL && !m_caster->HasFlag(UNIT_FIELD_FLAGS2, UNIT_FLAG2_ALLOW_CHEAT_SPELLS))
{
m_customError = SPELL_CUSTOM_ERROR_GM_ONLY;
return SPELL_FAILED_CUSTOM_ERROR;
}
// Check global cooldown
if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_GCD) && HasGlobalCooldown())
return SPELL_FAILED_NOT_READY;
// only triggered spells can be processed an ended battleground
if (!IsTriggered() && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground* bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() == STATUS_WAIT_LEAVE)
return SPELL_FAILED_DONT_REPORT;
if (m_caster->GetTypeId() == TYPEID_PLAYER && VMAP::VMapFactory::createOrGetVMapManager()->isLineOfSightCalcEnabled())
{
if (m_spellInfo->Attributes & SPELL_ATTR0_OUTDOORS_ONLY &&
!m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()))
return SPELL_FAILED_ONLY_OUTDOORS;
if (m_spellInfo->Attributes & SPELL_ATTR0_INDOORS_ONLY &&
m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()))
return SPELL_FAILED_ONLY_INDOORS;
}
// only check at first call, Stealth auras are already removed at second call
// for now, ignore triggered spells
if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_SHAPESHIFT))
{
bool checkForm = true;
// Ignore form req aura
Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
for (Unit::AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
{
if (!(*i)->IsAffectingSpell(m_spellInfo))
continue;
checkForm = false;
break;
}
if (checkForm)
{
// Cannot be used in this stance/form
SpellCastResult shapeError = m_spellInfo->CheckShapeshift(m_caster->GetShapeshiftForm());
if (shapeError != SPELL_CAST_OK)
return shapeError;
if ((m_spellInfo->Attributes & SPELL_ATTR0_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
return SPELL_FAILED_ONLY_STEALTHED;
}
}
Unit::AuraEffectList const& blockSpells = m_caster->GetAuraEffectsByType(SPELL_AURA_BLOCK_SPELL_FAMILY);
for (Unit::AuraEffectList::const_iterator blockItr = blockSpells.begin(); blockItr != blockSpells.end(); ++blockItr)
if (uint32((*blockItr)->GetMiscValue()) == m_spellInfo->SpellFamilyName)
return SPELL_FAILED_SPELL_UNAVAILABLE;
bool reqCombat = true;
Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
{
if ((*j)->IsAffectingSpell(m_spellInfo))
{
m_needComboPoints = false;
if ((*j)->GetMiscValue() == 1)
{
reqCombat=false;
break;
}
}
}
// caster state requirements
// not for triggered spells (needed by execute)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE))
{
if (m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraState), m_spellInfo, m_caster))
return SPELL_FAILED_CASTER_AURASTATE;
if (m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraStateNot), m_spellInfo, m_caster))
return SPELL_FAILED_CASTER_AURASTATE;
// Note: spell 62473 requres casterAuraSpell = triggering spell
if (m_spellInfo->CasterAuraSpell && !m_caster->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->CasterAuraSpell, m_caster)))
return SPELL_FAILED_CASTER_AURASTATE;
if (m_spellInfo->ExcludeCasterAuraSpell && m_caster->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->ExcludeCasterAuraSpell, m_caster)))
return SPELL_FAILED_CASTER_AURASTATE;
if (reqCombat && m_caster->IsInCombat() && !m_spellInfo->CanBeUsedInCombat())
return SPELL_FAILED_AFFECTING_COMBAT;
}
// cancel autorepeat spells if cast start when moving
// (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
// Do not cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving() && !m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo))
{
// skip stuck spell to allow use it in falling case and apply spell limitations at movement
if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR) || m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK) &&
(IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0))
return SPELL_FAILED_MOVING;
}
// Check vehicle flags
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE))
{
SpellCastResult vehicleCheck = m_spellInfo->CheckVehicle(m_caster);
if (vehicleCheck != SPELL_CAST_OK)
return vehicleCheck;
}
// check spell cast conditions from database
{
ConditionSourceInfo condInfo = ConditionSourceInfo(m_caster);
condInfo.mConditionTargets[1] = m_targets.GetObjectTarget();
ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL, m_spellInfo->Id);
if (!conditions.empty() && !sConditionMgr->IsObjectMeetToConditions(condInfo, conditions))
{
// mLastFailedCondition can be NULL if there was an error processing the condition in Condition::Meets (i.e. wrong data for ConditionTarget or others)
if (condInfo.mLastFailedCondition && condInfo.mLastFailedCondition->ErrorType)
{
if (condInfo.mLastFailedCondition->ErrorType == SPELL_FAILED_CUSTOM_ERROR)
m_customError = SpellCustomErrors(condInfo.mLastFailedCondition->ErrorTextId);
return SpellCastResult(condInfo.mLastFailedCondition->ErrorType);
}
if (!condInfo.mLastFailedCondition || !condInfo.mLastFailedCondition->ConditionTarget)
return SPELL_FAILED_CASTER_AURASTATE;
return SPELL_FAILED_BAD_TARGETS;
}
}
// Don't check explicit target for passive spells (workaround) (check should be skipped only for learn case)
// those spells may have incorrect target entries or not filled at all (for example 15332)
// such spells when learned are not targeting anyone using targeting system, they should apply directly to caster instead
// also, such casts shouldn't be sent to client
if (!((m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster)))
{
// Check explicit target for m_originalCaster - todo: get rid of such workarounds
SpellCastResult castResult = m_spellInfo->CheckExplicitTarget(m_originalCaster ? m_originalCaster : m_caster, m_targets.GetObjectTarget(), m_targets.GetItemTarget());
if (castResult != SPELL_CAST_OK)
return castResult;
}
if (Unit* target = m_targets.GetUnitTarget())
{
SpellCastResult castResult = m_spellInfo->CheckTarget(m_caster, target, false);
if (castResult != SPELL_CAST_OK)
return castResult;
if (target != m_caster)
{
// Must be behind the target
if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET) && target->HasInArc(static_cast<float>(M_PI), m_caster))
return SPELL_FAILED_NOT_BEHIND;
// Target must be facing you
if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_REQ_TARGET_FACING_CASTER) && !target->HasInArc(static_cast<float>(M_PI), m_caster))
return SPELL_FAILED_NOT_INFRONT;
if (m_caster->GetEntry() != WORLD_TRIGGER) // Ignore LOS for gameobjects casts (wrongly casted by a trigger)
if (!(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !m_caster->IsWithinLOSInMap(target))
return SPELL_FAILED_LINE_OF_SIGHT;
}
}
// Check for line of sight for spells with dest
if (m_targets.HasDst())
{
float x, y, z;
m_targets.GetDstPos()->GetPosition(x, y, z);
if (!(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !m_caster->IsWithinLOS(x, y, z))
return SPELL_FAILED_LINE_OF_SIGHT;
}
// check pet presence
for (int j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (m_spellInfo->Effects[j].TargetA.GetTarget() == TARGET_UNIT_PET)
{
if (!m_caster->GetGuardianPet())
{
if (m_triggeredByAuraSpell) // not report pet not existence for triggered spells
return SPELL_FAILED_DONT_REPORT;
else
return SPELL_FAILED_NO_PET;
}
break;
}
}
// Spell casted only on battleground
if ((m_spellInfo->AttributesEx3 & SPELL_ATTR3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER)
if (!m_caster->ToPlayer()->InBattleground())
return SPELL_FAILED_ONLY_BATTLEGROUNDS;
// do not allow spells to be cast in arenas or rated battlegrounds
if (Player* player = m_caster->ToPlayer())
if (player->InArena()/* || player->InRatedBattleGround() NYI*/)
{
SpellCastResult castResult = CheckArenaAndRatedBattlegroundCastRules();
if (castResult != SPELL_CAST_OK)
return castResult;
}
// zone check
if (m_caster->GetTypeId() == TYPEID_UNIT || !m_caster->ToPlayer()->IsGameMaster())
{
uint32 zone, area;
m_caster->GetZoneAndAreaId(zone, area);
SpellCastResult locRes= m_spellInfo->CheckLocation(m_caster->GetMapId(), zone, area,
m_caster->GetTypeId() == TYPEID_PLAYER ? m_caster->ToPlayer() : NULL);
if (locRes != SPELL_CAST_OK)
return locRes;
}
// not let players cast spells at mount (and let do it to creatures)
if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE) &&
!m_spellInfo->IsPassive() && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_MOUNTED))
{
if (m_caster->IsInFlight())
return SPELL_FAILED_NOT_ON_TAXI;
else
return SPELL_FAILED_NOT_MOUNTED;
}
// check spell focus object
if (m_spellInfo->RequiresSpellFocus)
{
focusObject = SearchSpellFocus();
if (!focusObject)
return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
}
SpellCastResult castResult = SPELL_CAST_OK;
// always (except passive spells) check items (only player related checks)
if (!m_spellInfo->IsPassive())
{
castResult = CheckItems();
if (castResult != SPELL_CAST_OK)
return castResult;
}
// Triggered spells also have range check
/// @todo determine if there is some flag to enable/disable the check
castResult = CheckRange(strict);
if (castResult != SPELL_CAST_OK)
return castResult;
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST))
{
castResult = CheckPower();
if (castResult != SPELL_CAST_OK)
return castResult;
}
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURAS))
{
castResult = CheckCasterAuras();
if (castResult != SPELL_CAST_OK)
return castResult;
}
// script hook
castResult = CallScriptCheckCastHandlers();
if (castResult != SPELL_CAST_OK)
return castResult;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// for effects of spells that have only one target
switch (m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_DUMMY:
{
if (m_spellInfo->Id == 19938) // Awaken Peon
{
Unit* unit = m_targets.GetUnitTarget();
if (!unit || !unit->HasAura(17743))
return SPELL_FAILED_BAD_TARGETS;
}
else if (m_spellInfo->Id == 31789) // Righteous Defense
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_DONT_REPORT;
Unit* target = m_targets.GetUnitTarget();
if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty())
return SPELL_FAILED_BAD_TARGETS;
}
break;
}
case SPELL_EFFECT_LEARN_SPELL:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_PET)
break;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell);
if (!learn_spellproto)
return SPELL_FAILED_NOT_KNOWN;
if (m_spellInfo->SpellLevel > pet->getLevel())
return SPELL_FAILED_LOWLEVEL;
break;
}
case SPELL_EFFECT_UNLOCK_GUILD_VAULT_TAB:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (Guild* guild = m_caster->ToPlayer()->GetGuild())
if (guild->GetLeaderGUID() != m_caster->ToPlayer()->GetGUID())
return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
break;
}
case SPELL_EFFECT_LEARN_PET_SPELL:
{
// check target only for unit target case
if (Unit* unitTarget = m_targets.GetUnitTarget())
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Pet* pet = unitTarget->ToPet();
if (!pet || pet->GetOwner() != m_caster)
return SPELL_FAILED_BAD_TARGETS;
SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell);
if (!learn_spellproto)
return SPELL_FAILED_NOT_KNOWN;
if (m_spellInfo->SpellLevel > pet->getLevel())
return SPELL_FAILED_LOWLEVEL;
}
break;
}
case SPELL_EFFECT_APPLY_GLYPH:
{
uint32 glyphId = m_spellInfo->Effects[i].MiscValue;
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyphId))
if (m_caster->HasAura(gp->SpellId))
return SPELL_FAILED_UNIQUE_GLYPH;
break;
}
case SPELL_EFFECT_FEED_PET:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Item* foodItem = m_targets.GetItemTarget();
if (!foodItem)
return SPELL_FAILED_BAD_TARGETS;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
if (!pet->HaveInDiet(foodItem->GetTemplate()))
return SPELL_FAILED_WRONG_PET_FOOD;
if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->ItemLevel))
return SPELL_FAILED_FOOD_LOWLEVEL;
if (m_caster->IsInCombat() || pet->IsInCombat())
return SPELL_FAILED_AFFECTING_COMBAT;
break;
}
case SPELL_EFFECT_POWER_BURN:
case SPELL_EFFECT_POWER_DRAIN:
{
// Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (Unit* target = m_targets.GetUnitTarget())
if (target != m_caster && target->getPowerType() != Powers(m_spellInfo->Effects[i].MiscValue))
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_CHARGE:
{
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR)
{
// Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process
if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953))
m_caster->RemoveMovementImpairingAuras();
}
if (m_caster->HasUnitState(UNIT_STATE_ROOT))
return SPELL_FAILED_ROOTED;
if (GetSpellInfo()->NeedsExplicitUnitTarget())
{
Unit* target = m_targets.GetUnitTarget();
if (!target)
return SPELL_FAILED_DONT_REPORT;
Position pos;
target->GetContactPoint(m_caster, pos.m_positionX, pos.m_positionY, pos.m_positionZ);
target->GetFirstCollisionPosition(pos, CONTACT_DISTANCE, target->GetRelativeAngle(m_caster));
m_preGeneratedPath.SetPathLengthLimit(m_spellInfo->GetMaxRange(true) * 1.5f);
bool result = m_preGeneratedPath.CalculatePath(pos.m_positionX, pos.m_positionY, pos.m_positionZ + target->GetObjectSize());
if (m_preGeneratedPath.GetPathType() & PATHFIND_SHORT)
return SPELL_FAILED_OUT_OF_RANGE;
else if (!result || m_preGeneratedPath.GetPathType() & PATHFIND_NOPATH)
return SPELL_FAILED_NOPATH;
}
break;
}
case SPELL_EFFECT_SKINNING:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() != TYPEID_UNIT)
return SPELL_FAILED_BAD_TARGETS;
if (!(m_targets.GetUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE))
return SPELL_FAILED_TARGET_UNSKINNABLE;
Creature* creature = m_targets.GetUnitTarget()->ToCreature();
if (creature->GetCreatureType() != CREATURE_TYPE_CRITTER && !creature->loot.isLooted())
return SPELL_FAILED_TARGET_NOT_LOOTED;
uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill();
int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill);
int32 TargetLevel = m_targets.GetUnitTarget()->getLevel();
int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5);
if (ReqValue > skillValue)
return SPELL_FAILED_LOW_CASTLEVEL;
// chance for fail at orange skinning attempt
if ((m_selfContainer && (*m_selfContainer) == this) &&
skillValue < sWorld->GetConfigMaxSkillValue() &&
(ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37))
return SPELL_FAILED_TRY_AGAIN;
break;
}
case SPELL_EFFECT_OPEN_LOCK:
{
if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_TARGET &&
m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_ITEM_TARGET)
break;
if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
// we need a go target in case of TARGET_GAMEOBJECT_TARGET
|| (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget()))
return SPELL_FAILED_BAD_TARGETS;
Item* pTempItem = NULL;
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData())
pTempItem = pTrade->GetTraderData()->GetItem(TradeSlots(m_targets.GetItemTargetGUID()));
}
else if (m_targets.GetTargetMask() & TARGET_FLAG_ITEM)
pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.GetItemTargetGUID());
// we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM_TARGET
if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET &&
!m_targets.GetGOTarget() &&
(!pTempItem || !pTempItem->GetTemplate()->LockID || !pTempItem->IsLocked()))
return SPELL_FAILED_BAD_TARGETS;
if (m_spellInfo->Id != 1842 || (m_targets.GetGOTarget() &&
m_targets.GetGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP))
if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners
!m_caster->ToPlayer()->CanUseBattlegroundObject(m_targets.GetGOTarget()))
return SPELL_FAILED_TRY_AGAIN;
// get the lock entry
uint32 lockId = 0;
if (GameObject* go = m_targets.GetGOTarget())
{
lockId = go->GetGOInfo()->GetLockId();
if (!lockId)
return SPELL_FAILED_BAD_TARGETS;
}
else if (Item* itm = m_targets.GetItemTarget())
lockId = itm->GetTemplate()->LockID;
SkillType skillId = SKILL_NONE;
int32 reqSkillValue = 0;
int32 skillValue = 0;
// check lock compatibility
SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue);
if (res != SPELL_CAST_OK)
return res;
// chance for fail at orange mining/herb/LockPicking gathering attempt
// second check prevent fail at rechecks
if (skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
{
bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
// chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
if ((canFailAtMax || skillValue < sWorld->GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37))
return SPELL_FAILED_TRY_AGAIN;
}
break;
}
case SPELL_EFFECT_RESURRECT_PET:
{
Creature* pet = m_caster->GetGuardianPet();
if (pet && pet->IsAlive())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
break;
}
// This is generic summon effect
case SPELL_EFFECT_SUMMON:
{
SummonPropertiesEntry const* SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[i].MiscValueB);
if (!SummonProperties)
break;
switch (SummonProperties->Category)
{
case SUMMON_CATEGORY_PET:
if (m_caster->GetPetGUID())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
case SUMMON_CATEGORY_PUPPET:
if (m_caster->GetCharmGUID())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
break;
}
break;
}
case SPELL_EFFECT_CREATE_TAMED_PET:
{
if (m_targets.GetUnitTarget())
{
if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (m_targets.GetUnitTarget()->GetPetGUID())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
}
break;
}
case SPELL_EFFECT_SUMMON_PET:
{
if (m_caster->GetPetGUID()) //let warlock do a replacement summon
{
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK)
{
if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
if (Pet* pet = m_caster->ToPlayer()->GetPet())
pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
}
else
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
}
if (m_caster->GetCharmGUID())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
break;
}
case SPELL_EFFECT_SUMMON_PLAYER:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (!m_caster->GetTarget())
return SPELL_FAILED_BAD_TARGETS;
Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetTarget());
if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell
return SPELL_FAILED_BAD_TARGETS;
// check if our map is dungeon
MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId());
if (map->IsDungeon())
{
uint32 mapId = m_caster->GetMap()->GetId();
Difficulty difficulty = m_caster->GetMap()->GetDifficulty();
if (map->IsRaid())
if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty))
if (InstancePlayerBind* casterBind = m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty))
if (targetBind->perm && targetBind->save != casterBind->save)
return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE;
InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapId);
if (!instance)
return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId))
return SPELL_FAILED_BAD_TARGETS;
}
break;
}
// RETURN HERE
case SPELL_EFFECT_SUMMON_RAF_FRIEND:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Player* playerCaster = m_caster->ToPlayer();
//
if (!(playerCaster->GetTarget()))
return SPELL_FAILED_BAD_TARGETS;
Player* target = playerCaster->GetSelectedPlayer();
if (!target ||
!(target->GetSession()->GetRecruiterId() == playerCaster->GetSession()->GetAccountId() || target->GetSession()->GetAccountId() == playerCaster->GetSession()->GetRecruiterId()))
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_LEAP:
case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
{
//Do not allow to cast it before BG starts.
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() != STATUS_IN_PROGRESS)
return SPELL_FAILED_TRY_AGAIN;
break;
}
case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
{
if (m_targets.GetUnitTarget() == m_caster)
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_LEAP_BACK:
{
if (m_caster->HasUnitState(UNIT_STATE_ROOT))
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_ROOTED;
else
return SPELL_FAILED_DONT_REPORT;
}
break;
}
case SPELL_EFFECT_TALENT_SPEC_SELECT:
// can't change during already started arena/battleground
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() == STATUS_IN_PROGRESS)
return SPELL_FAILED_NOT_IN_BATTLEGROUND;
break;
default:
break;
}
}
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch (m_spellInfo->Effects[i].ApplyAuraName)
{
case SPELL_AURA_MOD_POSSESS_PET:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_NO_PET;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
if (pet->GetCharmerGUID())
return SPELL_FAILED_CHARMED;
break;
}
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_AOE_CHARM:
{
if (m_caster->GetCharmerGUID())
return SPELL_FAILED_CHARMED;
if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_CHARM
|| m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_POSSESS)
{
if (m_caster->GetPetGUID())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
if (m_caster->GetCharmGUID())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
}
if (Unit* target = m_targets.GetUnitTarget())
{
if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
if (target->IsMounted())
return SPELL_FAILED_CANT_BE_CHARMED;
if (target->GetCharmerGUID())
return SPELL_FAILED_CHARMED;
if (target->GetOwner() && target->GetOwner()->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_TARGET_IS_PLAYER_CONTROLLED;
int32 damage = CalculateDamage(i, target);
if (damage && int32(target->getLevel()) > damage)
return SPELL_FAILED_HIGHLEVEL;
}
break;
}
case SPELL_AURA_MOUNTED:
{
if (m_caster->IsInWater())
return SPELL_FAILED_ONLY_ABOVEWATER;
// Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
bool allowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena();
InstanceTemplate const* it = sObjectMgr->GetInstanceTemplate(m_caster->GetMapId());
if (it)
allowMount = it->AllowMount;
if (m_caster->GetTypeId() == TYPEID_PLAYER && !allowMount && !m_spellInfo->AreaGroupId)
return SPELL_FAILED_NO_MOUNTS_ALLOWED;
if (m_caster->IsInDisallowedMountForm())
return SPELL_FAILED_NOT_SHAPESHIFT;
break;
}
case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
{
if (!m_targets.GetUnitTarget())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
// can be casted at non-friendly unit or own pet/charm
if (m_caster->IsFriendlyTo(m_targets.GetUnitTarget()))
return SPELL_FAILED_TARGET_FRIENDLY;
break;
}
case SPELL_AURA_FLY:
case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED:
{
// not allow cast fly spells if not have req. skills (all spells is self target)
// allow always ghost flight spells
if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->IsAlive())
{
Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(m_originalCaster->GetZoneId());
if (AreaTableEntry const* area = GetAreaEntryByAreaID(m_originalCaster->GetAreaId()))
if (area->flags & AREA_FLAG_NO_FLY_ZONE || (Bf && !Bf->CanFlyIn()))
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE;
}
break;
}
case SPELL_AURA_PERIODIC_MANA_LEECH:
{
if (m_spellInfo->Effects[i].IsTargetingArea())
break;
if (!m_targets.GetUnitTarget())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem)
break;
if (m_targets.GetUnitTarget()->getPowerType() != POWER_MANA)
return SPELL_FAILED_BAD_TARGETS;
break;
}
default:
break;
}
}
// check trade slot case (last, for allow catch any another cast problems)
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (m_CastItem)
return SPELL_FAILED_ITEM_ENCHANT_TRADE_WINDOW;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_NOT_TRADING;
TradeData* my_trade = m_caster->ToPlayer()->GetTradeData();
if (!my_trade)
return SPELL_FAILED_NOT_TRADING;
TradeSlots slot = TradeSlots(m_targets.GetItemTargetGUID());
if (slot != TRADE_SLOT_NONTRADED)
return SPELL_FAILED_BAD_TARGETS;
if (!IsTriggered())
if (my_trade->GetSpell())
return SPELL_FAILED_ITEM_ALREADY_ENCHANTED;
}
// check if caster has at least 1 combo point for spells that require combo points
if (m_needComboPoints)
if (Player* plrCaster = m_caster->ToPlayer())
if (!plrCaster->GetComboPoints())
return SPELL_FAILED_NO_COMBO_POINTS;
// all ok
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckPetCast(Unit* target)
{
if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS)) //prevent spellcast interruption by another spellcast
return SPELL_FAILED_SPELL_IN_PROGRESS;
// dead owner (pets still alive when owners ressed?)
if (Unit* owner = m_caster->GetCharmerOrOwner())
if (!owner->IsAlive())
return SPELL_FAILED_CASTER_DEAD;
if (!target && m_targets.GetUnitTarget())
target = m_targets.GetUnitTarget();
if (m_spellInfo->NeedsExplicitUnitTarget())
{
if (!target)
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
m_targets.SetUnitTarget(target);
}
// cooldown
if (Creature const* creatureCaster = m_caster->ToCreature())
if (creatureCaster->HasSpellCooldown(m_spellInfo->Id))
return SPELL_FAILED_NOT_READY;
// Check if spell is affected by GCD
if (m_spellInfo->StartRecoveryCategory > 0)
if (m_caster->GetCharmInfo() && m_caster->GetCharmInfo()->GetGlobalCooldownMgr().HasGlobalCooldown(m_spellInfo))
return SPELL_FAILED_NOT_READY;
return CheckCast(true);
}
SpellCastResult Spell::CheckCasterAuras() const
{
// spells totally immuned to caster auras (wsg flag drop, give marks etc)
if (m_spellInfo->AttributesEx6 & SPELL_ATTR6_IGNORE_CASTER_AURAS)
return SPELL_CAST_OK;
uint8 school_immune = 0;
uint32 mechanic_immune = 0;
uint32 dispel_immune = 0;
// Check if the spell grants school or mechanic immunity.
// We use bitmasks so the loop is done only once and not on every aura check below.
if (m_spellInfo->AttributesEx & SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY)
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_SCHOOL_IMMUNITY)
school_immune |= uint32(m_spellInfo->Effects[i].MiscValue);
else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MECHANIC_IMMUNITY)
mechanic_immune |= 1 << uint32(m_spellInfo->Effects[i].MiscValue);
else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_DISPEL_IMMUNITY)
dispel_immune |= SpellInfo::GetDispelMask(DispelType(m_spellInfo->Effects[i].MiscValue));
}
// immune movement impairment and loss of control
if (m_spellInfo->Id == 42292 || m_spellInfo->Id == 59752 || m_spellInfo->Id == 19574)
mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
}
bool usableInStun = m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_STUNNED;
// Glyph of Pain Suppression
// Allow Pain Suppression and Guardian Spirit to be cast while stunned
// there is no other way to handle it
if ((m_spellInfo->Id == 33206 || m_spellInfo->Id == 47788) && !m_caster->HasAura(63248))
usableInStun = false;
// Check whether the cast should be prevented by any state you might have.
SpellCastResult prevented_reason = SPELL_CAST_OK;
// Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
if (unitflag & UNIT_FLAG_STUNNED)
{
// spell is usable while stunned, check if caster has only mechanic stun auras, another stun types must prevent cast spell
if (usableInStun)
{
bool foundNotStun = false;
Unit::AuraEffectList const& stunAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_STUN);
for (Unit::AuraEffectList::const_iterator i = stunAuras.begin(); i != stunAuras.end(); ++i)
{
if ((*i)->GetSpellInfo()->GetAllEffectsMechanicMask() && !((*i)->GetSpellInfo()->GetAllEffectsMechanicMask() & (1<<MECHANIC_STUN)))
{
foundNotStun = true;
break;
}
}
if (foundNotStun && m_spellInfo->Id != 22812)
prevented_reason = SPELL_FAILED_STUNNED;
}
else
prevented_reason = SPELL_FAILED_STUNNED;
}
else if (unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED))
prevented_reason = SPELL_FAILED_CONFUSED;
else if (unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED))
prevented_reason = SPELL_FAILED_FLEEING;
else if (unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
prevented_reason = SPELL_FAILED_SILENCED;
else if (unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
prevented_reason = SPELL_FAILED_PACIFIED;
// Attr must make flag drop spell totally immune from all effects
if (prevented_reason != SPELL_CAST_OK)
{
if (school_immune || mechanic_immune || dispel_immune)
{
//Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
Unit::AuraApplicationMap const& auras = m_caster->GetAppliedAuras();
for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
Aura const* aura = itr->second->GetBase();
SpellInfo const* auraInfo = aura->GetSpellInfo();
if (auraInfo->GetAllEffectsMechanicMask() & mechanic_immune)
continue;
if (auraInfo->GetSchoolMask() & school_immune && !(auraInfo->AttributesEx & SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE))
continue;
if (auraInfo->GetDispelMask() & dispel_immune)
continue;
//Make a second check for spell failed so the right SPELL_FAILED message is returned.
//That is needed when your casting is prevented by multiple states and you are only immune to some of them.
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (AuraEffect* part = aura->GetEffect(i))
{
switch (part->GetAuraType())
{
case SPELL_AURA_MOD_STUN:
if (!usableInStun || !(auraInfo->GetAllEffectsMechanicMask() & (1<<MECHANIC_STUN)))
return SPELL_FAILED_STUNNED;
break;
case SPELL_AURA_MOD_CONFUSE:
if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED))
return SPELL_FAILED_CONFUSED;
break;
case SPELL_AURA_MOD_FEAR:
if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED))
return SPELL_FAILED_FLEEING;
break;
case SPELL_AURA_MOD_SILENCE:
case SPELL_AURA_MOD_PACIFY:
case SPELL_AURA_MOD_PACIFY_SILENCE:
if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
return SPELL_FAILED_PACIFIED;
else if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
return SPELL_FAILED_SILENCED;
break;
default: break;
}
}
}
}
}
// You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
else
return prevented_reason;
}
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckArenaAndRatedBattlegroundCastRules()
{
bool isRatedBattleground = false; // NYI
bool isArena = !isRatedBattleground;
// check USABLE attributes
// USABLE takes precedence over NOT_USABLE
if (isRatedBattleground && m_spellInfo->AttributesEx9 & SPELL_ATTR9_USABLE_IN_RATED_BATTLEGROUNDS)
return SPELL_CAST_OK;
if (isArena && m_spellInfo->AttributesEx4 & SPELL_ATTR4_USABLE_IN_ARENA)
return SPELL_CAST_OK;
// check NOT_USABLE attributes
if (m_spellInfo->AttributesEx4 & SPELL_ATTR4_NOT_USABLE_IN_ARENA_OR_RATED_BG)
return isArena ? SPELL_FAILED_NOT_IN_ARENA : SPELL_FAILED_NOT_IN_RATED_BATTLEGROUND;
if (isArena && m_spellInfo->AttributesEx9 & SPELL_ATTR9_NOT_USABLE_IN_ARENA)
return SPELL_FAILED_NOT_IN_ARENA;
// check cooldowns
uint32 spellCooldown = m_spellInfo->GetRecoveryTime();
if (isArena && spellCooldown > 10 * MINUTE * IN_MILLISECONDS) // not sure if still needed
return SPELL_FAILED_NOT_IN_ARENA;
if (isRatedBattleground && spellCooldown > 15 * MINUTE * IN_MILLISECONDS)
return SPELL_FAILED_NOT_IN_RATED_BATTLEGROUND;
return SPELL_CAST_OK;
}
bool Spell::CanAutoCast(Unit* target)
{
uint64 targetguid = target->GetGUID();
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (m_spellInfo->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA)
{
if (m_spellInfo->StackAmount <= 1)
{
if (target->HasAuraEffect(m_spellInfo->Id, j))
return false;
}
else
{
if (AuraEffect* aureff = target->GetAuraEffect(m_spellInfo->Id, j))
if (aureff->GetBase()->GetStackAmount() >= m_spellInfo->StackAmount)
return false;
}
}
else if (m_spellInfo->Effects[j].IsAreaAuraEffect())
{
if (target->HasAuraEffect(m_spellInfo->Id, j))
return false;
}
}
SpellCastResult result = CheckPetCast(target);
if (result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
{
SelectSpellTargets();
//check if among target units, our WANTED target is as well (->only self cast spells return false)
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if (ihit->targetGUID == targetguid)
return true;
}
return false; //target invalid
}
SpellCastResult Spell::CheckRange(bool strict)
{
// Don't check for instant cast spells
if (!strict && m_casttime == 0)
return SPELL_CAST_OK;
uint32 range_type = 0;
if (m_spellInfo->RangeEntry)
{
// check needed by 68766 51693 - both spells are cast on enemies and have 0 max range
// these are triggered by other spells - possibly we should omit range check in that case?
if (m_spellInfo->RangeEntry->ID == 1)
return SPELL_CAST_OK;
range_type = m_spellInfo->RangeEntry->type;
}
Unit* target = m_targets.GetUnitTarget();
float max_range = m_caster->GetSpellMaxRangeForTarget(target, m_spellInfo);
float min_range = m_caster->GetSpellMinRangeForTarget(target, m_spellInfo);
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
if (target && target != m_caster)
{
if (range_type == SPELL_RANGE_MELEE)
{
// Because of lag, we can not check too strictly here.
if (!m_caster->IsWithinMeleeRange(target, max_range))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT;
}
else if (!m_caster->IsWithinCombatRange(target, max_range))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; //0x5A;
if (range_type == SPELL_RANGE_RANGED)
{
if (m_caster->IsWithinMeleeRange(target))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT;
}
else if (min_range && m_caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT;
if (m_caster->GetTypeId() == TYPEID_PLAYER &&
(m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc(static_cast<float>(M_PI), target))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_UNIT_NOT_INFRONT : SPELL_FAILED_DONT_REPORT;
}
if (m_targets.HasDst() && !m_targets.HasTraj())
{
if (!m_caster->IsWithinDist3d(m_targets.GetDstPos(), max_range))
return SPELL_FAILED_OUT_OF_RANGE;
if (min_range && m_caster->IsWithinDist3d(m_targets.GetDstPos(), min_range))
return SPELL_FAILED_TOO_CLOSE;
}
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckPower()
{
// item cast not used power
if (m_CastItem)
return SPELL_CAST_OK;
// health as power used - need check health amount
if (m_spellInfo->PowerType == POWER_HEALTH)
{
if (int32(m_caster->GetHealth()) <= m_powerCost)
return SPELL_FAILED_CASTER_AURASTATE;
return SPELL_CAST_OK;
}
// Check valid power type
if (m_spellInfo->PowerType >= MAX_POWERS)
{
TC_LOG_ERROR("spells", "Spell::CheckPower: Unknown power type '%d'", m_spellInfo->PowerType);
return SPELL_FAILED_UNKNOWN;
}
//check rune cost only if a spell has PowerType == POWER_RUNES
if (m_spellInfo->PowerType == POWER_RUNES)
{
SpellCastResult failReason = CheckRuneCost(m_spellInfo->RuneCostID);
if (failReason != SPELL_CAST_OK)
return failReason;
}
// Check power amount
Powers powerType = Powers(m_spellInfo->PowerType);
if (int32(m_caster->GetPower(powerType)) < m_powerCost)
return SPELL_FAILED_NO_POWER;
else
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckItems()
{
Player* player = m_caster->ToPlayer();
if (!player)
return SPELL_CAST_OK;
if (!m_CastItem)
{
if (m_castItemGUID)
return SPELL_FAILED_ITEM_NOT_READY;
}
else
{
uint32 itemid = m_CastItem->GetEntry();
if (!player->HasItemCount(itemid))
return SPELL_FAILED_ITEM_NOT_READY;
ItemTemplate const* proto = m_CastItem->GetTemplate();
if (!proto)
return SPELL_FAILED_ITEM_NOT_READY;
for (uint8 i = 0; i < MAX_ITEM_SPELLS; ++i)
if (proto->Spells[i].SpellCharges)
if (m_CastItem->GetSpellCharges(i) == 0)
return SPELL_FAILED_NO_CHARGES_REMAIN;
// consumable cast item checks
if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.GetUnitTarget())
{
// such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
SpellCastResult failReason = SPELL_CAST_OK;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.GetUnitTarget() is not the real target but the caster
if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_PET)
continue;
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_HEAL)
{
if (m_targets.GetUnitTarget()->IsFullHealth())
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
continue;
}
else
{
failReason = SPELL_CAST_OK;
break;
}
}
// Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_ENERGIZE)
{
if (m_spellInfo->Effects[i].MiscValue < 0 || m_spellInfo->Effects[i].MiscValue >= int8(MAX_POWERS))
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
continue;
}
Powers power = Powers(m_spellInfo->Effects[i].MiscValue);
if (m_targets.GetUnitTarget()->GetPower(power) == m_targets.GetUnitTarget()->GetMaxPower(power))
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
continue;
}
else
{
failReason = SPELL_CAST_OK;
break;
}
}
}
if (failReason != SPELL_CAST_OK)
return failReason;
}
}
// check target item
if (m_targets.GetItemTargetGUID())
{
if (!m_targets.GetItemTarget())
return SPELL_FAILED_ITEM_GONE;
if (!m_targets.GetItemTarget()->IsFitToSpellRequirements(m_spellInfo))
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// if not item target then required item must be equipped
else
{
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT))
if (!player->HasItemFitToSpellRequirements(m_spellInfo))
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// do not take reagents for these item casts
if (!(m_CastItem && m_CastItem->GetTemplate()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST))
{
bool checkReagents = !(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST) && !player->CanNoReagentCast(m_spellInfo);
// Not own traded item (in trader trade slot) requires reagents even if triggered spell
if (!checkReagents)
if (Item* targetItem = m_targets.GetItemTarget())
if (targetItem->GetOwnerGUID() != m_caster->GetGUID())
checkReagents = true;
// check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
if (checkReagents)
{
for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++)
{
if (m_spellInfo->Reagent[i] <= 0)
continue;
uint32 itemid = m_spellInfo->Reagent[i];
uint32 itemcount = m_spellInfo->ReagentCount[i];
// if CastItem is also spell reagent
if (m_CastItem && m_CastItem->GetEntry() == itemid)
{
ItemTemplate const* proto = m_CastItem->GetTemplate();
if (!proto)
return SPELL_FAILED_ITEM_NOT_READY;
for (uint8 s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
{
// CastItem will be used up and does not count as reagent
int32 charges = m_CastItem->GetSpellCharges(s);
if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
{
++itemcount;
break;
}
}
}
if (!player->HasItemCount(itemid, itemcount))
return SPELL_FAILED_REAGENTS;
}
}
// check totem-item requirements (items presence in inventory)
uint32 totems = 2;
for (uint8 i = 0; i < 2; ++i)
{
if (m_spellInfo->Totem[i] != 0)
{
if (player->HasItemCount(m_spellInfo->Totem[i]))
{
totems -= 1;
continue;
}
}
else
totems -= 1;
}
if (totems != 0)
return SPELL_FAILED_TOTEMS;
}
// special checks for spell effects
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch (m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_CREATE_ITEM:
case SPELL_EFFECT_CREATE_ITEM_2:
{
if (!IsTriggered() && m_spellInfo->Effects[i].ItemType)
{
ItemPosCountVec dest;
InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1);
if (msg != EQUIP_ERR_OK)
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(m_spellInfo->Effects[i].ItemType);
/// @todo Needs review
if (pProto && !(pProto->ItemLimitCategory))
{
player->SendEquipError(msg, NULL, NULL, m_spellInfo->Effects[i].ItemType);
return SPELL_FAILED_DONT_REPORT;
}
else
{
if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000)))
return SPELL_FAILED_TOO_MANY_OF_ITEM;
else if (!(player->HasItemCount(m_spellInfo->Effects[i].ItemType)))
return SPELL_FAILED_TOO_MANY_OF_ITEM;
else
player->CastSpell(m_caster, m_spellInfo->Effects[EFFECT_1].CalcValue(), false); // move this to anywhere
return SPELL_FAILED_DONT_REPORT;
}
}
}
break;
}
case SPELL_EFFECT_ENCHANT_ITEM:
if (m_spellInfo->Effects[i].ItemType && m_targets.GetItemTarget()
&& (m_targets.GetItemTarget()->IsVellum()))
{
// cannot enchant vellum for other player
if (m_targets.GetItemTarget()->GetOwner() != m_caster)
return SPELL_FAILED_NOT_TRADEABLE;
// do not allow to enchant vellum from scroll made by vellum-prevent exploit
if (m_CastItem && m_CastItem->GetTemplate()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST)
return SPELL_FAILED_TOTEM_CATEGORY;
ItemPosCountVec dest;
InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1);
if (msg != EQUIP_ERR_OK)
{
player->SendEquipError(msg, NULL, NULL, m_spellInfo->Effects[i].ItemType);
return SPELL_FAILED_DONT_REPORT;
}
}
// no break
case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
{
Item* targetItem = m_targets.GetItemTarget();
if (!targetItem)
return SPELL_FAILED_ITEM_NOT_FOUND;
if (targetItem->GetTemplate()->ItemLevel < m_spellInfo->BaseLevel)
return SPELL_FAILED_LOWLEVEL;
bool isItemUsable = false;
for (uint8 e = 0; e < MAX_ITEM_PROTO_SPELLS; ++e)
{
ItemTemplate const* proto = targetItem->GetTemplate();
if (proto->Spells[e].SpellId && (
proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE))
{
isItemUsable = true;
break;
}
}
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(m_spellInfo->Effects[i].MiscValue);
// do not allow adding usable enchantments to items that have use effect already
if (pEnchant && isItemUsable)
for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
if (pEnchant->type[s] == ITEM_ENCHANTMENT_TYPE_USE_SPELL)
return SPELL_FAILED_ON_USE_ENCHANT;
// Not allow enchant in trade slot for some enchant type
if (targetItem->GetOwner() != m_caster)
{
if (!pEnchant)
return SPELL_FAILED_ERROR;
if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
return SPELL_FAILED_NOT_TRADEABLE;
}
break;
}
case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
{
Item* item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_ITEM_NOT_FOUND;
// Not allow enchant in trade slot for some enchant type
if (item->GetOwner() != m_caster)
{
uint32 enchant_id = m_spellInfo->Effects[i].MiscValue;
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return SPELL_FAILED_ERROR;
if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
return SPELL_FAILED_NOT_TRADEABLE;
}
break;
}
case SPELL_EFFECT_ENCHANT_HELD_ITEM:
// check item existence in effect code (not output errors at offhand hold item effect to main hand for example
break;
case SPELL_EFFECT_DISENCHANT:
{
if (!m_targets.GetItemTarget())
return SPELL_FAILED_CANT_BE_DISENCHANTED;
// prevent disenchanting in trade slot
if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_DISENCHANTED;
ItemTemplate const* itemProto = m_targets.GetItemTarget()->GetTemplate();
if (!itemProto)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
uint32 item_quality = itemProto->Quality;
// 2.0.x addon: Check player enchanting level against the item disenchanting requirements
uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
if (item_disenchantskilllevel == uint32(-1))
return SPELL_FAILED_CANT_BE_DISENCHANTED;
if (item_disenchantskilllevel > player->GetSkillValue(SKILL_ENCHANTING))
return SPELL_FAILED_LOW_CASTLEVEL;
if (item_quality > 4 || item_quality < 2)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
if (itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
if (!itemProto->DisenchantID)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
break;
}
case SPELL_EFFECT_PROSPECTING:
{
if (!m_targets.GetItemTarget())
return SPELL_FAILED_CANT_BE_PROSPECTED;
//ensure item is a prospectable ore
if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_PROTO_FLAG_PROSPECTABLE))
return SPELL_FAILED_CANT_BE_PROSPECTED;
//prevent prospecting in trade slot
if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_PROSPECTED;
//Check for enough skill in jewelcrafting
uint32 item_prospectingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank;
if (item_prospectingskilllevel >player->GetSkillValue(SKILL_JEWELCRAFTING))
return SPELL_FAILED_LOW_CASTLEVEL;
//make sure the player has the required ores in inventory
if (m_targets.GetItemTarget()->GetCount() < 5)
return SPELL_FAILED_NEED_MORE_ITEMS;
if (!LootTemplates_Prospecting.HaveLootFor(m_targets.GetItemTargetEntry()))
return SPELL_FAILED_CANT_BE_PROSPECTED;
break;
}
case SPELL_EFFECT_MILLING:
{
if (!m_targets.GetItemTarget())
return SPELL_FAILED_CANT_BE_MILLED;
//ensure item is a millable herb
if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_PROTO_FLAG_MILLABLE))
return SPELL_FAILED_CANT_BE_MILLED;
//prevent milling in trade slot
if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_MILLED;
//Check for enough skill in inscription
uint32 item_millingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank;
if (item_millingskilllevel > player->GetSkillValue(SKILL_INSCRIPTION))
return SPELL_FAILED_LOW_CASTLEVEL;
//make sure the player has the required herbs in inventory
if (m_targets.GetItemTarget()->GetCount() < 5)
return SPELL_FAILED_NEED_MORE_ITEMS;
if (!LootTemplates_Milling.HaveLootFor(m_targets.GetItemTargetEntry()))
return SPELL_FAILED_CANT_BE_MILLED;
break;
}
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
{
if (m_attackType != RANGED_ATTACK)
break;
Item* pItem = player->GetWeaponForAttack(m_attackType);
if (!pItem || pItem->IsBroken())
return SPELL_FAILED_EQUIPPED_ITEM;
switch (pItem->GetTemplate()->SubClass)
{
case ITEM_SUBCLASS_WEAPON_THROWN:
{
uint32 ammo = pItem->GetEntry();
if (!player->HasItemCount(ammo))
return SPELL_FAILED_NO_AMMO;
break;
}
case ITEM_SUBCLASS_WEAPON_GUN:
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
case ITEM_SUBCLASS_WEAPON_WAND:
break;
default:
break;
}
break;
}
case SPELL_EFFECT_CREATE_MANA_GEM:
{
uint32 item_id = m_spellInfo->Effects[i].ItemType;
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id);
if (!pProto)
return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
if (Item* pitem = player->GetItemByEntry(item_id))
{
for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x)
if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges)
return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
}
break;
}
default:
break;
}
}
// check weapon presence in slots for main/offhand weapons
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT) && m_spellInfo->EquippedItemClass >=0)
{
// main hand weapon required
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_MAIN_HAND)
{
Item* item = m_caster->ToPlayer()->GetWeaponForAttack(BASE_ATTACK);
// skip spell if no weapon in slot or broken
if (!item || item->IsBroken())
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
// skip spell if weapon not fit to triggered spell
if (!item->IsFitToSpellRequirements(m_spellInfo))
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// offhand hand weapon required
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND)
{
Item* item = m_caster->ToPlayer()->GetWeaponForAttack(OFF_ATTACK);
// skip spell if no weapon in slot or broken
if (!item || item->IsBroken())
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
// skip spell if weapon not fit to triggered spell
if (!item->IsFitToSpellRequirements(m_spellInfo))
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
}
return SPELL_CAST_OK;
}
void Spell::Delayed() // only called in DealDamage()
{
if (!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER)
return;
//if (m_spellState == SPELL_STATE_DELAYED)
// return; // spell is active and can't be time-backed
if (isDelayableNoMore()) // Spells may only be delayed twice
return;
// spells not loosing casting time (slam, dynamites, bombs..)
//if (!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
// return;
//check pushback reduce
int32 delaytime = 500; // spellcasting delay is normally 500ms
int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
if (delayReduce >= 100)
return;
AddPct(delaytime, -delayReduce);
if (m_timer + delaytime > m_casttime)
{
delaytime = m_casttime - m_timer;
m_timer = m_casttime;
}
else
m_timer += delaytime;
TC_LOG_INFO("spells", "Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime);
WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
data.append(m_caster->GetPackGUID());
data << uint32(delaytime);
m_caster->SendMessageToSet(&data, true);
}
void Spell::DelayedChannel()
{
if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
return;
if (isDelayableNoMore()) // Spells may only be delayed twice
return;
//check pushback reduce
int32 delaytime = CalculatePct(m_spellInfo->GetDuration(), 25); // channeling delay is normally 25% of its time per hit
int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
if (delayReduce >= 100)
return;
AddPct(delaytime, -delayReduce);
if (m_timer <= delaytime)
{
delaytime = m_timer;
m_timer = 0;
}
else
m_timer -= delaytime;
TC_LOG_DEBUG("spells", "Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if ((*ihit).missCondition == SPELL_MISS_NONE)
if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime);
// partially interrupt persistent area auras
if (DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id))
dynObj->Delay(delaytime);
SendChannelUpdate(m_timer);
}
void Spell::UpdatePointers()
{
if (m_originalCasterGUID == m_caster->GetGUID())
m_originalCaster = m_caster;
else
{
m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
if (m_originalCaster && !m_originalCaster->IsInWorld())
m_originalCaster = NULL;
}
if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER)
m_CastItem = m_caster->ToPlayer()->GetItemByGuid(m_castItemGUID);
m_targets.Update(m_caster);
// further actions done only for dest targets
if (!m_targets.HasDst())
return;
// cache last transport
WorldObject* transport = NULL;
// update effect destinations (in case of moved transport dest target)
for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
{
SpellDestination& dest = m_destTargets[effIndex];
if (!dest._transportGUID)
continue;
if (!transport || transport->GetGUID() != dest._transportGUID)
transport = ObjectAccessor::GetWorldObject(*m_caster, dest._transportGUID);
if (transport)
{
dest._position.Relocate(transport);
dest._position.RelocateOffset(dest._transportOffset);
}
}
}
CurrentSpellTypes Spell::GetCurrentContainer() const
{
if (IsNextMeleeSwingSpell())
return(CURRENT_MELEE_SPELL);
else if (IsAutoRepeat())
return(CURRENT_AUTOREPEAT_SPELL);
else if (m_spellInfo->IsChanneled())
return(CURRENT_CHANNELED_SPELL);
else
return(CURRENT_GENERIC_SPELL);
}
bool Spell::CheckEffectTarget(Unit const* target, uint32 eff) const
{
switch (m_spellInfo->Effects[eff].ApplyAuraName)
{
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_MOD_POSSESS_PET:
case SPELL_AURA_AOE_CHARM:
if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle())
return false;
if (target->IsMounted())
return false;
if (target->GetCharmerGUID())
return false;
if (int32 damage = CalculateDamage(eff, target))
if ((int32)target->getLevel() > damage)
return false;
break;
default:
break;
}
if (IsTriggered() || m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS))
return true;
/// @todo shit below shouldn't be here, but it's temporary
//Check targets for LOS visibility (except spells without range limitations)
switch (m_spellInfo->Effects[eff].Effect)
{
case SPELL_EFFECT_RESURRECT_NEW:
// player far away, maybe his corpse near?
if (target != m_caster && !target->IsWithinLOSInMap(m_caster))
{
if (!m_targets.GetCorpseTargetGUID())
return false;
Corpse* corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.GetCorpseTargetGUID());
if (!corpse)
return false;
if (target->GetGUID() != corpse->GetOwnerGUID())
return false;
if (!corpse->IsWithinLOSInMap(m_caster))
return false;
}
// all ok by some way or another, skip normal check
break;
default: // normal case
// Get GO cast coordinates if original caster -> GO
WorldObject* caster = NULL;
if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
if (!caster)
caster = m_caster;
if (target != m_caster && !target->IsWithinLOSInMap(caster))
return false;
break;
}
return true;
}
bool Spell::IsNextMeleeSwingSpell() const
{
return m_spellInfo->Attributes & SPELL_ATTR0_ON_NEXT_SWING;
}
bool Spell::IsAutoActionResetSpell() const
{
/// @todo changed SPELL_INTERRUPT_FLAG_AUTOATTACK -> SPELL_INTERRUPT_FLAG_INTERRUPT to fix compile - is this check correct at all?
return !IsTriggered() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT);
}
bool Spell::IsNeedSendToClient() const
{
return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || m_spellInfo->IsChanneled() ||
(m_spellInfo->AttributesEx8 & SPELL_ATTR8_AURA_SEND_AMOUNT) || m_spellInfo->Speed > 0.0f || (!m_triggeredByAuraSpell && !IsTriggered());
}
bool Spell::HaveTargetsForEffect(uint8 effect) const
{
for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
for (std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
return false;
}
SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
{
m_Spell = spell;
}
SpellEvent::~SpellEvent()
{
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->cancel();
if (m_Spell->IsDeletable())
{
delete m_Spell;
}
else
{
TC_LOG_ERROR("spells", "~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
(m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id);
ASSERT(false);
}
}
bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
{
// update spell if it is not finished
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->update(p_time);
// check spell state to process
switch (m_Spell->getState())
{
case SPELL_STATE_FINISHED:
{
// spell was finished, check deletable state
if (m_Spell->IsDeletable())
{
// check, if we do have unfinished triggered spells
return true; // spell is deletable, finish event
}
// event will be re-added automatically at the end of routine)
} break;
case SPELL_STATE_DELAYED:
{
// first, check, if we have just started
if (m_Spell->GetDelayStart() != 0)
{
// no, we aren't, do the typical update
// check, if we have channeled spell on our hands
/*
if (m_Spell->m_spellInfo->IsChanneled())
{
// evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
// check, if we have casting anything else except this channeled spell and autorepeat
if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
{
// another non-melee non-delayed spell is casted now, abort
m_Spell->cancel();
}
else
{
// Set last not triggered spell for apply spellmods
((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true);
// do the action (pass spell to channeling state)
m_Spell->handle_immediate();
// And remove after effect handling
((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false);
}
// event will be re-added automatically at the end of routine)
}
else
*/
{
// run the spell handler and think about what we can do next
uint64 t_offset = e_time - m_Spell->GetDelayStart();
uint64 n_offset = m_Spell->handle_delayed(t_offset);
if (n_offset)
{
// re-add us to the queue
m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
return false; // event not complete
}
// event complete
// finish update event will be re-added automatically at the end of routine)
}
}
else
{
// delaying had just started, record the moment
m_Spell->SetDelayStart(e_time);
// re-plan the event for the delay moment
m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
return false; // event not complete
}
} break;
default:
{
// all other states
// event will be re-added automatically at the end of routine)
} break;
}
// spell processing not complete, plan event on the next update interval
m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
return false; // event not complete
}
void SpellEvent::Abort(uint64 /*e_time*/)
{
// oops, the spell we try to do is aborted
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->cancel();
}
bool SpellEvent::IsDeletable() const
{
return m_Spell->IsDeletable();
}
bool Spell::IsValidDeadOrAliveTarget(Unit const* target) const
{
if (target->IsAlive())
return !m_spellInfo->IsRequiringDeadTarget();
if (m_spellInfo->IsAllowingDeadTarget())
return true;
return false;
}
void Spell::HandleLaunchPhase()
{
// handle effects with SPELL_EFFECT_HANDLE_LAUNCH mode
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// don't do anything for empty effect
if (!m_spellInfo->Effects[i].IsEffect())
continue;
HandleEffects(NULL, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH);
}
float multiplier[MAX_SPELL_EFFECTS];
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_applyMultiplierMask & (1 << i))
multiplier[i] = m_spellInfo->Effects[i].CalcDamageMultiplier(m_originalCaster, this);
bool usesAmmo = m_spellInfo->AttributesCu & SPELL_ATTR0_CU_DIRECT_DAMAGE;
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
TargetInfo& target = *ihit;
uint32 mask = target.effectMask;
if (!mask)
continue;
// do not consume ammo anymore for Hunter's volley spell
if (IsTriggered() && m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->IsTargetingArea())
usesAmmo = false;
if (usesAmmo)
{
bool ammoTaken = false;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
if (!(mask & 1<<i))
continue;
switch (m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_SCHOOL_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
ammoTaken=true;
TakeAmmo();
}
if (ammoTaken)
break;
}
}
DoAllEffectOnLaunchTarget(target, multiplier);
}
}
void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier)
{
Unit* unit = NULL;
// In case spell hit target, do all effect on that target
if (targetInfo.missCondition == SPELL_MISS_NONE)
unit = m_caster->GetGUID() == targetInfo.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, targetInfo.targetGUID);
// In case spell reflect from target, do all effect on caster (if hit)
else if (targetInfo.missCondition == SPELL_MISS_REFLECT && targetInfo.reflectResult == SPELL_MISS_NONE)
unit = m_caster;
if (!unit)
return;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (targetInfo.effectMask & (1<<i))
{
m_damage = 0;
m_healing = 0;
HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH_TARGET);
if (m_damage > 0)
{
if (m_spellInfo->Effects[i].IsTargetingArea())
{
m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask));
if (m_caster->GetTypeId() == TYPEID_UNIT)
m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask));
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
uint32 targetAmount = m_UniqueTargetInfo.size();
if (targetAmount > 10)
m_damage = m_damage * 10/targetAmount;
}
}
}
if (m_applyMultiplierMask & (1 << i))
{
m_damage = int32(m_damage * m_damageMultipliers[i]);
m_damageMultipliers[i] *= multiplier[i];
}
targetInfo.damage += m_damage;
}
}
targetInfo.crit = m_caster->isSpellCrit(unit, m_spellInfo, m_spellSchoolMask, m_attackType);
}
SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
{
if (!lockId) // possible case for GO and maybe for items.
return SPELL_CAST_OK;
// Get LockInfo
LockEntry const* lockInfo = sLockStore.LookupEntry(lockId);
if (!lockInfo)
return SPELL_FAILED_BAD_TARGETS;
bool reqKey = false; // some locks not have reqs
for (int j = 0; j < MAX_LOCK_CASE; ++j)
{
switch (lockInfo->Type[j])
{
// check key item (many fit cases can be)
case LOCK_KEY_ITEM:
if (lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry() == lockInfo->Index[j])
return SPELL_CAST_OK;
reqKey = true;
break;
// check key skill (only single first fit case can be)
case LOCK_KEY_SKILL:
{
reqKey = true;
// wrong locktype, skip
if (uint32(m_spellInfo->Effects[effIndex].MiscValue) != lockInfo->Index[j])
continue;
skillId = SkillByLockType(LockType(lockInfo->Index[j]));
if (skillId != SKILL_NONE)
{
reqSkillValue = lockInfo->Skill[j];
// castitem check: rogue using skeleton keys. the skill values should not be added in this case.
skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
0 : m_caster->ToPlayer()->GetSkillValue(skillId);
// skill bonus provided by casting spell (mostly item spells)
// add the effect base points modifier from the spell casted (cheat lock / skeleton key etc.)
if (m_spellInfo->Effects[effIndex].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET || m_spellInfo->Effects[effIndex].TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET)
skillValue += m_spellInfo->Effects[effIndex].CalcValue();
if (skillValue < reqSkillValue)
return SPELL_FAILED_LOW_CASTLEVEL;
}
return SPELL_CAST_OK;
}
}
}
if (reqKey)
return SPELL_FAILED_BAD_TARGETS;
return SPELL_CAST_OK;
}
void Spell::SetSpellValue(SpellValueMod mod, int32 value)
{
switch (mod)
{
case SPELLVALUE_BASE_POINT0:
m_spellValue->EffectBasePoints[0] = m_spellInfo->Effects[EFFECT_0].CalcBaseValue(value);
break;
case SPELLVALUE_BASE_POINT1:
m_spellValue->EffectBasePoints[1] = m_spellInfo->Effects[EFFECT_1].CalcBaseValue(value);
break;
case SPELLVALUE_BASE_POINT2:
m_spellValue->EffectBasePoints[2] = m_spellInfo->Effects[EFFECT_2].CalcBaseValue(value);
break;
case SPELLVALUE_RADIUS_MOD:
m_spellValue->RadiusMod = (float)value / 10000;
break;
case SPELLVALUE_MAX_TARGETS:
m_spellValue->MaxAffectedTargets = (uint32)value;
break;
case SPELLVALUE_AURA_STACK:
m_spellValue->AuraStackAmount = uint8(value);
break;
}
}
void Spell::PrepareTargetProcessing()
{
CheckEffectExecuteData();
}
void Spell::FinishTargetProcessing()
{
SendLogExecute();
}
void Spell::InitEffectExecuteData(uint8 effIndex)
{
ASSERT(effIndex < MAX_SPELL_EFFECTS);
if (!m_effectExecuteData[effIndex])
{
m_effectExecuteData[effIndex] = new ByteBuffer(0x20);
// first dword - target counter
*m_effectExecuteData[effIndex] << uint32(1);
}
else
{
// increase target counter by one
uint32 count = (*m_effectExecuteData[effIndex]).read<uint32>(0);
(*m_effectExecuteData[effIndex]).put<uint32>(0, ++count);
}
}
void Spell::CheckEffectExecuteData()
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
ASSERT(!m_effectExecuteData[i]);
}
void Spell::LoadScripts()
{
sScriptMgr->CreateSpellScripts(m_spellInfo->Id, m_loadedScripts);
for (std::list<SpellScript*>::iterator itr = m_loadedScripts.begin(); itr != m_loadedScripts.end();)
{
if (!(*itr)->_Load(this))
{
std::list<SpellScript*>::iterator bitr = itr;
++itr;
delete (*bitr);
m_loadedScripts.erase(bitr);
continue;
}
TC_LOG_DEBUG("spells", "Spell::LoadScripts: Script `%s` for spell `%u` is loaded now", (*itr)->_GetScriptName()->c_str(), m_spellInfo->Id);
(*itr)->Register();
++itr;
}
}
void Spell::CallScriptBeforeCastHandlers()
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_CAST);
std::list<SpellScript::CastHandler>::iterator hookItrEnd = (*scritr)->BeforeCast.end(), hookItr = (*scritr)->BeforeCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnCastHandlers()
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_CAST);
std::list<SpellScript::CastHandler>::iterator hookItrEnd = (*scritr)->OnCast.end(), hookItr = (*scritr)->OnCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptAfterCastHandlers()
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_CAST);
std::list<SpellScript::CastHandler>::iterator hookItrEnd = (*scritr)->AfterCast.end(), hookItr = (*scritr)->AfterCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
SpellCastResult Spell::CallScriptCheckCastHandlers()
{
SpellCastResult retVal = SPELL_CAST_OK;
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CHECK_CAST);
std::list<SpellScript::CheckCastHandler>::iterator hookItrEnd = (*scritr)->OnCheckCast.end(), hookItr = (*scritr)->OnCheckCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
{
SpellCastResult tempResult = (*hookItr).Call(*scritr);
if (retVal == SPELL_CAST_OK)
retVal = tempResult;
}
(*scritr)->_FinishScriptCall();
}
return retVal;
}
void Spell::PrepareScriptHitHandlers()
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
(*scritr)->_InitHit();
}
bool Spell::CallScriptEffectHandlers(SpellEffIndex effIndex, SpellEffectHandleMode mode)
{
// execute script effect handler hooks and check if effects was prevented
bool preventDefault = false;
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
std::list<SpellScript::EffectHandler>::iterator effItr, effEndItr;
SpellScriptHookType hookType;
switch (mode)
{
case SPELL_EFFECT_HANDLE_LAUNCH:
effItr = (*scritr)->OnEffectLaunch.begin();
effEndItr = (*scritr)->OnEffectLaunch.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH;
break;
case SPELL_EFFECT_HANDLE_LAUNCH_TARGET:
effItr = (*scritr)->OnEffectLaunchTarget.begin();
effEndItr = (*scritr)->OnEffectLaunchTarget.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH_TARGET;
break;
case SPELL_EFFECT_HANDLE_HIT:
effItr = (*scritr)->OnEffectHit.begin();
effEndItr = (*scritr)->OnEffectHit.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT;
break;
case SPELL_EFFECT_HANDLE_HIT_TARGET:
effItr = (*scritr)->OnEffectHitTarget.begin();
effEndItr = (*scritr)->OnEffectHitTarget.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT_TARGET;
break;
default:
ASSERT(false);
return false;
}
(*scritr)->_PrepareScriptCall(hookType);
for (; effItr != effEndItr; ++effItr)
// effect execution can be prevented
if (!(*scritr)->_IsEffectPrevented(effIndex) && (*effItr).IsEffectAffected(m_spellInfo, effIndex))
(*effItr).Call(*scritr, effIndex);
if (!preventDefault)
preventDefault = (*scritr)->_IsDefaultEffectPrevented(effIndex);
(*scritr)->_FinishScriptCall();
}
return preventDefault;
}
void Spell::CallScriptBeforeHitHandlers()
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_HIT);
std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->BeforeHit.end(), hookItr = (*scritr)->BeforeHit.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnHitHandlers()
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_HIT);
std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->OnHit.end(), hookItr = (*scritr)->OnHit.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptAfterHitHandlers()
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_HIT);
std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->AfterHit.end(), hookItr = (*scritr)->AfterHit.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptObjectAreaTargetSelectHandlers(std::list<WorldObject*>& targets, SpellEffIndex effIndex)
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_AREA_TARGET_SELECT);
std::list<SpellScript::ObjectAreaTargetSelectHandler>::iterator hookItrEnd = (*scritr)->OnObjectAreaTargetSelect.end(), hookItr = (*scritr)->OnObjectAreaTargetSelect.begin();
for (; hookItr != hookItrEnd; ++hookItr)
if ((*hookItr).IsEffectAffected(m_spellInfo, effIndex))
(*hookItr).Call(*scritr, targets);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptObjectTargetSelectHandlers(WorldObject*& target, SpellEffIndex effIndex)
{
for (std::list<SpellScript*>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_TARGET_SELECT);
std::list<SpellScript::ObjectTargetSelectHandler>::iterator hookItrEnd = (*scritr)->OnObjectTargetSelect.end(), hookItr = (*scritr)->OnObjectTargetSelect.begin();
for (; hookItr != hookItrEnd; ++hookItr)
if ((*hookItr).IsEffectAffected(m_spellInfo, effIndex))
(*hookItr).Call(*scritr, target);
(*scritr)->_FinishScriptCall();
}
}
bool Spell::CheckScriptEffectImplicitTargets(uint32 effIndex, uint32 effIndexToCheck)
{
// Skip if there are not any script
if (!m_loadedScripts.size())
return true;
for (std::list<SpellScript*>::iterator itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr)
{
std::list<SpellScript::ObjectTargetSelectHandler>::iterator targetSelectHookEnd = (*itr)->OnObjectTargetSelect.end(), targetSelectHookItr = (*itr)->OnObjectTargetSelect.begin();
for (; targetSelectHookItr != targetSelectHookEnd; ++targetSelectHookItr)
if (((*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) ||
(!(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)))
return false;
std::list<SpellScript::ObjectAreaTargetSelectHandler>::iterator areaTargetSelectHookEnd = (*itr)->OnObjectAreaTargetSelect.end(), areaTargetSelectHookItr = (*itr)->OnObjectAreaTargetSelect.begin();
for (; areaTargetSelectHookItr != areaTargetSelectHookEnd; ++areaTargetSelectHookItr)
if (((*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) ||
(!(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)))
return false;
}
return true;
}
bool Spell::CanExecuteTriggersOnHit(uint32 effMask, SpellInfo const* triggeredByAura) const
{
bool only_on_caster = (triggeredByAura && (triggeredByAura->AttributesEx4 & SPELL_ATTR4_PROC_ONLY_ON_CASTER));
// If triggeredByAura has SPELL_ATTR4_PROC_ONLY_ON_CASTER then it can only proc on a casted spell with TARGET_UNIT_CASTER
for (uint8 i = 0;i < MAX_SPELL_EFFECTS; ++i)
{
if ((effMask & (1 << i)) && (!only_on_caster || (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_CASTER)))
return true;
}
return false;
}
void Spell::PrepareTriggersExecutedOnHit()
{
/// @todo move this to scripts
if (m_spellInfo->SpellFamilyName)
{
SpellInfo const* excludeCasterSpellInfo = sSpellMgr->GetSpellInfo(m_spellInfo->ExcludeCasterAuraSpell);
if (excludeCasterSpellInfo && !excludeCasterSpellInfo->IsPositive())
m_preCastSpell = m_spellInfo->ExcludeCasterAuraSpell;
SpellInfo const* excludeTargetSpellInfo = sSpellMgr->GetSpellInfo(m_spellInfo->ExcludeTargetAuraSpell);
if (excludeTargetSpellInfo && !excludeTargetSpellInfo->IsPositive())
m_preCastSpell = m_spellInfo->ExcludeTargetAuraSpell;
}
/// @todo move this to scripts
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
{
// Permafrost
if (m_spellInfo->SpellFamilyFlags[1] & 0x00001000 || m_spellInfo->SpellFamilyFlags[0] & 0x00100220)
m_preCastSpell = 68391;
break;
}
}
// handle SPELL_AURA_ADD_TARGET_TRIGGER auras:
// save auras which were present on spell caster on cast, to prevent triggered auras from affecting caster
// and to correctly calculate proc chance when combopoints are present
Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER);
for (Unit::AuraEffectList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
{
if (!(*i)->IsAffectingSpell(m_spellInfo))
continue;
SpellInfo const* auraSpellInfo = (*i)->GetSpellInfo();
uint32 auraSpellIdx = (*i)->GetEffIndex();
if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(auraSpellInfo->Effects[auraSpellIdx].TriggerSpell))
{
// calculate the chance using spell base amount, because aura amount is not updated on combo-points change
// this possibly needs fixing
int32 auraBaseAmount = (*i)->GetBaseAmount();
// proc chance is stored in effect amount
int32 chance = m_caster->CalculateSpellDamage(NULL, auraSpellInfo, auraSpellIdx, &auraBaseAmount);
// build trigger and add to the list
HitTriggerSpell spellTriggerInfo;
spellTriggerInfo.triggeredSpell = spellInfo;
spellTriggerInfo.triggeredByAura = auraSpellInfo;
spellTriggerInfo.chance = chance * (*i)->GetBase()->GetStackAmount();
m_hitTriggerSpells.push_back(spellTriggerInfo);
}
}
}
// Global cooldowns management
enum GCDLimits
{
MIN_GCD = 1000,
MAX_GCD = 1500
};
bool Spell::HasGlobalCooldown() const
{
// Only player or controlled units have global cooldown
if (m_caster->GetCharmInfo())
return m_caster->GetCharmInfo()->GetGlobalCooldownMgr().HasGlobalCooldown(m_spellInfo);
else if (m_caster->GetTypeId() == TYPEID_PLAYER)
return m_caster->ToPlayer()->GetGlobalCooldownMgr().HasGlobalCooldown(m_spellInfo);
else
return false;
}
void Spell::TriggerGlobalCooldown()
{
int32 gcd = m_spellInfo->StartRecoveryTime;
if (!gcd)
return;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_COOLDOWN))
return;
// Global cooldown can't leave range 1..1.5 secs
// There are some spells (mostly not casted directly by player) that have < 1 sec and > 1.5 sec global cooldowns
// but as tests show are not affected by any spell mods.
if (m_spellInfo->StartRecoveryTime >= MIN_GCD && m_spellInfo->StartRecoveryTime <= MAX_GCD)
{
// gcd modifier auras are applied only to own spells and only players have such mods
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this);
// Apply haste rating
gcd = int32(float(gcd) * m_caster->GetFloatValue(UNIT_FIELD_MOD_CASTING_SPEED));
if (gcd < MIN_GCD)
gcd = MIN_GCD;
else if (gcd > MAX_GCD)
gcd = MAX_GCD;
}
// Only players or controlled units have global cooldown
if (m_caster->GetCharmInfo())
m_caster->GetCharmInfo()->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd);
else if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd);
}
void Spell::CancelGlobalCooldown()
{
if (!m_spellInfo->StartRecoveryTime)
return;
// Cancel global cooldown when interrupting current cast
if (m_caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) != this)
return;
// Only players or controlled units have global cooldown
if (m_caster->GetCharmInfo())
m_caster->GetCharmInfo()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo);
else if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo);
}
namespace Trinity
{
WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo,
SpellTargetCheckTypes selectionType, ConditionList* condList) : _caster(caster), _referer(referer), _spellInfo(spellInfo),
_targetSelectionType(selectionType), _condList(condList)
{
if (condList)
_condSrcInfo = new ConditionSourceInfo(NULL, caster);
else
_condSrcInfo = NULL;
}
WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck()
{
if (_condSrcInfo)
delete _condSrcInfo;
}
bool WorldObjectSpellTargetCheck::operator()(WorldObject* target)
{
if (_spellInfo->CheckTarget(_caster, target, true) != SPELL_CAST_OK)
return false;
Unit* unitTarget = target->ToUnit();
if (Corpse* corpseTarget = target->ToCorpse())
{
// use ofter for party/assistance checks
if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID()))
unitTarget = owner;
else
return false;
}
if (unitTarget)
{
switch (_targetSelectionType)
{
case TARGET_CHECK_ENEMY:
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAttackTarget(unitTarget, _spellInfo))
return false;
break;
case TARGET_CHECK_ALLY:
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo))
return false;
break;
case TARGET_CHECK_PARTY:
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo))
return false;
if (!_referer->IsInPartyWith(unitTarget))
return false;
break;
case TARGET_CHECK_RAID_CLASS:
if (_referer->getClass() != unitTarget->getClass())
return false;
// nobreak;
case TARGET_CHECK_RAID:
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo))
return false;
if (!_referer->IsInRaidWith(unitTarget))
return false;
break;
default:
break;
}
}
if (!_condSrcInfo)
return true;
_condSrcInfo->mConditionTargets[0] = target;
return sConditionMgr->IsObjectMeetToConditions(*_condSrcInfo, *_condList);
}
WorldObjectSpellNearbyTargetCheck::WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo,
SpellTargetCheckTypes selectionType, ConditionList* condList)
: WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(caster) { }
bool WorldObjectSpellNearbyTargetCheck::operator()(WorldObject* target)
{
float dist = target->GetDistance(*_position);
if (dist < _range && WorldObjectSpellTargetCheck::operator ()(target))
{
_range = dist;
return true;
}
return false;
}
WorldObjectSpellAreaTargetCheck::WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster,
Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList)
: WorldObjectSpellTargetCheck(caster, referer, spellInfo, selectionType, condList), _range(range), _position(position) { }
bool WorldObjectSpellAreaTargetCheck::operator()(WorldObject* target)
{
if (!target->IsWithinDist3d(_position, _range) && !(target->ToGameObject() && target->ToGameObject()->IsInRange(_position->GetPositionX(), _position->GetPositionY(), _position->GetPositionZ(), _range)))
return false;
return WorldObjectSpellTargetCheck::operator ()(target);
}
WorldObjectSpellConeTargetCheck::WorldObjectSpellConeTargetCheck(float coneAngle, float range, Unit* caster,
SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList)
: WorldObjectSpellAreaTargetCheck(range, caster, caster, caster, spellInfo, selectionType, condList), _coneAngle(coneAngle) { }
bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target)
{
if (_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_BACK)
{
if (!_caster->isInBack(target, _coneAngle))
return false;
}
else if (_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_LINE)
{
if (!_caster->HasInLine(target, _caster->GetObjectSize()))
return false;
}
else
{
if (!_caster->isInFront(target, _coneAngle))
return false;
}
return WorldObjectSpellAreaTargetCheck::operator ()(target);
}
WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, SpellInfo const* spellInfo)
: WorldObjectSpellAreaTargetCheck(range, position, caster, caster, spellInfo, TARGET_CHECK_DEFAULT, NULL) { }
bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target)
{
// return all targets on missile trajectory (0 - size of a missile)
if (!_caster->HasInLine(target, 0))
return false;
return WorldObjectSpellAreaTargetCheck::operator ()(target);
}
} //namespace Trinity
|
devastates/SkyFire_5xx
|
src/server/game/Spells/Spell.cpp
|
C++
|
gpl-2.0
| 315,517
|
/*********************************************************************************
Copyright MCQ TECH GmbH 2012
$Autor:$ Dipl.-Ing. Steffen Kutsche
$Id:$
$Date:$ 15.02.2012
Description: MODBUS-Configuration for mct_spi_aio-Driver
Tracen der MODBUS-Kommandos erfolgt mit:
#define/#undef CONFIG_MODBUS_CMD_TRACE
MODBUS-Adressen:TCP RTU
-----------------
0 220
Geräte-Object mct_if.01.3-2-SLOT.0
[mct] = MC Technology
[if] = Interface
[.01] = 1 Gerät
[.3-2] = MODBUS, Treiberkennung mct_spi_aio
SLOT = z.Zeit immer 0
.0 = Instanz
Input : 4xKanal 32bit float (0-1 = Spannung/Widerstand, 2-3 = Strom)
Output: 4xKanal 16bit (0-1 = Spannung, 2-3 = Strom)
Register:
*********************************************************************************/
#ifndef __MCT_MODBUS_SPI_AIO_CFG_H_
#define __MCT_MODBUS_SPI_AIO_CFG_H_
#define MODBUS_DEVICE_INTERFACE "mct_" DRIVER_INTERFACE ".01." BUS_MODBUS "-" DRIVER_SPI_AIO_IDENT "-"
//#define CONFIG_MODBUS_CMD_TRACE // AN: Schalter - tracen der Kommandos
#undef CONFIG_MODBUS_CMD_TRACE // AUS: Schalter - tracen der Kommandos
#define MODBUS_SLVS 1 // Anzahl MOD-Bus Geräte
#define MODBUS_SLV_0 0 // Index MOD-Bus Gerät 4 analoge Eingänge
// 4 analoge Ausgänge
#endif
|
mbrugg/MC-EWIO-KERNEL-ORG
|
drivers/mct/spi_aio/mct_spi_aio_modbus_cfg.h
|
C
|
gpl-2.0
| 1,277
|
package com.ezee.web.common.ui.grid.leasecategory;
import com.ezee.model.entity.lease.EzeeLeaseCategory;
import com.ezee.web.common.ui.grid.EzeeFinancialEntityGridModel;
public class EzeeLeaseCategoryGridModel extends EzeeFinancialEntityGridModel<EzeeLeaseCategory> {
}
|
simehanley/eZee
|
ezeeparent/ezeewebcommon/src/main/java/com/ezee/web/common/ui/grid/leasecategory/EzeeLeaseCategoryGridModel.java
|
Java
|
gpl-2.0
| 271
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_13) on Thu Jul 09 06:46:48 PDT 2009 -->
<TITLE>
CpuInfo (Sigar API)
</TITLE>
<META NAME="date" CONTENT="2009-07-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="CpuInfo (Sigar API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/hyperic/sigar/Cpu.html" title="class in org.hyperic.sigar"><B>PREV CLASS</B></A>
<A HREF="../../../org/hyperic/sigar/CpuPerc.html" title="class in org.hyperic.sigar"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/hyperic/sigar/CpuInfo.html" target="_top"><B>FRAMES</B></A>
<A HREF="CpuInfo.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.hyperic.sigar</FONT>
<BR>
Class CpuInfo</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.hyperic.sigar.CpuInfo</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable</DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>CpuInfo</B><DT>extends java.lang.Object<DT>implements java.io.Serializable</DL>
</PRE>
<P>
CpuInfo sigar class.
<P>
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../serialized-form.html#org.hyperic.sigar.CpuInfo">Serialized Form</A></DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#CpuInfo()">CpuInfo</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#gather(org.hyperic.sigar.Sigar)">gather</A></B>(<A HREF="../../../org/hyperic/sigar/Sigar.html" title="class in org.hyperic.sigar">Sigar</A> sigar)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> long</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#getCacheSize()">getCacheSize</A></B>()</CODE>
<BR>
Get the CPU cache size.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#getCoresPerSocket()">getCoresPerSocket</A></B>()</CODE>
<BR>
Get the Number of CPU cores per CPU socket.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#getMhz()">getMhz</A></B>()</CODE>
<BR>
Get the CPU speed.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#getModel()">getModel</A></B>()</CODE>
<BR>
Get the CPU model.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#getTotalCores()">getTotalCores</A></B>()</CODE>
<BR>
Get the Total CPU cores (logical).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#getTotalSockets()">getTotalSockets</A></B>()</CODE>
<BR>
Get the Total CPU sockets (physical).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#getVendor()">getVendor</A></B>()</CODE>
<BR>
Get the CPU vendor id.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.Map</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#toMap()">toMap</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/hyperic/sigar/CpuInfo.html#toString()">toString</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="CpuInfo()"><!-- --></A><H3>
CpuInfo</H3>
<PRE>
public <B>CpuInfo</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="gather(org.hyperic.sigar.Sigar)"><!-- --></A><H3>
gather</H3>
<PRE>
public void <B>gather</B>(<A HREF="../../../org/hyperic/sigar/Sigar.html" title="class in org.hyperic.sigar">Sigar</A> sigar)
throws <A HREF="../../../org/hyperic/sigar/SigarException.html" title="class in org.hyperic.sigar">SigarException</A></PRE>
<DL>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE><A HREF="../../../org/hyperic/sigar/SigarException.html" title="class in org.hyperic.sigar">SigarException</A></CODE></DL>
</DD>
</DL>
<HR>
<A NAME="getVendor()"><!-- --></A><H3>
getVendor</H3>
<PRE>
public java.lang.String <B>getVendor</B>()</PRE>
<DL>
<DD>Get the CPU vendor id.<p>
Supported Platforms: AIX, FreeBSD, Linux, HPUX, Solaris, Win32.
<p>
System equivalent commands:<ul>
<li> AIX: <code>lsattr -El proc0</code><br>
<li> Darwin: <code></code><br>
<li> FreeBSD: <code></code><br>
<li> HPUX: <code></code><br>
<li> Linux: <code>cat /proc/cpuinfo</code><br>
<li> Solaris: <code>psrinfo -v</code><br>
<li> Win32: <code></code><br>
</ul>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>CPU vendor id</DL>
</DD>
</DL>
<HR>
<A NAME="getModel()"><!-- --></A><H3>
getModel</H3>
<PRE>
public java.lang.String <B>getModel</B>()</PRE>
<DL>
<DD>Get the CPU model.<p>
Supported Platforms: AIX, FreeBSD, Linux, HPUX, Solaris, Win32.
<p>
System equivalent commands:<ul>
<li> AIX: <code>lsattr -El proc0</code><br>
<li> Darwin: <code></code><br>
<li> FreeBSD: <code></code><br>
<li> HPUX: <code></code><br>
<li> Linux: <code>cat /proc/cpuinfo</code><br>
<li> Solaris: <code>psrinfo -v</code><br>
<li> Win32: <code></code><br>
</ul>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>CPU model</DL>
</DD>
</DL>
<HR>
<A NAME="getMhz()"><!-- --></A><H3>
getMhz</H3>
<PRE>
public int <B>getMhz</B>()</PRE>
<DL>
<DD>Get the CPU speed.<p>
Supported Platforms: AIX, FreeBSD, HPUX, Linux, Solaris, Win32.
<p>
System equivalent commands:<ul>
<li> AIX: <code>lsattr -El proc0</code><br>
<li> Darwin: <code></code><br>
<li> FreeBSD: <code></code><br>
<li> HPUX: <code></code><br>
<li> Linux: <code>cat /proc/cpuinfo</code><br>
<li> Solaris: <code>psrinfo -v</code><br>
<li> Win32: <code></code><br>
</ul>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>CPU speed</DL>
</DD>
</DL>
<HR>
<A NAME="getCacheSize()"><!-- --></A><H3>
getCacheSize</H3>
<PRE>
public long <B>getCacheSize</B>()</PRE>
<DL>
<DD>Get the CPU cache size.<p>
Supported Platforms: AIX, Linux.
<p>
System equivalent commands:<ul>
<li> AIX: <code>lsattr -El proc0</code><br>
<li> Darwin: <code></code><br>
<li> FreeBSD: <code></code><br>
<li> HPUX: <code></code><br>
<li> Linux: <code>cat /proc/cpuinfo</code><br>
<li> Solaris: <code>psrinfo -v</code><br>
<li> Win32: <code></code><br>
</ul>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>CPU cache size</DL>
</DD>
</DL>
<HR>
<A NAME="getTotalCores()"><!-- --></A><H3>
getTotalCores</H3>
<PRE>
public int <B>getTotalCores</B>()</PRE>
<DL>
<DD>Get the Total CPU cores (logical).<p>
Supported Platforms: Undocumented.
<p>
System equivalent commands:<ul>
<li> AIX: <code>lsattr -El proc0</code><br>
<li> Darwin: <code></code><br>
<li> FreeBSD: <code></code><br>
<li> HPUX: <code></code><br>
<li> Linux: <code>cat /proc/cpuinfo</code><br>
<li> Solaris: <code>psrinfo -v</code><br>
<li> Win32: <code></code><br>
</ul>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>Total CPU cores (logical)</DL>
</DD>
</DL>
<HR>
<A NAME="getTotalSockets()"><!-- --></A><H3>
getTotalSockets</H3>
<PRE>
public int <B>getTotalSockets</B>()</PRE>
<DL>
<DD>Get the Total CPU sockets (physical).<p>
Supported Platforms: Undocumented.
<p>
System equivalent commands:<ul>
<li> AIX: <code>lsattr -El proc0</code><br>
<li> Darwin: <code></code><br>
<li> FreeBSD: <code></code><br>
<li> HPUX: <code></code><br>
<li> Linux: <code>cat /proc/cpuinfo</code><br>
<li> Solaris: <code>psrinfo -v</code><br>
<li> Win32: <code></code><br>
</ul>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>Total CPU sockets (physical)</DL>
</DD>
</DL>
<HR>
<A NAME="getCoresPerSocket()"><!-- --></A><H3>
getCoresPerSocket</H3>
<PRE>
public int <B>getCoresPerSocket</B>()</PRE>
<DL>
<DD>Get the Number of CPU cores per CPU socket.<p>
Supported Platforms: Undocumented.
<p>
System equivalent commands:<ul>
<li> AIX: <code>lsattr -El proc0</code><br>
<li> Darwin: <code></code><br>
<li> FreeBSD: <code></code><br>
<li> HPUX: <code></code><br>
<li> Linux: <code>cat /proc/cpuinfo</code><br>
<li> Solaris: <code>psrinfo -v</code><br>
<li> Win32: <code></code><br>
</ul>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>Number of CPU cores per CPU socket</DL>
</DD>
</DL>
<HR>
<A NAME="toMap()"><!-- --></A><H3>
toMap</H3>
<PRE>
public java.util.Map <B>toMap</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="toString()"><!-- --></A><H3>
toString</H3>
<PRE>
public java.lang.String <B>toString</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>toString</CODE> in class <CODE>java.lang.Object</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/hyperic/sigar/Cpu.html" title="class in org.hyperic.sigar"><B>PREV CLASS</B></A>
<A HREF="../../../org/hyperic/sigar/CpuPerc.html" title="class in org.hyperic.sigar"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/hyperic/sigar/CpuInfo.html" target="_top"><B>FRAMES</B></A>
<A HREF="CpuInfo.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright ? 2004-2009 <a target="_top" href="http://www.hyperic.com/">Hyperic</a>. All Rights Reserved.
</BODY>
</HTML>
|
gitpan/hyperic-sigar
|
docs/javadoc/org/hyperic/sigar/CpuInfo.html
|
HTML
|
gpl-2.0
| 17,848
|
package com.rugie.chat;
/**
* Created with IntelliJ IDEA.
* User: adamchlupacek
* Date: 18/10/14
* Time: 22:22
*/
public class Tuple2<T1,T2> {
private T1 first;
private T2 second;
public Tuple2(T1 first, T2 second) {
this.first = first;
this.second = second;
}
public T1 getFirst() {
return first;
}
public T2 getSecond() {
return second;
}
}
|
AdamChlupacek/RugieChat
|
src/com/rugie/chat/Tuple2.java
|
Java
|
gpl-2.0
| 385
|
/**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark 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, version 2.
*
* The OWASP Benchmark 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.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01184")
public class BenchmarkTest01184 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("vector");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
String fileName = null;
java.io.FileInputStream fis = null;
try {
fileName = org.owasp.benchmark.helpers.Utils.testfileDir + bar;
fis = new java.io.FileInputStream(new java.io.File(fileName));
byte[] b = new byte[1000];
int size = fis.read(b);
response.getWriter().write("The beginning of file: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileName) + "' is:\n\n");
response.getWriter().write(org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(b,0,size)));
} catch (Exception e) {
System.out.println("Couldn't open FileInputStream on file: '" + fileName + "'");
response.getWriter().write("Problem getting FileInputStream: " + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
fis = null;
} catch (Exception e) {
// we tried...
}
}
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns constant to bar on true condition
int num = 86;
if ( (7*42) - num > 200 )
bar = "This_should_always_happen";
else bar = param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
|
andresriancho/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01184.java
|
Java
|
gpl-2.0
| 3,186
|
package com.javarush.task.task10.task1020;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
Задача по алгоритмам
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int[] array = new int[30];
for (int i = 0; i < 30; i++) {
array[i] = Integer.parseInt(reader.readLine());
}
sort(array);
System.out.println(array[9]);
System.out.println(array[10]);
}
public static void sort(int[] array) {
for (int i = 0; i < array.length - 1; i++)
for (int j = i + 1; j < array.length; j++)
if (array[j] < array[i]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
|
biblelamp/JavaExercises
|
JavaRushTasks/1.JavaSyntax/src/com/javarush/task/task10/task1020/Solution.java
|
Java
|
gpl-2.0
| 916
|
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<table BORDER COLS=16 WIDTH="100%" >
<pre>
# fileName = xPeriment-P.lopT-10-tableau-1901/xPer-P.lopT-1901-pal-11-35-10-1903-sample.html
# created with the command table.html
# on Thu Sep 10 23:51:07 EDT 2015
# thisFile = xPeriment-P.lopT-10-tableau-1901/xPer-P.lopT-1901-pal-11-35-10-1903-sample.txt
# configuration file = xPeriment-P.lopT-10-tableau-1901.tcl
# created on Thu Sep 10 23:51:06 EDT 2015
#
</pre>
<tr><td>instanceID</td><td>instanceDim</td><td>hostID</td><td>sandboxID</td><td>solverName</td><td>valueTarget</td><td>valueBest</td><td>targetReached</td><td>isCensored</td><td>runtimeLmt</td><td>runtime</td><td>cntProbe</td><td>walkLength</td><td>cntRestart</td><td>speedProbe</td><td>coordBest</td></tr>
<tr><td>pal-11-35-1-1903</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00400</td><td>53</td><td>26</td><td>0</td><td>13171</td><td>10,11,4,9,2,3,7,1,5,8,6</td></tr>
<tr><td>pal-11-35-2-316410</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00700</td><td>99</td><td>49</td><td>0</td><td>13636</td><td>7,10,2,11,5,3,8,1,6,4,9</td></tr>
<tr><td>pal-11-35-3-871546</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00400</td><td>61</td><td>30</td><td>0</td><td>13760</td><td>11,4,9,2,3,7,8,1,5,6,10</td></tr>
<tr><td>pal-11-35-4-233105</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00500</td><td>63</td><td>31</td><td>0</td><td>13725</td><td>5,8,9,3,1,2,6,7,10,11,4</td></tr>
<tr><td>pal-11-35-5-116105</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00100</td><td>15</td><td>7</td><td>0</td><td>10156</td><td>3,7,5,8,6,11,9,1,10,4,2</td></tr>
<tr><td>pal-11-35-6-194892</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00500</td><td>75</td><td>37</td><td>0</td><td>14071</td><td>8,1,4,2,5,6,9,7,10,11,3</td></tr>
<tr><td>pal-11-35-7-662606</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00200</td><td>21</td><td>10</td><td>0</td><td>11230</td><td>5,8,9,1,6,10,2,11,3,4,7</td></tr>
<tr><td>pal-11-35-8-727650</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.0100</td><td>143</td><td>71</td><td>0</td><td>14785</td><td>6,4,9,10,2,3,7,8,11,1,5</td></tr>
<tr><td>pal-11-35-9-471542</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00200</td><td>19</td><td>9</td><td>0</td><td>10976</td><td>7,10,4,8,2,11,5,9,3,1,6</td></tr>
<tr><td>pal-11-35-10-591696</td><td>11</td><td>brglez@triangle-Darwin-14.5.0</td><td>P.lop</td><td>P.lopT</td><td>-35.0</td><td>-35</td><td>1</td><td>0</td><td>7200</td><td>0.00200</td><td>25</td><td>12</td><td>0</td><td>11704</td><td>7,1,5,8,6,10,11,4,9,2,3</td></tr>
</table>
</body>
</html>
|
fbrglez/gitBed
|
xProj/P.lop/xWork/xPeriment-P.lopT-10-tableau-1901-20150910/xPer-P.lopT-1901-pal-11-35-10-1903-sample.html
|
HTML
|
gpl-2.0
| 3,617
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcContrib.UI.Grid;
using ViniSandbox.Models;
using WebViniSandbox.Helpers;
namespace WebViniSandbox.Models
{
public class FileGridModel : GridModel<file>
{
public FileGridModel()
{
Column.For(a => "<a href=\"/File/DownloadFile/" + a.id + "\">" + a.name + "</a>").Encode(false).Named("Nome");
Column.For(a => a.source).Named("Fonte");
//Column.For(a => a.date.Value.ToString("dd/MM/yyyy hh:mm"));
//Column.For(a => a.file_detail.type);
Column.For(a => a.file_detail.md5).Named("MD5");
Column.For(a => "<a href=\"/Analysis/Index?id_file=" + a.id + "\">" + a.file_detail.analyses.Count() + "</a>").Named("Análises").Encode(false);
Column.For(a =>
TagBuilders.ImageButtonGrid("javascript:callpdetailsfile(true," + a.id + ")", "/Content/ico/details.png", "Detalhes") +
TagBuilders.ImageButtonGrid("javascript:callpfmaliciousfile(" + a.id + ", true," + ((a.file_detail.malicious.HasValue && a.file_detail.malicious.Value)?"true":"false") +
")", a.file_detail.malicious.HasValue && a.file_detail.malicious.Value ? "/Content/ico/malicious.png" : "/Content/ico/malicious_disable.png", "Malicioso") +
TagBuilders.ImageButtonGrid("javascript:callpfsendantivirusfile(" + a.id + ",false)", "/Content/ico/send.png", "Enviar Amostra") +
TagBuilders.ImageButtonGrid("javascript:callpfreanalizefile(" + a.id + ",false)", "/Content/ico/redo.png", "Reanalisar")
//enviar empresa de antivirus
//malicioso
//reanalisar
//Numero de analises
).Encode(false).Sortable(false).Named("Ações");
}
}
}
|
mviniciusleal/vinisandbox
|
WebViniSandbox/Models/GridModel/FileGridModel.cs
|
C#
|
gpl-2.0
| 1,879
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <paths.h>
#include <signal.h>
#include <stdarg.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <limits.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <syslog.h>
#include <signal.h>
#include <dirent.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/if_ether.h>
#include <net/if.h>
#include <linux/sockios.h>
#include <string.h>
#include <net/route.h>
#include <net/if.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>
#include "common.h"
#define MD5_OUT_BUFSIZE 36
static struct timeval tick_val= {0, 0};
int get_net_info(char *ifname, struct net_info *info)
{
int sk;
struct ifreq ifr;
unsigned char buffer[6];
int ret;
struct link_data {
unsigned int cmd;
unsigned int value;
}link;
sk = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (sk < 0)
return sk;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
// ¼ì²éÁ¬½Ó
link.cmd = 0x0000000A;
link.value = 0;
ifr.ifr_data = (caddr_t)&link;
if (ioctl(sk, SIOCETHTOOL, &ifr) == 0)
{
if (link.value)
{
//info->link = 1;
DBG(" %s link....\n", ifname);
}
else
{
}
}
// »ñÈ¡IP
if(ioctl(sk, SIOCGIFADDR, &ifr) == -1)
{
fprintf(stderr,"err\n");
ret = -1;
goto err;
}
memcpy(buffer, ifr.ifr_addr.sa_data, sizeof(buffer));
memcpy(info->ip, &buffer[2], 4);
// »ñÈ¡netmask
if(ioctl(sk, SIOCGIFNETMASK, &ifr) == -1)
{
fprintf(stderr,"err\n");
ret = -1;
goto err;
}
memcpy(buffer, ifr.ifr_netmask.sa_data, sizeof(buffer));
memcpy(info->mask, &buffer[2], 4);
err:
close(sk);
return ret;
}
int get_mac(char *devname, char *mac)
{
struct ifreq ifr;
unsigned char tmbuf[IFHWADDRLEN];
int ret = 0;
int s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
memset(mac,0,6);
strncpy(ifr.ifr_name, devname, IFNAMSIZ-1);
if(ioctl(s, SIOCGIFHWADDR, &ifr) == -1){
ret = -1;
}
else
{
memcpy(tmbuf, ifr.ifr_hwaddr.sa_data, sizeof(tmbuf));
memcpy(mac, &tmbuf[0], 6);
}
close(s);
return ret;
}
int get_netmask(char *devname, char *netmask)
{
struct ifreq ifr;
unsigned char tmbuf[6];
int ret = 0;
int s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
memset(netmask,0,4);
strncpy(ifr.ifr_name, devname, IFNAMSIZ-1);
if(ioctl(s, SIOCGIFNETMASK, &ifr)==-1){
ret = -1;
}
else
{
memcpy(tmbuf, ifr.ifr_netmask.sa_data, sizeof(tmbuf));
memcpy(netmask, &tmbuf[2], 4);
}
close(s);
return ret;
}
int get_ip(char *devname, char *ip)
{
struct ifreq ifr;
unsigned char tmbuf[6];
int ret = 0;
int s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
memset(ip,0,4);
strncpy(ifr.ifr_name, devname, IFNAMSIZ-1);
if(ioctl(s, SIOCGIFADDR, &ifr)==-1){
ret = -1;
}
else
{
memcpy(tmbuf, ifr.ifr_addr.sa_data, sizeof(tmbuf));
memcpy(ip, &tmbuf[2], 4);
}
close(s);
return ret;
}
int get_gateway(char *gw)
{
char msg[64];
char *via;
FILE *fpin;
int a, b, c, d;
memset(gw,0,4);
if((fpin = popen("ip route show|grep default","r")) == NULL)
return -1;
while(fgets(msg, sizeof(msg), fpin) != NULL)
{
if((via = strstr(msg,"via")) != NULL)
{
a = gw[0];
b = gw[1];
c = gw[2];
d = gw[3];
sscanf(via+4,"%d.%d.%d.%d ",&a, &b,&c,&d);
pclose(fpin);
return 0;
}
}
pclose(fpin);
return -1;
}
int getmask(char *nmask)
{
int loopmask = 0;
int ip[4] = {
0, 0, 0, 0
};
sscanf(nmask, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]);
int n = 8;
for (--n; n >= 0; --n) // test all 4 bytes in one pass
{
if (ip[0] & 1 << n)
loopmask++;
if (ip[1] & 1 << n)
loopmask++;
if (ip[2] & 1 << n)
loopmask++;
if (ip[3] & 1 << n)
loopmask++;
}
return loopmask;
}
char *get_complete_ip(char *from, char *to)
{
static char ipaddr[20];
int i[4];
if (!from || !to)
return "0.0.0.0";
if (sscanf(from, "%d.%d.%d.%d", &i[0], &i[1], &i[2], &i[3]) != 4)
return "0.0.0.0";
snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%s", i[0], i[1], i[2], to);
return ipaddr;
}
static char *get_ifname(char *name, int nsize, char *buf)
{
char *end;
// Ìø¹ý¿Õ¸ñ
while(isspace(*buf))
buf++;
end = strstr(buf, ": ");
if (end == NULL || ((end - buf) + 1) > nsize)
return NULL;
memcpy(name, buf, (end - buf));
name[end - buf] = '\0';
return end;
}
int sys_get_eth_ifname(char *ifname, int nsize)
{
FILE *fp;
char buf[256];
int ret = 0;
fp = fopen("/proc/net/dev", "r");
if (fp == NULL)
return -1;
while (fgets(buf, sizeof(buf), fp))
{
if (buf[0] == '\0' || buf[1] == '\0')
continue;
if (get_ifname(ifname, nsize, buf) != NULL)
{
if (!strncmp(ifname, "eth", 3))
{
ret = 1;
break;
}
}
}
fclose(fp);
return ret;
}
int sys_get_wlan_ifname(char *ifname, int nsize)
{
FILE *fp;
char buf[256];
int ret = 0;
fp = fopen("/proc/net/wireless", "r");
if (fp == NULL)
return -1;
while (fgets(buf, sizeof(buf), fp))
{
if (buf[0] == '\0' || buf[1] == '\0')
continue;
if (get_ifname(ifname, nsize, buf) != NULL)
{
if (!strncmp(ifname, "wlan", 4))
{
ret = 1;
break;
}
}
}
fclose(fp);
return ret;
}
int pipe_exec(char *shell)
{
FILE *fp;
char buffer[64];
int ret = -1;
fp = popen(shell, "r");
if (fp != NULL)
{
memset(buffer, 0, sizeof(buffer));
if (fread(buffer, 1, sizeof(buffer)-1, fp) > 0)
{
ret = 1;
}
else
{
ret = 0;
}
pclose(fp);
}
return ret;
}
int get_eth_link(char *name)
{
char cmd[32];
memset(cmd, 0x0, sizeof(cmd));
sprintf(cmd, "ifconfig %s | grep RUNNING", name);
return pipe_exec(cmd);
}
int LSMOD(char *module)
{
char cmd[32];
memset(cmd, 0x0, sizeof(cmd));
sprintf(cmd, "lsmod | grep %s", module);
return pipe_exec(cmd);
}
int file_to_buf(char *path, char *buf, int len)
{
FILE *fp;
memset(buf, 0, len);
if ((fp = fopen(path, "r"))) {
fclose(fp);
return 1;
}
return 0;
}
int get_ppp_pid(char *file)
{
char buf[80];
int pid = -1;
if (file_to_buf(file, buf, sizeof(buf))) {
char tmp[80], tmp1[80];
snprintf(tmp, sizeof(tmp), "/var/run/%s.pid", buf);
file_to_buf(tmp, tmp1, sizeof(tmp1));
pid = atoi(tmp1);
}
return pid;
}
char *find_name_by_proc(char *out, int pid)
{
FILE *fp;
char line[254];
char filename[80];
static char name[80];
if(!out)
return NULL;
snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
if ((fp = fopen(filename, "r"))) {
if(fgets(line, sizeof(line), fp)){
sscanf(out, "%*s %s", line);
}else{
out = NULL;
}
fclose(fp);
return out;
}
return NULL;
}
int check_wan_link(int num)
{
return 1;
}
static int system2(char *command)
{
return system(command);
}
int sysprintf(const char *fmt, ...)
{
char varbuf[256];
va_list args;
va_start(args, (char *)fmt);
vsnprintf(varbuf, sizeof(varbuf), fmt, args);
va_end(args);
return system2(varbuf);
}
int _evalpid(char *const argv[], char *path, int timeout, int *ppid)
{
pid_t pid;
int status;
int fd;
int flags;
int sig;
switch (pid = fork()) {
case -1: /* error */
perror("fork");
return errno;
case 0: /* child */
/*
* Reset signal handlers set for parent process
*/
for (sig = 0; sig < (_NSIG - 1); sig++)
signal(sig, SIG_DFL);
/* Clean up */
ioctl(0, TIOCNOTTY, 0);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
setsid();
/*
* We want to check the board if exist UART? , add by honor
* 2003-12-04
*/
if ((fd = open("/dev/console", O_RDWR)) < 0) {
(void)open("/dev/null", O_RDONLY);
(void)open("/dev/null", O_WRONLY);
(void)open("/dev/null", O_WRONLY);
} else {
close(fd);
(void)open("/dev/console", O_RDONLY);
(void)open("/dev/console", O_WRONLY);
(void)open("/dev/console", O_WRONLY);
}
/*
* Redirect stdout to <path>
*/
if (path) {
flags = O_WRONLY | O_CREAT;
if (!strncmp(path, ">>", 2)) {
/*
* append to <path>
*/
flags |= O_APPEND;
path += 2;
} else if (!strncmp(path, ">", 1)) {
/*
* overwrite <path>
*/
flags |= O_TRUNC;
path += 1;
}
if ((fd = open(path, flags, 0644)) < 0)
perror(path);
else {
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
alarm(timeout);
execvp(argv[0], argv);
perror(argv[0]);
exit(errno);
default: /* parent */
if (ppid) {
*ppid = pid;
return 0;
} else {
waitpid(pid, &status, 0);
if (WIFEXITED(status))
return WEXITSTATUS(status);
else
return status;
}
}
}
int _eval(char *const argv[],int timeout, int *ppid)
{
return _evalpid(argv, ">/dev/console", timeout, ppid);
}
int f_exists(const char *path) // note: anything but a directory
{
struct stat st;
return (stat(path, &st) == 0) && (!S_ISDIR(st.st_mode));
}
int f_read(const char *path, void *buffer, int max)
{
int f;
int n;
if ((f = open(path, O_RDONLY)) < 0)
return -1;
n = read(f, buffer, max);
close(f);
return n;
}
int f_read_string(const char *path, char *buffer, int max)
{
if (max <= 0)
return -1;
int n = f_read(path, buffer, max - 1);
buffer[(n > 0) ? n : 0] = 0;
return n;
}
char *psname(int pid, char *buffer, int maxlen)
{
char buf[512];
char path[64];
char *p;
if (maxlen <= 0)
return NULL;
*buffer = 0;
sprintf(path, "/proc/%d/stat", pid);
if ((f_read_string(path, buf, sizeof(buf)) > 4)
&& ((p = strrchr(buf, ')')) != NULL)) {
*p = 0;
if (((p = strchr(buf, '(')) != NULL) && (atoi(buf) == pid)) {
strncpy(buffer, p + 1, maxlen);
}
}
return buffer;
}
static int _pidof(const char *name, pid_t ** pids)
{
const char *p;
char *e;
DIR *dir;
struct dirent *de;
pid_t i;
int count;
char buf[256];
count = 0;
*pids = NULL;
if ((p = strchr(name, '/')) != NULL)
name = p + 1;
if ((dir = opendir("/proc")) != NULL) {
while ((de = readdir(dir)) != NULL) {
i = strtol(de->d_name, &e, 10);
if (*e != 0)
continue;
if (strcmp(name, psname(i, buf, sizeof(buf))) == 0) {
if ((*pids =
realloc(*pids,
sizeof(pid_t) * (count + 1))) ==
NULL) {
return -1;
}
(*pids)[count++] = i;
}
}
}
closedir(dir);
return count;
}
int pidof(const char *name)
{
pid_t *pids;
pid_t p;
if (_pidof(name, &pids) > 0) {
p = *pids;
free(pids);
return p;
}
return -1;
}
int killall(const char *name, int sig)
{
pid_t *pids;
int i;
int r;
if ((i = _pidof(name, &pids)) > 0) {
r = 0;
do {
r |= kill(pids[--i], sig);
}
while (i > 0);
free(pids);
return r;
}
return -2;
}
int kill_pid(int pid)
{
int deadcnt = 20;
struct stat s;
char pfile[32];
if (pid > 0)
{
kill(pid, SIGTERM);
sprintf(pfile, "/proc/%d/stat", pid);
while (deadcnt--)
{
usleep(100*1000);
if ((stat(pfile, &s) > -1) && (s.st_mode & S_IFREG))
{
kill(pid, SIGKILL);
}
else
break;
}
return 1;
}
return 0;
}
int stop_process(char *name)
{
int deadcounter = 20;
if (pidof(name) > 0) {
killall(name, SIGTERM);
while (pidof(name) > 0 && deadcounter--) {
usleep(100*1000);
}
if (pidof(name) > 0) {
killall(name, SIGKILL);
}
return 1;
}
return 0;
}
void get_sys_date(struct tm *tm)
{
time_t timep;
time(&timep);
tm = localtime(&timep);
}
int get_tick_1hz(void)
{
struct timeval tv;
int tick;
gettimeofday(&tv, NULL);
tick = (tv.tv_sec - tick_val.tv_sec)*1000 + (tv.tv_usec - tick_val.tv_usec)/1000;
return tick/1000;
}
void clktick_init(void)
{
gettimeofday(&tick_val, NULL);
}
int get_tick_1khz(void)
{
int tick;
struct timeval tv;
gettimeofday(&tv, NULL);
tick = (tv.tv_sec - tick_val.tv_sec)*1000 + (tv.tv_usec - tick_val.tv_usec)/1000;
return tick;
}
#define GPIO_SYS_PATH "/sys/class/gpio"
void gpio_export(int gpio, char *dir, int value)
{
// set gpio-pinmux
sysprintf("echo \"%d\" >%s/export", gpio, GPIO_SYS_PATH);
// set gpio-direction and gpio-level: "in" or "out", 1 or 0
if (!strcmp(dir, "in"))
{
sysprintf("echo \"in\" >%s/gpio%d/direction", GPIO_SYS_PATH, gpio);
}
else
{
sysprintf("echo \"out\" >%s/gpio%d/direction", GPIO_SYS_PATH, gpio);
sysprintf("echo \"%d\" >%s/gpio%d/value", value, GPIO_SYS_PATH, gpio);
}
}
void gpio_unexport(int gpio)
{
sysprintf("echo \"%d\" >%s/unexport", gpio, GPIO_SYS_PATH);
}
void set_gpio_high(int gpionum)
{
// sysprintf("echo \"out\" >%s/gpio%d/direction", GPIO_SYS_PATH, gpionum);
sysprintf("echo \"1\" >%s/gpio%d/value", GPIO_SYS_PATH, gpionum);
}
void set_gpio_low(int gpionum)
{
// sysprintf("echo \"out\" >%s/gpio%d/direction", GPIO_SYS_PATH, gpionum);
sysprintf("echo \"0\" >%s/gpio%d/value", GPIO_SYS_PATH, gpionum);
}
int get_gpio_level(int gpionum)
{
return sysprintf("cat %s/gpio%d/value", GPIO_SYS_PATH, gpionum);
}
|
xiyanxiyan10/MisakaServer
|
misaka/lib/common.c
|
C
|
gpl-2.0
| 14,031
|
Kenney
http://opengameart.org/content/space-shooter-redux
http://opengameart.org/content/onscreen-controls-8-styles
|
ShadowBlip/Neteria
|
examples/pygame/CREDITS.md
|
Markdown
|
gpl-2.0
| 116
|
{{template "header" "applications"}}
<div class="breadcrumb">
<a href="/">All applications</a> > <a href="/application/show/{{ .application.Name }}">{{ .application.Name }}</a> > Deploy #{{ .deployment.Id.Hex }}
</div>
</header>
<main>
<div class="box">
<h2 class="box-title"><span class="state state-{{ .deployment.Status}}"></span> <span class="select">{{ .application.Name }}</span></h2>
<ul class="box-list">
<li><span class="box-list-label">Created At :</span> {{ .deployment.CreatedAt.String }}</li>
<li><span class="box-list-label">Last Update :</span> {{ .deployment.UpdatedAt.String }}</li>
<li><span class="box-list-label">Duration :</span> {{ .deployment.Duration.String }}</li>
</ul>
</div>
<div class="box">
{{ if or (eq .deployment.Status "error") (eq .deployment.Status "done") }}
<pre class="stream">{{ .deployment.Logs }}</pre>
{{ else }}
<div class="stream" data-socket="{{ .websocket_proto }}://{{ .public_host }}/ws/application/deployment/{{ .application.Id.Hex }}/{{ .deployment.Id.Hex }}"></div>
{{ end }}
</div>
</main>
{{template "footer"}}
|
KarhuTeam/Karhu
|
views/deployment_show.html
|
HTML
|
gpl-2.0
| 1,180
|
<?php
require_once 'wpml-admin-text-functionality.class.php';
class WPML_Admin_Texts extends WPML_Admin_Text_Functionality{
private $icl_st_cache = array();
/** @var TranslationManagement $tm_instance */
private $tm_instance;
/** @var WPML_String_Translation $st_instance */
private $st_instance;
/**
* @param TranslationManagement $tm_instance
* @param WPML_String_Translation $st_instance
*/
function __construct( &$tm_instance, &$st_instance ) {
add_action( 'plugins_loaded', array( $this, 'icl_st_set_admin_options_filters' ), 10 );
add_filter( 'wpml_unfiltered_admin_string', array( $this, 'unfiltered_admin_string_filter' ), 10, 2 );
$this->tm_instance = &$tm_instance;
$this->st_instance = &$st_instance;
}
function icl_register_admin_options( $array, $key = "", $option = array() ) {
if(is_object($option)) {
$option = object_to_array($option);
}
foreach ( $array as $k => $v ) {
$option = $key === '' ? array( $k => maybe_unserialize( $this->get_option_without_filtering( $k ) ) ) : $option;
if ( is_array( $v ) ) {
$this->icl_register_admin_options( $v, $key . '[' . $k . ']', $option[ $k ] );
} else {
$context = $this->get_context( $key, $k );
if ( $v === '' ) {
icl_unregister_string( $context, $key . $k );
} elseif ( isset( $option[ $k ] ) && ( $key === '' || preg_match_all( '#\[([^\]]+)\]#',
(string) $key,
$opt_key_matches ) > 0 )
) {
icl_register_string( $context, $key . $k, $option[ $k ] );
$vals = array( $k => 1 );
$opt_keys = isset( $opt_key_matches ) ? array_reverse( $opt_key_matches[1] ) : array();
foreach ( $opt_keys as $opt ) {
$vals = array( $opt => $vals );
}
update_option( '_icl_admin_option_names',
array_merge_recursive( (array) get_option( '_icl_admin_option_names' ), $vals ) );
}
}
}
}
function icl_st_render_option_writes( $option_name, $option_value, $option_key = '' ) {
$sub_key = $option_key . '[' . $option_name . ']';
if ( is_array( $option_value ) || is_object( $option_value ) ) {
$output = '<h4><a class="icl_stow_toggler" href="#">+ ' . $option_name
. '</a></h4><ul class="icl_st_option_writes" style="display: none">';
foreach ( $option_value as $key => $value ) {
$output .= '<li>' . $this->icl_st_render_option_writes( $key, $value, $sub_key ) . '</li>';
}
$output .= '</ul>';
} elseif ( is_string( $option_value ) || is_numeric( $option_value ) ) {
$fixed = $this->is_sub_key_fixed( $sub_key );
$string_name = $option_key . $option_name;
$context = $this->get_context( $option_key, $option_name );
$checked = icl_st_is_registered_string( $context, $string_name ) ? ' checked="checked"' : '';
$has_translations = ! $fixed && $checked === ''
&& icl_st_string_has_translations( $context, $string_name )
? ' class="icl_st_has_translations" ' : '';
$input_val = ' value="' . htmlspecialchars( $option_value ) . '" ';
$option_key_name = ' name="icl_admin_options' . $sub_key . '" ';
$input_open = '<input' . ( $fixed ? ' disabled="disabled"' : '' );
$read_only_input_open = '<input type="text" readonly="readonly"';
$output = '<div class="icl_st_admin_string icl_st_' . ( is_numeric( $option_value ) ? 'numeric' : 'string' ) . '">'
. $input_open . ' type="hidden" ' . $option_key_name . ' value="" />'
. $input_open . $has_translations . ' type="checkbox" ' . $option_key_name . $input_val . $checked . ' />'
. $read_only_input_open . ' value="' . $option_name . '" size="32" />'
. $read_only_input_open . $input_val . ' size="48" /></div><br clear="all" />';
}
return isset( $output ) ? $output : '';
}
private function is_sub_key_fixed( $sub_key ) {
if ( $fixed = ( preg_match_all( '#\[([^\]]+)\]#', $sub_key, $matches ) > 0 ) ) {
$fixed_settings = $this->tm_instance->admin_texts_to_translate;
foreach ( $matches[1] as $m ) {
if ( $fixed = isset( $fixed_settings[ $m ] ) ) {
$fixed_settings = $fixed_settings[ $m ];
} else {
break;
}
}
}
return $fixed;
}
private function get_context( $option_key, $option_name ) {
return 'admin_texts_' . ( preg_match( '#\[([^\]]+)\]#', (string) $option_key, $matches ) === 1 ? $matches[1] : $option_name );
}
function icl_st_scan_options_strings() {
$options = wp_load_alloptions();
foreach ( $options as $name => $value ) {
if ( $this->is_blacklisted( $name ) ) {
unset( $options[ $name ] );
} else {
$options[ $name ] = maybe_unserialize( $value );
}
}
return $options;
}
function icl_st_set_admin_options_filters() {
static $option_names;
if ( empty( $option_names ) ) {
$option_names = get_option( '_icl_admin_option_names' );
}
if ( is_array( $option_names ) ) {
foreach ( $option_names as $option_key => $option ) {
if ( $this->is_blacklisted( $option_key ) ) {
unset( $option_names[ $option_key ] );
update_option( '_icl_admin_option_names', $option_names );
}
elseif ( $option_key != 'theme' && $option_key != 'plugin' ) { // theme and plugin are an obsolete format before 3.2
add_filter( 'option_' . $option_key, array( $this, 'icl_st_translate_admin_string' ) );
add_action( 'update_option_' . $option_key, array( $this, 'clear_cache_for_option' ), 10, 0);
}
}
}
}
function icl_st_translate_admin_string( $option_value, $key = "", $name = "", $rec_level = 0 ) {
$lang = $this->st_instance->get_current_string_language( $name );
$option_name = substr( current_filter(), 7 );
$name = $name === '' ? $option_name : $name;
if ( isset( $this->icl_st_cache[ $lang ][ $name ] ) ) {
return $this->icl_st_cache[ $lang ][ $name ];
}
$serialized = is_serialized( $option_value );
$option_value = $serialized ? unserialize( $option_value ) : $option_value;
if ( is_array( $option_value ) || is_object( $option_value ) ) {
foreach ( $option_value as $k => &$value ) {
$value = $this->icl_st_translate_admin_string( $value,
$key . '[' . $name . ']',
$k,
$rec_level + 1 );
}
} else {
if ( $this->is_admin_text( $key , $name ) ) {
$tr = icl_t( 'admin_texts_' . $option_name, $key . $name, $option_value, $hast, true );
$option_value = $hast ? $tr : $option_value;
}
}
$option_value = $serialized ? serialize( $option_value ) : $option_value;
/*
* if sticky links plugin is enabled and set to change links into sticky
* in strings, change those links back into permalinks when displayed
*/
if ( is_string( $option_value ) and class_exists( "WPML_Sticky_links" ) ) {
global $WPML_Sticky_Links;
if ( isset( $WPML_Sticky_Links ) && $WPML_Sticky_Links->settings['sticky_links_strings'] ) {
$option_value = $WPML_Sticky_Links->show_permalinks( $option_value );
}
}
if ( $rec_level === 0 ) {
$this->icl_st_cache[ $lang ][ $name ] = $option_value;
}
return $option_value;
}
private function is_admin_text( $key , $name ) {
static $option_names;
$option_names = empty( $option_names ) ? get_option( '_icl_admin_option_names' ) : $option_names;
if ( $key ) {
$key = ltrim( $key, '[' );
$key = rtrim( $key, ']' );
$keys = explode( '][', $key );
$test_option_names = $option_names;
foreach ( $keys as $key ) {
if ( isset( $test_option_names[ $key ] ) ) {
$test_option_names = $test_option_names[ $key ];
} else {
return false;
}
}
return isset( $test_option_names[ $name ] );
} else {
return isset( $option_names[ $name ] );
}
}
function clear_cache_for_option() {
$option_name = substr( current_filter(), 14 );
foreach ( array_keys( $this->icl_st_cache ) as $lang_code ) {
if ( isset( $this->icl_st_cache[ $lang_code ][ $option_name ] ) ) {
unset ( $this->icl_st_cache[ $lang_code ][ $option_name ] );
}
}
}
/**
* @param mixed $default_value Value to return in case the string does not exists
* @param string $option_name Name of option to retrieve. Expected to not be SQL-escaped.
*
* @return mixed Value set for the option.
*/
function unfiltered_admin_string_filter( $default_value, $option_name ) {
return $this->get_option_without_filtering( $option_name, $default_value );
}
}
|
alvarpoon/evie
|
wp-content/plugins/wpml-string-translation/inc/admin-texts/wpml-admin-texts.class.php
|
PHP
|
gpl-2.0
| 8,755
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Bootstrap 附加导航(Affix)插件</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="jsjquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
/* Custom Styles */
ul.nav-tabs{
width: 140px;
margin-top: 20px;
border-radius: 4px;
border: 1px solid #ddd;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.067);
}
ul.nav-tabs li{
margin: 0;
border-top: 1px solid #ddd;
}
ul.nav-tabs li:first-child{
border-top: none;
}
ul.nav-tabs li a{
margin: 0;
padding: 8px 16px;
border-radius: 0;
}
ul.nav-tabs li.active a, ul.nav-tabs li.active a:hover{
color: #fff;
background: #0088cc;
border: 1px solid #0088cc;
}
ul.nav-tabs li:first-child a{
border-radius: 4px 4px 0 0;
}
ul.nav-tabs li:last-child a{
border-radius: 0 0 4px 4px;
}
ul.nav-tabs.affix{
top: 30px; /* Set the top position of pinned element */
}
</style>
</head>
<body data-spy="scroll" data-target="#myScrollspy">
<div class="container">
<div class="jumbotron">
<h1>Bootstrap Affix</h1>
</div>
<div class="row">
<div class="col-xs-3" id="myScrollspy">
<ul class="nav nav-tabs nav-stacked" data-spy="affix" data-offset-top="125">
<li class="active"><a href="#section-1">第一部分</a></li>
<li><a href="#section-2">第二部分</a></li>
<li><a href="#section-3">第三部分</a></li>
<li><a href="#section-4">第四部分</a></li>
<li><a href="#section-5">第五部分</a></li>
</ul>
</div>
<div class="col-xs-9">
<h2 id="section-1">第一部分</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla. Vivamus nisl leo, blandit at bibendum eu, tristique eget risus. Integer aliquet quam ut elit suscipit, id interdum neque porttitor. Integer faucibus ligula.</p>
<p>Vestibulum quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti. Aliquam sit amet gravida nibh, facilisis gravida odio. Phasellus auctor velit at lacus blandit, commodo iaculis justo viverra. Etiam vitae est arcu. Mauris vel congue dolor. Aliquam eget mi mi. Fusce quam tortor, commodo ac dui quis, bibendum viverra erat. Maecenas mattis lectus enim, quis tincidunt dui molestie euismod. Curabitur et diam tristique, accumsan nunc eu, hendrerit tellus.</p>
<hr>
<h2 id="section-2">第二部分</h2>
<p>Nullam hendrerit justo non leo aliquet imperdiet. Etiam in sagittis lectus. Suspendisse ultrices placerat accumsan. Mauris quis dapibus orci. In dapibus velit blandit pharetra tincidunt. Quisque non sapien nec lacus condimentum facilisis ut iaculis enim. Sed viverra interdum bibendum. Donec ac sollicitudin dolor. Sed fringilla vitae lacus at rutrum. Phasellus congue vestibulum ligula sed consequat.</p>
<p>Vestibulum consectetur scelerisque lacus, ac fermentum lorem convallis sed. Nam odio tortor, dictum quis malesuada at, pellentesque vitae orci. Vivamus elementum, felis eu auctor lobortis, diam velit egestas lacus, quis fermentum metus ante quis urna. Sed at facilisis libero. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum bibendum blandit dolor. Nunc orci dolor, molestie nec nibh in, hendrerit tincidunt ante. Vivamus sem augue, hendrerit non sapien in, mollis ornare augue.</p>
<hr>
<h2 id="section-3">第三部分</h2>
<p>Integer pulvinar leo id risus pellentesque vestibulum. Sed diam libero, sodales eget sapien vel, porttitor bibendum enim. Donec sed nibh vitae lorem porttitor blandit in nec ante. Pellentesque vitae metus ipsum. Phasellus sed nunc ac sem malesuada condimentum. Etiam in aliquam lectus. Nam vel sapien diam. Donec pharetra id arcu eget blandit. Proin imperdiet mattis augue in porttitor. Quisque tempus enim id lobortis feugiat. Suspendisse tincidunt risus quis dolor fringilla blandit. Ut sed sapien at purus lacinia porttitor. Nullam iaculis, felis a pretium ornare, dolor nisl semper tortor, vel sagittis lacus est consequat eros. Sed id pretium nisl. Curabitur dolor nisl, laoreet vitae aliquam id, tincidunt sit amet mauris.</p>
<p>Phasellus vitae suscipit justo. Mauris pharetra feugiat ante id lacinia. Etiam faucibus mauris id tempor egestas. Duis luctus turpis at accumsan tincidunt. Phasellus risus risus, volutpat vel tellus ac, tincidunt fringilla massa. Etiam hendrerit dolor eget ante rutrum adipiscing. Cras interdum ipsum mattis, tempus mauris vel, semper ipsum. Duis sed dolor ut enim lobortis pellentesque ultricies ac ligula. Pellentesque convallis elit nisi, id vulputate ipsum ullamcorper ut. Cras ac pulvinar purus, ac viverra est. Suspendisse potenti. Integer pellentesque neque et elementum tempus. Curabitur bibendum in ligula ut rhoncus.</p>
<p>Quisque pharetra velit id velit iaculis pretium. Nullam a justo sed ligula porta semper eu quis enim. Pellentesque pellentesque, metus at facilisis hendrerit, lectus velit facilisis leo, quis volutpat turpis arcu quis enim. Nulla viverra lorem elementum interdum ultricies. Suspendisse accumsan quam nec ante mollis tempus. Morbi vel accumsan diam, eget convallis tellus. Suspendisse potenti.</p>
<hr>
<h2 id="section-4">第四部分</h2>
<p>Suspendisse a orci facilisis, dignissim tortor vitae, ultrices mi. Vestibulum a iaculis lacus. Phasellus vitae convallis ligula, nec volutpat tellus. Vivamus scelerisque mollis nisl, nec vehicula elit egestas a. Sed luctus metus id mi gravida, faucibus convallis neque pretium. Maecenas quis sapien ut leo fringilla tempor vitae sit amet leo. Donec imperdiet tempus placerat. Pellentesque pulvinar ultrices nunc sed ultrices. Morbi vel mi pretium, fermentum lacus et, viverra tellus. Phasellus sodales libero nec dui convallis, sit amet fermentum sapien auctor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed eu elementum nibh, quis varius libero.</p>
<p>Vestibulum quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti. Aliquam sit amet gravida nibh, facilisis gravida odio. Phasellus auctor velit at lacus blandit, commodo iaculis justo viverra. Etiam vitae est arcu. Mauris vel congue dolor. Aliquam eget mi mi. Fusce quam tortor, commodo ac dui quis, bibendum viverra erat. Maecenas mattis lectus enim, quis tincidunt dui molestie euismod. Curabitur et diam tristique, accumsan nunc eu, hendrerit tellus.</p>
<p>Phasellus fermentum, neque sit amet sodales tempor, enim ante interdum eros, eget luctus ipsum eros ut ligula. Nunc ornare erat quis faucibus molestie. Proin malesuada consequat commodo. Mauris iaculis, eros ut dapibus luctus, massa enim elementum purus, sit amet tristique purus purus nec felis. Morbi vestibulum sapien eget porta pulvinar. Nam at quam diam. Proin rhoncus, felis elementum accumsan dictum, felis nisi vestibulum tellus, et ultrices risus felis in orci. Quisque vestibulum sem nisl, vel congue leo dictum nec. Cras eget est at velit sagittis ullamcorper vel et lectus. In hac habitasse platea dictumst. Etiam interdum iaculis velit, vel sollicitudin lorem feugiat sit amet. Etiam luctus, quam sed sodales aliquam, lorem libero hendrerit urna, faucibus rhoncus massa nibh at felis. Curabitur ac tempus nulla, ut semper erat. Vivamus porta ullamcorper sem, ornare egestas mauris facilisis id.</p>
<p>Ut ut risus nisl. Fusce porttitor eros at magna luctus, non congue nulla eleifend. Aenean porttitor feugiat dolor sit amet facilisis. Pellentesque venenatis magna et risus commodo, a commodo turpis gravida. Nam mollis massa dapibus urna aliquet, quis iaculis elit sodales. Sed eget ornare orci, eu malesuada justo. Nunc lacus augue, dictum quis dui id, lacinia congue quam. Nulla sem sem, aliquam nec dolor ac, tempus convallis nunc. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nulla suscipit convallis iaculis. Quisque eget commodo ligula. Praesent leo dui, facilisis quis eleifend in, aliquet vitae nunc. Suspendisse fermentum odio ac massa ultricies pellentesque. Fusce eu suscipit massa.</p>
<hr>
<h2 id="section-5">第五部分</h2>
<p>Nam eget purus nec est consectetur vehicula. Nullam ultrices nisl risus, in viverra libero egestas sit amet. Etiam porttitor dolor non eros pulvinar malesuada. Vestibulum sit amet est mollis nulla tempus aliquet. Praesent luctus hendrerit arcu non laoreet. Morbi consequat placerat magna, ac ornare odio sagittis sed. Donec vitae ullamcorper purus. Vivamus non metus ac justo porta volutpat.</p>
<p>Vivamus mattis accumsan erat, vel convallis risus pretium nec. Integer nunc nulla, viverra ut sem non, scelerisque vehicula arcu. Fusce bibendum convallis augue sit amet lobortis. Cras porta urna turpis, sodales lobortis purus adipiscing id. Maecenas ullamcorper, turpis suscipit pellentesque fringilla, massa lacus pulvinar mi, nec dignissim velit arcu eget purus. Nam at dapibus tellus, eget euismod nisl. Ut eget venenatis sapien. Vivamus vulputate varius mauris, vel varius nisl facilisis ac. Nulla aliquet justo a nibh ornare, eu congue neque rutrum.</p>
<p>Suspendisse a orci facilisis, dignissim tortor vitae, ultrices mi. Vestibulum a iaculis lacus. Phasellus vitae convallis ligula, nec volutpat tellus. Vivamus scelerisque mollis nisl, nec vehicula elit egestas a. Sed luctus metus id mi gravida, faucibus convallis neque pretium. Maecenas quis sapien ut leo fringilla tempor vitae sit amet leo. Donec imperdiet tempus placerat. Pellentesque pulvinar ultrices nunc sed ultrices. Morbi vel mi pretium, fermentum lacus et, viverra tellus. Phasellus sodales libero nec dui convallis, sit amet fermentum sapien auctor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed eu elementum nibh, quis varius libero.</p>
<p>Morbi sed fermentum ipsum. Morbi a orci vulputate tortor ornare blandit a quis orci. Donec aliquam sodales gravida. In ut ullamcorper nisi, ac pretium velit. Vestibulum vitae lectus volutpat, consequat lorem sit amet, pulvinar tellus. In tincidunt vel leo eget pulvinar. Curabitur a eros non lacus malesuada aliquam. Praesent et tempus odio. Integer a quam nunc. In hac habitasse platea dictumst. Aliquam porta nibh nulla, et mattis turpis placerat eget. Pellentesque dui diam, pellentesque vel gravida id, accumsan eu magna. Sed a semper arcu, ut dignissim leo.</p>
<p>Sed vitae lobortis diam, id molestie magna. Aliquam consequat ipsum quis est dictum ultrices. Aenean nibh velit, fringilla in diam id, blandit hendrerit lacus. Donec vehicula rutrum tellus eget fermentum. Pellentesque ac erat et arcu ornare tincidunt. Aliquam erat volutpat. Vivamus lobortis urna quis gravida semper. In condimentum, est a faucibus luctus, mi dolor cursus mi, id vehicula arcu risus a nibh. Pellentesque blandit sapien lacus, vel vehicula nunc feugiat sit amet.</p>
</div>
</div>
</div>
</body>
</html>
|
youlangu/Study
|
Bootstrap/附加导航.html
|
HTML
|
gpl-2.0
| 11,894
|
/*
* 2.5 block I/O model
*
* Copyright (C) 2001 Jens Axboe <axboe@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 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.
*
* You should have received a copy of the GNU General Public Licens
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
*/
#ifndef __LINUX_BIO_H
#define __LINUX_BIO_H
#include <linux/highmem.h>
#include <linux/mempool.h>
#include <linux/ioprio.h>
#ifdef CONFIG_BLOCK
#include <asm/io.h>
/* BIO_* and request flags are defined in blk_types.h */
#include <linux/blk_types.h>
#define BIO_DEBUG
#ifdef BIO_DEBUG
#define BIO_BUG_ON BUG_ON
#else
#define BIO_BUG_ON
#endif
#define BIO_MAX_PAGES 256
#define BIO_MAX_SIZE (BIO_MAX_PAGES << PAGE_CACHE_SHIFT)
#define BIO_MAX_SECTORS (BIO_MAX_SIZE >> 9)
/*
* was unsigned short, but we might as well be ready for > 64kB I/O pages
*/
struct bio_vec {
struct page *bv_page; /* ¶ÎËùפÁôµÄÎïÀíÒ³ */
unsigned int bv_len; /* ¶ÎµÄ×Ö½Ú³¤¶È */
unsigned int bv_offset; /* Ò³¿òÖжÎÊý¾ÝµÄÆ«ÒÆÁ¿ */
};
struct bio_set;
struct bio;
struct bio_integrity_payload;
typedef void (bio_end_io_t) (struct bio *, int);
typedef void (bio_destructor_t) (struct bio *);
/*
* main unit of I/O for the block layer and lower layers (ie drivers and
* stacking drivers)
*/
struct bio { /* ´ú±íÕýÔÚÏÖ³¡Ö´ÐеÄIO²Ù×÷£¬Ã¿¸ö¿éIOÇëÇó¶¼Í¨¹ýbio½á¹¹Ìå±íʾ */
sector_t bi_sector; /* device address in 512 byte
sectors */
/* ¿éIO²Ù×÷µÄµÚÒ»¸ö´ÅÅÌÉÈÇø */
struct bio *bi_next; /* request queue link */
/* Á´½Óµ½ÇëÇó¶ÓÁеÄÏÂÒ»¸öbio */
struct block_device *bi_bdev; /* Ïà¹ØµÄ¿éÉ豸 */
unsigned long bi_flags; /* status, command, etc */
/* ״̬ºÍÃüÁî±êÖ¾ */
unsigned long bi_rw; /* bottom bits READ/WRITE,
* top bits priority
*/
/* ÓÉö¾Ùbio_rw_flags¶¨Òå */
/* IO²Ù×÷±êÖ¾, READ or WRITE */
unsigned short bi_vcnt; /* how many bio_vec's */
/* bi_io_vecÖ¸ÏòµÄbio_vecÊý×éÖеĸöÊý */
unsigned short bi_idx; /* current index into bvl_vec */
/* bi_io_vecµÄµ±Ç°Ë÷Òý */
/* Number of segments in this BIO after
* physical address coalescing is performed.
*/
unsigned int bi_phys_segments; /* ºÏ²¢Ö®ºóbioÖÐÎïÀí¶ÎµÄ¸öÊý */
unsigned int bi_size; /* residual I/O count */
/* ÐèÒª´«Ë͵ÄIOÊý¾ÝÁ¿ */
/*
* To keep track of the max segment size, we account for the
* sizes of the first and last mergeable segments in this bio.
*/
unsigned int bi_seg_front_size;
unsigned int bi_seg_back_size;
unsigned int bi_max_vecs; /* max bvl_vecs we can hold */
/* bioµÄbio_vecÊý×éÖÐÔÊÐíµÄ×î´ó¶ÎÊý */
unsigned int bi_comp_cpu; /* completion CPU */
atomic_t bi_cnt; /* pin count */
/* bioµÄÒýÓüÆÊý */
struct bio_vec *bi_io_vec; /* the actual vec list */
/* Ö¸ÏòbioµÄbio_vecÊý×éÖеĶεÄÖ¸Õë */
bio_end_io_t *bi_end_io; /* IOÍê³É·½·¨£¬bioµÄIO²Ù×÷½áÊøÊ±µ÷Óõķ½·¨ */
void *bi_private; /* ͨÓÿé²ãºÍ¿éÉ豸Çý¶¯µÄIOÍê³É·½·¨Ê¹ÓõÄÖ¸Õë */
#if defined(CONFIG_BLK_DEV_INTEGRITY)
struct bio_integrity_payload *bi_integrity; /* data integrity */
#endif
bio_destructor_t *bi_destructor; /* destructor */
/* ÊÍ·Åbioʱµ÷ÓõÄÎö¹¹·½·¨,ͨ³£Îªbio_fs_destructor() */
/*
* We can inline a number of vecs at the end of the bio, to avoid
* double allocations for a small number of bio_vecs. This member
* MUST obviously be kept at the very end of the bio.
*/
struct bio_vec bi_inline_vecs[0];
};
static inline bool bio_rw_flagged(struct bio *bio, enum bio_rw_flags flag)
{
return (bio->bi_rw & (1 << flag)) != 0;
}
/*
* upper 16 bits of bi_rw define the io priority of this bio
*/
#define BIO_PRIO_SHIFT (8 * sizeof(unsigned long) - IOPRIO_BITS) /* 48 */
#define bio_prio(bio) ((bio)->bi_rw >> BIO_PRIO_SHIFT)
#define bio_prio_valid(bio) ioprio_valid(bio_prio(bio))
#define bio_set_prio(bio, prio) do { \
WARN_ON(prio >= (1 << IOPRIO_BITS)); \
(bio)->bi_rw &= ((1UL << BIO_PRIO_SHIFT) - 1); \
(bio)->bi_rw |= ((unsigned long) (prio) << BIO_PRIO_SHIFT); \
} while (0)
/*
* various member access, note that bio_data should of course not be used
* on highmem page vectors
*/
#define bio_iovec_idx(bio, idx) (&((bio)->bi_io_vec[(idx)]))
#define bio_iovec(bio) bio_iovec_idx((bio), (bio)->bi_idx)
#define bio_page(bio) bio_iovec((bio))->bv_page /* ·µ»Øbioµ±Ç°Òª²Ù×÷¶ÎËùÔÚµÄpageÒ³ */
#define bio_offset(bio) bio_iovec((bio))->bv_offset /* ·µ»Øbioµ±Ç°Òª²Ù×÷µÄ¶ÎÔÚpageÖÐµÄÆ«ÒÆ */
#define bio_segments(bio) ((bio)->bi_vcnt - (bio)->bi_idx)
#define bio_sectors(bio) ((bio)->bi_size >> 9) /* ¼ÆËãÉÈÇøÊý */
#define bio_empty_barrier(bio) (bio_rw_flagged(bio, BIO_RW_BARRIER) && !bio_has_data(bio) && !bio_rw_flagged(bio, BIO_RW_DISCARD))
static inline unsigned int bio_cur_bytes(struct bio *bio)
{
if (bio->bi_vcnt)
return bio_iovec(bio)->bv_len;
else /* dataless requests such as discard */
return bio->bi_size;
}
/* ·µ»Øbioµ±Ç°Òª²Ù×÷µÄ¶ÎµÄÄÚºËÐéÄâµØÖ· */
static inline void *bio_data(struct bio *bio)
{
if (bio->bi_vcnt)
return page_address(bio_page(bio)) + bio_offset(bio);
return NULL;
}
static inline int bio_has_allocated_vec(struct bio *bio)
{
return bio->bi_io_vec && bio->bi_io_vec != bio->bi_inline_vecs;
}
/*
* will die
*/
#define bio_to_phys(bio) (page_to_phys(bio_page((bio))) + (unsigned long) bio_offset((bio)))
#define bvec_to_phys(bv) (page_to_phys((bv)->bv_page) + (unsigned long) (bv)->bv_offset)
/*
* queues that have highmem support enabled may still need to revert to
* PIO transfers occasionally and thus map high pages temporarily. For
* permanent PIO fall back, user is probably better off disabling highmem
* I/O completely on that queue (see ide-dma for example)
*/
#define __bio_kmap_atomic(bio, idx, kmtype) \
(kmap_atomic(bio_iovec_idx((bio), (idx))->bv_page, kmtype) + \
bio_iovec_idx((bio), (idx))->bv_offset)
#define __bio_kunmap_atomic(addr, kmtype) kunmap_atomic(addr, kmtype)
/*
* merge helpers etc
*/
#define __BVEC_END(bio) bio_iovec_idx((bio), (bio)->bi_vcnt - 1)
#define __BVEC_START(bio) bio_iovec_idx((bio), (bio)->bi_idx)
/* Default implementation of BIOVEC_PHYS_MERGEABLE */
#define __BIOVEC_PHYS_MERGEABLE(vec1, vec2) \
((bvec_to_phys((vec1)) + (vec1)->bv_len) == bvec_to_phys((vec2)))
/*
* allow arch override, for eg virtualized architectures (put in asm/io.h)
*/
#ifndef BIOVEC_PHYS_MERGEABLE
#define BIOVEC_PHYS_MERGEABLE(vec1, vec2) \
__BIOVEC_PHYS_MERGEABLE(vec1, vec2)
#endif
#define __BIO_SEG_BOUNDARY(addr1, addr2, mask) \
(((addr1) | (mask)) == (((addr2) - 1) | (mask)))
#define BIOVEC_SEG_BOUNDARY(q, b1, b2) \
__BIO_SEG_BOUNDARY(bvec_to_phys((b1)), bvec_to_phys((b2)) + (b2)->bv_len, queue_segment_boundary((q)))
#define BIO_SEG_BOUNDARY(q, b1, b2) \
BIOVEC_SEG_BOUNDARY((q), __BVEC_END((b1)), __BVEC_START((b2)))
#define bio_io_error(bio) bio_endio((bio), -EIO)
/*
* drivers should not use the __ version unless they _really_ want to
* run through the entire bio and not just pending pieces
*/
#define __bio_for_each_segment(bvl, bio, i, start_idx) \
for (bvl = bio_iovec_idx((bio), (start_idx)), i = (start_idx); \
i < (bio)->bi_vcnt; \
bvl++, i++)
#define bio_for_each_segment(bvl, bio, i) \
__bio_for_each_segment(bvl, bio, i, (bio)->bi_idx)
/*
* get a reference to a bio, so it won't disappear. the intended use is
* something like:
*
* bio_get(bio);
* submit_bio(rw, bio);
* if (bio->bi_flags ...)
* do_something
* bio_put(bio);
*
* without the bio_get(), it could potentially complete I/O before submit_bio
* returns. and then bio would be freed memory when if (bio->bi_flags ...)
* runs
*/
#define bio_get(bio) atomic_inc(&(bio)->bi_cnt)
#if defined(CONFIG_BLK_DEV_INTEGRITY)
/*
* bio integrity payload
*/
struct bio_integrity_payload {
struct bio *bip_bio; /* parent bio */
sector_t bip_sector; /* virtual start sector */
void *bip_buf; /* generated integrity data */
bio_end_io_t *bip_end_io; /* saved I/O completion fn */
unsigned int bip_size;
unsigned short bip_slab; /* slab the bip came from */
unsigned short bip_vcnt; /* # of integrity bio_vecs */
unsigned short bip_idx; /* current bip_vec index */
struct work_struct bip_work; /* I/O completion */
struct bio_vec bip_vec[0]; /* embedded bvec array */
};
#endif /* CONFIG_BLK_DEV_INTEGRITY */
/*
* A bio_pair is used when we need to split a bio.
* This can only happen for a bio that refers to just one
* page of data, and in the unusual situation when the
* page crosses a chunk/device boundary
*
* The address of the master bio is stored in bio1.bi_private
* The address of the pool the pair was allocated from is stored
* in bio2.bi_private
*/
struct bio_pair {
struct bio bio1, bio2;
struct bio_vec bv1, bv2;
#if defined(CONFIG_BLK_DEV_INTEGRITY)
struct bio_integrity_payload bip1, bip2;
struct bio_vec iv1, iv2;
#endif
atomic_t cnt;
int error;
};
extern struct bio_pair *bio_split(struct bio *bi, int first_sectors);
extern void bio_pair_release(struct bio_pair *dbio);
extern struct bio_set *bioset_create(unsigned int, unsigned int);
extern void bioset_free(struct bio_set *);
extern struct bio *bio_alloc(gfp_t, int);
extern struct bio *bio_kmalloc(gfp_t, int);
extern struct bio *bio_alloc_bioset(gfp_t, int, struct bio_set *);
extern void bio_put(struct bio *);
extern void bio_free(struct bio *, struct bio_set *);
extern void bio_endio(struct bio *, int);
struct request_queue;
extern int bio_phys_segments(struct request_queue *, struct bio *);
extern void __bio_clone(struct bio *, struct bio *);
extern struct bio *bio_clone(struct bio *, gfp_t);
extern void bio_init(struct bio *);
extern int bio_add_page(struct bio *, struct page *, unsigned int,unsigned int);
extern int bio_add_pc_page(struct request_queue *, struct bio *, struct page *,
unsigned int, unsigned int);
extern int bio_get_nr_vecs(struct block_device *);
extern sector_t bio_sector_offset(struct bio *, unsigned short, unsigned int);
extern struct bio *bio_map_user(struct request_queue *, struct block_device *,
unsigned long, unsigned int, int, gfp_t);
struct sg_iovec;
struct rq_map_data;
extern struct bio *bio_map_user_iov(struct request_queue *,
struct block_device *,
struct sg_iovec *, int, int, gfp_t);
extern void bio_unmap_user(struct bio *);
extern struct bio *bio_map_kern(struct request_queue *, void *, unsigned int,
gfp_t);
extern struct bio *bio_copy_kern(struct request_queue *, void *, unsigned int,
gfp_t, int);
extern void bio_set_pages_dirty(struct bio *bio);
extern void bio_check_pages_dirty(struct bio *bio);
extern struct bio *bio_copy_user(struct request_queue *, struct rq_map_data *,
unsigned long, unsigned int, int, gfp_t);
extern struct bio *bio_copy_user_iov(struct request_queue *,
struct rq_map_data *, struct sg_iovec *,
int, int, gfp_t);
extern int bio_uncopy_user(struct bio *);
void zero_fill_bio(struct bio *bio);
extern struct bio_vec *bvec_alloc_bs(gfp_t, int, unsigned long *, struct bio_set *);
extern void bvec_free_bs(struct bio_set *, struct bio_vec *, unsigned int);
extern unsigned int bvec_nr_vecs(unsigned short idx);
/*
* Allow queuer to specify a completion CPU for this bio
*/
static inline void bio_set_completion_cpu(struct bio *bio, unsigned int cpu)
{
bio->bi_comp_cpu = cpu;
}
/*
* bio_set is used to allow other portions of the IO system to
* allocate their own private memory pools for bio and iovec structures.
* These memory pools in turn all allocate from the bio_slab
* and the bvec_slabs[].
*/
#define BIO_POOL_SIZE 2
#define BIOVEC_NR_POOLS 6
#define BIOVEC_MAX_IDX (BIOVEC_NR_POOLS - 1)
struct bio_set {
struct kmem_cache *bio_slab;
unsigned int front_pad;
mempool_t *bio_pool;
#if defined(CONFIG_BLK_DEV_INTEGRITY)
mempool_t *bio_integrity_pool;
#endif
mempool_t *bvec_pool;
};
struct biovec_slab {
int nr_vecs;
char *name;
struct kmem_cache *slab;
};
extern struct bio_set *fs_bio_set;
/*
* a small number of entries is fine, not going to be performance critical.
* basically we just need to survive
*/
#define BIO_SPLIT_ENTRIES 2
#ifdef CONFIG_HIGHMEM
/*
* remember never ever reenable interrupts between a bvec_kmap_irq and
* bvec_kunmap_irq!
*
* This function MUST be inlined - it plays with the CPU interrupt flags.
*/
static __always_inline char *bvec_kmap_irq(struct bio_vec *bvec,
unsigned long *flags)
{
unsigned long addr;
/*
* might not be a highmem page, but the preempt/irq count
* balancing is a lot nicer this way
*/
local_irq_save(*flags);
addr = (unsigned long) kmap_atomic(bvec->bv_page, KM_BIO_SRC_IRQ);
BUG_ON(addr & ~PAGE_MASK);
return (char *) addr + bvec->bv_offset;
}
static __always_inline void bvec_kunmap_irq(char *buffer,
unsigned long *flags)
{
unsigned long ptr = (unsigned long) buffer & PAGE_MASK;
kunmap_atomic((void *) ptr, KM_BIO_SRC_IRQ);
local_irq_restore(*flags);
}
#else
#define bvec_kmap_irq(bvec, flags) (page_address((bvec)->bv_page) + (bvec)->bv_offset)
#define bvec_kunmap_irq(buf, flags) do { *(flags) = 0; } while (0)
#endif
static inline char *__bio_kmap_irq(struct bio *bio, unsigned short idx,
unsigned long *flags)
{
return bvec_kmap_irq(bio_iovec_idx(bio, idx), flags);
}
#define __bio_kunmap_irq(buf, flags) bvec_kunmap_irq(buf, flags)
#define bio_kmap_irq(bio, flags) \
__bio_kmap_irq((bio), (bio)->bi_idx, (flags))
#define bio_kunmap_irq(buf,flags) __bio_kunmap_irq(buf, flags)
/*
* Check whether this bio carries any data or not. A NULL bio is allowed.
*/
/* bioÖÐÓÐÊý¾Ý·µ»Ø1£¬·ñÔò0 */
static inline int bio_has_data(struct bio *bio)
{
return bio && bio->bi_io_vec != NULL;
}
/*
* BIO list management for use by remapping drivers (e.g. DM or MD) and loop.
*
* A bio_list anchors a singly-linked list of bios chained through the bi_next
* member of the bio. The bio_list also caches the last list member to allow
* fast access to the tail.
*/
struct bio_list {
struct bio *head;
struct bio *tail;
};
static inline int bio_list_empty(const struct bio_list *bl)
{
return bl->head == NULL;
}
static inline void bio_list_init(struct bio_list *bl)
{
bl->head = bl->tail = NULL;
}
#define bio_list_for_each(bio, bl) \
for (bio = (bl)->head; bio; bio = bio->bi_next)
static inline unsigned bio_list_size(const struct bio_list *bl)
{
unsigned sz = 0;
struct bio *bio;
bio_list_for_each(bio, bl)
sz++;
return sz;
}
static inline void bio_list_add(struct bio_list *bl, struct bio *bio)
{
bio->bi_next = NULL;
if (bl->tail)
bl->tail->bi_next = bio;
else
bl->head = bio;
bl->tail = bio;
}
static inline void bio_list_add_head(struct bio_list *bl, struct bio *bio)
{
bio->bi_next = bl->head;
bl->head = bio;
if (!bl->tail)
bl->tail = bio;
}
static inline void bio_list_merge(struct bio_list *bl, struct bio_list *bl2)
{
if (!bl2->head)
return;
if (bl->tail)
bl->tail->bi_next = bl2->head;
else
bl->head = bl2->head;
bl->tail = bl2->tail;
}
static inline void bio_list_merge_head(struct bio_list *bl,
struct bio_list *bl2)
{
if (!bl2->head)
return;
if (bl->head)
bl2->tail->bi_next = bl->head;
else
bl->tail = bl2->tail;
bl->head = bl2->head;
}
static inline struct bio *bio_list_peek(struct bio_list *bl)
{
return bl->head;
}
static inline struct bio *bio_list_pop(struct bio_list *bl)
{
struct bio *bio = bl->head;
if (bio) {
bl->head = bl->head->bi_next;
if (!bl->head)
bl->tail = NULL;
bio->bi_next = NULL;
}
return bio;
}
static inline struct bio *bio_list_get(struct bio_list *bl)
{
struct bio *bio = bl->head;
bl->head = bl->tail = NULL;
return bio;
}
#if defined(CONFIG_BLK_DEV_INTEGRITY)
#define bip_vec_idx(bip, idx) (&(bip->bip_vec[(idx)]))
#define bip_vec(bip) bip_vec_idx(bip, 0)
#define __bip_for_each_vec(bvl, bip, i, start_idx) \
for (bvl = bip_vec_idx((bip), (start_idx)), i = (start_idx); \
i < (bip)->bip_vcnt; \
bvl++, i++)
#define bip_for_each_vec(bvl, bip, i) \
__bip_for_each_vec(bvl, bip, i, (bip)->bip_idx)
#define bio_integrity(bio) (bio->bi_integrity != NULL)
extern struct bio_integrity_payload *bio_integrity_alloc_bioset(struct bio *, gfp_t, unsigned int, struct bio_set *);
extern struct bio_integrity_payload *bio_integrity_alloc(struct bio *, gfp_t, unsigned int);
extern void bio_integrity_free(struct bio *, struct bio_set *);
extern int bio_integrity_add_page(struct bio *, struct page *, unsigned int, unsigned int);
extern int bio_integrity_enabled(struct bio *bio);
extern int bio_integrity_set_tag(struct bio *, void *, unsigned int);
extern int bio_integrity_get_tag(struct bio *, void *, unsigned int);
extern int bio_integrity_prep(struct bio *);
extern void bio_integrity_endio(struct bio *, int);
extern void bio_integrity_advance(struct bio *, unsigned int);
extern void bio_integrity_trim(struct bio *, unsigned int, unsigned int);
extern void bio_integrity_split(struct bio *, struct bio_pair *, int);
extern int bio_integrity_clone(struct bio *, struct bio *, gfp_t, struct bio_set *);
extern int bioset_integrity_create(struct bio_set *, int);
extern void bioset_integrity_free(struct bio_set *);
extern void bio_integrity_init(void);
#else /* CONFIG_BLK_DEV_INTEGRITY */
#define bio_integrity(a) (0)
#define bioset_integrity_create(a, b) (0)
#define bio_integrity_prep(a) (0)
#define bio_integrity_enabled(a) (0)
#define bio_integrity_clone(a, b, c, d) (0)
#define bioset_integrity_free(a) do { } while (0)
#define bio_integrity_free(a, b) do { } while (0)
#define bio_integrity_endio(a, b) do { } while (0)
#define bio_integrity_advance(a, b) do { } while (0)
#define bio_integrity_trim(a, b, c) do { } while (0)
#define bio_integrity_split(a, b, c) do { } while (0)
#define bio_integrity_set_tag(a, b, c) do { } while (0)
#define bio_integrity_get_tag(a, b, c) do { } while (0)
#define bio_integrity_init(a) do { } while (0)
#endif /* CONFIG_BLK_DEV_INTEGRITY */
#endif /* CONFIG_BLOCK */
#endif /* __LINUX_BIO_H */
|
decly/kernel-2.6.32
|
include/linux/bio.h
|
C
|
gpl-2.0
| 18,364
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entity.LitigeDbi;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Fabou
*/
@Stateless
public class LitigeDbiFacade extends AbstractFacade<LitigeDbi> {
@PersistenceContext(unitName = "AppWebGBIEPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public LitigeDbiFacade() {
super(LitigeDbi.class);
}
}
|
gdevsign/pfrc
|
AppWebGBIE/src/java/session/LitigeDbiFacade.java
|
Java
|
gpl-2.0
| 693
|
# Quick Start
List all available gate tasks:
```
mx gate --summary --dry-run
```
Run the gate tasks of interest:
```
mx gate --tags sulongBasic,llvm,nwcc
```
The example above runs a basic collection of sulong tests and tests from the LLVM and the NWCC test suites:
# Sulong Gate
Most of the continuous integration testing of Sulong is driven by `mx gate`.
With `mx gate`, actions are organized in _tasks_ with a unique name.
Usually, a task calls out to other tools (e.g. JUnit, Spotbugs, etc.) to do the actual work.
Tasks can be associated with an arbitrary number of tags.
The `--tags` option restricts the tasks ran by `mx gate`.
To run all available tasks use `mx gate`.
Please note that this command aborts as soon as one test has failed.
You can get a summary of gate jobs without executing anything:
```
mx gate --summary --dry-run
```
The Sulong gate contains general tasks which are common for many `mx` suites,
such as building the sources and various style checks, and tasks that test functionality of Sulong.
These Sulong specific tasks start with `Test`.
The task filter (`-t`/`--task-filter`) can be used to only show these:
```
mx gate --summary --dry-run -t Test
```
This will print a list including the _task name_, a _description_ and the _tags_ for the gate task:
```
Gate task summary:
...
TestSulong Sulong's internal tests (JUnit SulongSuite) [sulong, sulongBasic, sulongCoverage, run_sulong, run_sulongBasic, run_sulongCoverage]
...
```
### Test Sources
Usually, a Sulong test task executes LLVM Bitcode and verifies the result.
Most of the test cases exist in the form of LLVM Assembly, C, C++, and Fortran files,
which need to be translated to Bitcode before the test can run them.
Building the test sources is not done as part of the test task, but in a separate build task.
Those build tasks start with `Build_`. Again, the task filter is useful:
```
mx gate --summary --dry-run -t Build_
...
Gate task summary:
...
Build_SULONG_STANDALONE_TEST_SUITES Build SULONG_STANDALONE_TEST_SUITES [sulong, sulongBasic, sulongCoverage, build_sulong, build_sulongBasic, build_sulongCoverage]
...
```
The compiled test sources are organized in [_distributions_](https://github.com/graalvm/mx/blob/master/docs/layout-distributions.md),
and live in `<Sulong base dir>/mxbuild/<os>-<arch>/<TEST_DISTRIBUTION_NAME>`.
The `mx paths` command helps to find the exact location (in the example for the distribution `SULONG_STANDALONE_TEST_SUITES`):
```
mx paths --output SULONG_STANDALONE_TEST_SUITES
```
Sulong is tested using both self-maintained test suites and selected tests from external suites.
The build task takes care of downloading all necessary sources for external test suites.
The downloaded external sources will be stored in the `~/.mx/cache` directory.
### Test Harness
The test harness runs the test Bitcode via Sulong and verifies that the result is what we expect.
All our test harnesses are based on [JUnit](https://junit.org) test classes.
There are two categories of JUnit tests, **standalone tests** and **embedded tests**.
#### Standalone Tests
For standalone tests, the test harness executes a Bitcode program via Sulong and compares the
result (standard output, standard error, return code) against a reference program that is executed natively.
These tests can also be executed without the test harness by simply executing the Bitcode via the `lli` launcher.
Usually, standalone tests execute all eligible files found in the _test distribution_.
Thus, the JUnit test class does not need to be modified when creating a new test.
Adding the new test to the _test distribution_ is sufficient.
#### Embedded Tests
For embedded tests, there is no native reference executable because they cover functionality that is specific
to [GraalVM embedding](https://www.graalvm.org/reference-manual/llvm/Interoperability/).
For these tests, the JUnit test class takes care of verifying the result.
Therefore, new tests are not picked up automatically by the test class.
In addition to adding the new Bitcode to the _test distribution_, the test class needs to be modified
to pick up the new file, execute it and verify the result.
### Running the Gate
Running all of `mx gate` is quite time-consuming and not even supported on all platforms.
You can run specific tags by invoking `mx gate --tags [tags]`.
For example to run the `TestSulong` task, execute the following:
```
mx gate --tag sulong
```
The _tags_ that correspond to the _task name_ (e.g. tag `sulong` and task `TestSulong`),
will take care of building the required test sources.
Again, `--dry-run` is useful for checking what would be done:
```
mx gate --summary --dry-run --tag sulong
...
Build_SULONG_STANDALONE_TEST_SUITES Build SULONG_STANDALONE_TEST_SUITES [sulong, sulongBasic, sulongCoverage, build_sulong, build_sulongBasic, build_sulongCoverage]
TestSulong Sulong's internal tests (JUnit SulongSuite) [sulong, sulongBasic, sulongCoverage, run_sulong, run_sulongBasic, run_sulongCoverage]
```
For easier use there are also some compound tags to execute multiple task together:
* `sulongBasic`: tasks that test basic functionality that is expected to run on all platforms in all configurations.
* `sulongMisc`: specific features that might require special setup or only make sense on certain platforms (most likely linux/amd64).
The full `mx gate` command also performs various code quality checks.
* `style`: Use various static analysis tools to ensure code quality, including code formatting and copyright header checks.
* `fullbuild`: Build Sulong with ECJ as well as with Javac and run Spotbugs.
### Running JUnit Tests without `mx gate`
The Sulong test tasks execute JUnit tests by calling the `mx unittest` command.
The description of the `mx gate --summary --dry-run` table mentions which JUnit classes will be executed.
Sometimes it is easier to execute a test directly via `mx unittest`:
```
mx unittest SulongSuite
```
`mx unittest` also supports running only selected tests of a specific test class.
For example, `test[c/max-unsigned-short-to-float-cast.c.dir]` is part of the `SulongSuite` JUnit test class.
You can run only this test via the following command line:
```
mx unittest SulongSuite#test[c/max-unsigned-short-to-float-cast.c.dir]
```
The gate calls `mx unittest` with the `--very-verbose` option, which will print the individual test names.
Another useful `mx unittest` flag is `--color`, which makes the output easier to read.
### Debugging
To attach a debugger to Sulong tests, run `mx` with the `-d` argument, e.g.
`mx -d unittest SulongSuite` or `mx -d gate --tags sulong`.
## Fortran
Some of our tests are Fortran files. Make sure you have GCC, G++, and GFortran
in version 4.5, 4.6 or 4.7 available.
On the Mac you can use Homebrew:
brew tap homebrew/versions
brew install gcc46 --with-fortran
brew link --force gmp4
For the Fortran tests you also need to provide
[DragonEgg](http://dragonegg.llvm.org/) 3.2 and Clang 3.2.
[DragonEgg](http://dragonegg.llvm.org/) is a GCC plugin with which we
can use GCC to compile a source language to LLVM IR. Sulong uses
DragonEgg in its test cases to compile Fortran files to LLVM IR.
Sulong also uses DragonEgg for the C/C++ test cases besides Clang to get
additional "free" test cases for a given C/C++ file. DragonEgg requires
a GCC in the aforementioned versions.
- Sulong expects to find Clang 3.2 in `$DRAGONEGG_LLVM/bin`
- Sulong expects to find GCC 4.5, 4.6 or 4.7 in `$DRAGONEGG_GCC/bin`
- Sulong expects to find `dragonegg.so` under `$DRAGONEGG` or in `$DRAGONEGG_GCC/lib`
## Test Exclusion
Not all tests work under all circumstances. Especially external test suites,
which are not under our control, contain many tests that are not relevant for us (e.g. because they test the C parser).
Other tests only work on certain platforms. To solve this, we maintain `.exclude` files to skip such tests.
Tests that should be excluded when executing a JUnit test class `MyTestClass` should be listed in a file in `tests/configs/MyTestClass/*.exclude`.
The file name does not matter as long as it ends with `.exclude`.
To support platform specific excludes, the `os_arch/<os>/<arch>` subdirectories are only processed for the specific
operating system and architecture. For both, `<os>` and `<arch>`, `others` can be used to implement the "else" case.
### Exclusion Format
The exclusion file should contain one entry per line. Lines that start with `#` are ignored.
The precise format of the exclude entry depends on the test style.
#### Standalone Tests
For _standalone tests_, the entry corresponds to the test folder that contains the Bitcode and reference executable.
If executed with `mx gate` or via `mx unittest --very-verbose`, test folder is printed in square brackets:
```
$ mx unittest --very-verbose SulongSuite
MxJUnitCore
JUnit version 4.12
Using TestEngineConfig service Native
com.oracle.truffle.llvm.tests.SulongSuite started (1 of 1)
test[bitcode/anon-struct.ll.dir]: Passed 603.9 ms
test[bitcode/selectConstant.ll.dir]: Passed 36.2 ms
...
```
Thus, the exclude file should contain a line with `bitcode/anon-struct.ll.dir` to exclude the first test.
#### Embedded Tests
For _embedded tests_, the exclude file should contain the _test method_ (e.g., the Java method
annotated with `@Test`). Example:
```
$ mx unittest --very-verbose CxxMethodsTest
MxJUnitCore
JUnit version 4.12
Using TestEngineConfig service Native
com.oracle.truffle.llvm.tests.interop.CxxMethodsTest started (1 of 1)
testGettersAndSetters: Passed 21.2 ms
testInheritedMethodsFromSuperclass: Passed 3.2 ms
testWrongArity: Passed 4.6 ms
testOverloadedMethods: Passed 2.1 ms
testMemberFunction: Passed 5.8 ms
testNonExistingMethod: Passed 0.5 ms
testAllocPoint: Passed 0.1 ms
testConstructor: Passed 0.3 ms
com.oracle.truffle.llvm.tests.interop.CxxMethodsTest finished 50.9 ms
```
To exclude the first test, the exclude file should contain a line with `testGettersAndSetters`.
_Note:_ embedded JUnit test classes must be annotated in order to make the exclusion mechanism work.
```java
@RunWith(CommonTestUtils.ExcludingTruffleRunner.class)
```
|
smarr/Truffle
|
sulong/docs/contributor/TESTS.md
|
Markdown
|
gpl-2.0
| 10,243
|
<?php
/**
* Tea TO backend functions and definitions
*
* @package TakeaTea
* @subpackage Tea Networks
* @since Tea Theme Options 1.4.8
*
*/
if (!defined('ABSPATH')) {
die('You are not authorized to directly access to this page');
}
//---------------------------------------------------------------------------------------------------------//
/**
* Tea Networks
*
* To get its own Fields
*
* @since Tea Theme Options 1.4.8
*
*/
abstract class Tea_Networks
{
//Define protected/private vars
private $currentpage;
private $includes = array();
protected $adminmessage = '';
/**
* Constructor.
*
* @since Tea Theme Options 1.4.8
*/
public function __construct()
{
//Adds an admin notice
add_action('admin_notices', array(&$this, '__showAdminMessage'));
}
//--------------------------------------------------------------------------//
/**
* FUNCTIONS
**/
/**
* MAIN FUNCTIONS
**/
abstract protected function templatePages();
abstract public function getCallback($request);
abstract public function getConnection($request);
abstract public function getDisconnection($request);
abstract public function getUpdate();
/**
* ACCESSORS
**/
/**
* Retrieve the $currentpage value
*
* @return string $currentpage Get the current page
*
* @since Tea Theme Options 1.4.0
*/
protected function getCurrentPage()
{
//Return value
return $this->currentpage;
}
/**
* Define the $currentpage value
*
* @param string $currentpage Get the current page
*
* @since Tea Theme Options 1.4.0
*/
public function setCurrentPage($currentpage = '')
{
$this->currentpage = $currentpage;
}
/**
* Get includes.
*
* @return array $includes Array of all included files
*
* @since Tea Theme Options 1.4.0
*/
protected function getIncludes()
{
//Return value
return $this->includes;
}
/**
* Set includes.
*
* @param string $context Name of the included file's context
*
* @since Tea Theme Options 1.4.0
*/
protected function setIncludes($context)
{
$includes = $this->getIncludes();
$this->includes[$context] = true;
}
/**
* Display a warning message on the admin panel.
*
* @since Tea Theme Options 1.4.8
*/
public function __showAdminMessage()
{
//Get admin message
$content = $this->adminmessage;
if (!empty($content))
{
//Get template
include('tpl/layouts/__layout_admin_message.tpl.php');
}
}
}
|
dnnsldr/qchs_booster
|
wp-content/plugins/tea-theme-options/classes/class-tea-networks.php
|
PHP
|
gpl-2.0
| 2,769
|
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#define ADAPT_FLAG(x) (x[7] & 0x20)
#define ADAPT_LEN_OK(x) (x[8] >= 7)
#define PCR_FLAG(x) (x[9] & 0x10)
struct meta {
int num;
uint64_t diff, pcr;
};
#define BACKLOG_SIZE 64
#define PACKETS_PER_BUFFER 2000
static unsigned char *data[BACKLOG_SIZE];
static struct meta meta[BACKLOG_SIZE];
sem_t pcr_sem, data_sem;
int done = 0;
static void* writer() {
int num, i;
unsigned int total = 0;
double pcr, diff;
unsigned char *buffer;
int backlog = 0;
int semvalue;
sem_wait(&pcr_sem);
for (;;) {
if (done && (done + 1) % BACKLOG_SIZE == backlog &&
sem_getvalue(&pcr_sem, &semvalue) == 0 && semvalue == 0)
break;
else
sem_wait(&pcr_sem);
pcr = (double)meta[backlog].pcr;
num = meta[backlog].num;
diff = (double)meta[backlog].diff / (double)num;
buffer = data[backlog];
for (i = 0 ; i < num; ++i, buffer += 192) {
pcr += diff;
*(uint32_t*)buffer = htonl(((uint32_t)pcr) & 0x3fffffff);
if (write(1, buffer, 192) != 192) {
perror("write");
exit(1);
}
}
total += num;
fprintf(stderr, "\r%.1f MB", total*192.0f/1024.0f/1024.0f);
sem_post(&data_sem);
backlog = (backlog + 1) % BACKLOG_SIZE;
}
fprintf(stderr, "\n");
return NULL;
}
void reader() {
int num = 0;
int backlog = 0;
uint64_t pcr, oldpcr = 0;
unsigned char *buffer = data[backlog];
while (read(0, buffer+4, 188) == 188) {
++num;
if (ADAPT_FLAG(buffer) && ADAPT_LEN_OK(buffer) && PCR_FLAG(buffer)) {
pcr = (buffer[10] << 25) | (buffer[11] << 17) | (buffer[12] << 9) |
(buffer[13] << 1) | (buffer[14] >> 7);
pcr *= 300;
pcr += ((buffer[14] & 1) << 8) | buffer[15];
meta[backlog].num = num;
if (oldpcr == 0) {
meta[backlog].diff = 0;
meta[backlog].pcr = pcr;
} else {
meta[backlog].diff = pcr - oldpcr;
meta[backlog].pcr = oldpcr;
}
sem_post(&pcr_sem);
oldpcr = pcr;
backlog = (backlog + 1) % BACKLOG_SIZE;
num = 0;
sem_wait(&data_sem);
buffer = data[backlog];
} else {
buffer += 192;
}
if (num >= PACKETS_PER_BUFFER) {
fprintf(stderr, "Buffer :(");
exit(1);
}
}
if (num > 0) {
meta[backlog].num = num;
meta[backlog].diff = meta[(backlog == 0 ? BACKLOG_SIZE : backlog) - 1].diff;
meta[backlog].pcr = oldpcr;
done = backlog;
sem_post(&pcr_sem);
sem_post(&pcr_sem);
}
}
int main() {
int i;
pthread_t thread;
for (i = 0; i < BACKLOG_SIZE; ++i) {
if (!(data[i] = malloc(PACKETS_PER_BUFFER*192))) {
perror("malloc");
return -1;
}
}
if (sem_init(&pcr_sem, 0, 0)) {
perror("sem_init 1");
return -2;
}
if (sem_init(&data_sem, 0, BACKLOG_SIZE - 1)) {
perror("sem_init 2");
return -3;
}
if (pthread_create(&thread, NULL, writer, NULL) != 0)
return -4;
reader();
if (pthread_join(thread, NULL) != 0)
return -5;
sem_destroy(&pcr_sem);
sem_destroy(&data_sem);
return 0;
}
|
tonttu/ps3ize
|
convert/ts_to_m2ts.c
|
C
|
gpl-2.0
| 2,960
|
using UnityEngine;
using System.Collections;
namespace AISystem{
[Category("Animator")]
[System.Serializable]
public class GetFloat : BaseCondition {
[AnimatorParameter(AnimatorParameter.Float)]
public string parameterName;
public FloatComparer comparer;
public float value;
private Animator animator;
private int hash;
public override void OnAwake ()
{
animator = owner.GetComponent<Animator> ();
hash = Animator.StringToHash (parameterName);
}
public override bool Validate ()
{
if(animator != null){
float floatValue=animator.GetFloat(hash);
switch (comparer) {
case FloatComparer.Greater:
return floatValue > value;
case FloatComparer.Less:
return floatValue < value;
}
}
return false;
}
}
}
|
NusantaraBeta/BrawlerRumble
|
Assets/ThirdParty/AI System/Scripts/Conditions/Animator/GetFloat.cs
|
C#
|
gpl-2.0
| 776
|
<?php
require_once "DB.php";
require_once "MDB2.php";
require "conf.php";
require "constants.php";
$VERSANDKOSTEN = 0;
$GESCHENKVERPACKUNG = 0;
$dsnP = array( 'phptype' => 'pgsql',
'username' => $ERPuser,
'password' => $ERPpass,
'hostspec' => $ERPhost,
'database' => $ERPdbname,
'port' => $ERPport);
$log = false;
$erp = false;
/****************************************************
* Debugmeldungen in File schreiben
****************************************************/
if ($debug == "true") // zum Debuggen
{
$log = fopen("tmp/shop.log","a");
}
else
{
$log = false;
}
/****************************************************
* ERPverbindung aufbauen
****************************************************/
$options = array('result_buffering' => false,);
$erp = @DB::connect($dsnP);
$erp = MDB2::factory($dsnP, $options);
if (!$erp)
{
echo $erp->getMessage();
}
if (PEAR::isError($erp))
{
$aktuelleZeit = date("Y-m-d H:i:s");
if ($log)
{
fputs($log,$aktuelleZeit.": ERP-Connect\n");
}
echo $erp->getMessage();
die ($erp->getMessage());
}
else
{
if ($erp->autocommit)
{
$erp->autocommit();
}
}
if ($SHOPchar and ExportMode != "1")
{
$erp->setCharset($SHOPchar);
}
$erp->setFetchMode(MDB2_FETCHMODE_ASSOC);
/****************************************************
* SQL-Befehle absetzen
****************************************************/
function query($db, $sql, $function="--")
{
$aktuelleZeit = date("d.m.y H:i:s");
if ($GLOBALS["log"])
{
fputs($GLOBALS["log"],$aktuelleZeit.": ".$function."\n".$sql."\n");
}
$rc = $GLOBALS[$db]->query($sql);
if ($GLOBALS["log"])
{
fputs($GLOBALS["log"],print_r($rc,true)."\n");
}
if(PEAR::isError($rc))
{
return -99;
}
else
{
return true;
}
}
/****************************************************
* Datenbank abfragen
****************************************************/
function getAll($db, $sql, $function="--")
{
$aktuelleZeit = date("d.m.y H:i:s");
if ($GLOBALS["log"])
{
fputs($GLOBALS["log"],$aktuelleZeit.": ".$function."\n".$sql."\n");
}
$rs = $GLOBALS[$db]->queryAll($sql);
if ($rs->message <> "")
{
if ($GLOBALS["log"])
{
fputs($GLOBALS["log"],print_r($rs,true)."\n");
}
return false;
}
else
{
return $rs;
}
}
/****************************************************
* naechste_freie_Auftragsnummer() Naechste Auftragsnummer (ERP) holen
****************************************************/
function naechste_freie_Auftragsnummer()
{
$sql="select * from defaults";
$sql1="update defaults set sonumber=";
$rs2=getAll("erp",$sql,"naechste_freie_Auftragsnummer");
if ($rs2[0]["sonumber"]) {
$auftrag=$rs2[0]["sonumber"]+1;
$rc=query("erp",$sql1.$auftrag, "naechste_freie_Auftragsnummer");
if ($rc === -99) {
echo "Kann keine Auftragsnummer erzeugen - Abbruch";
exit();
}
return $auftrag;
} else {
return false;
}
}
/****************************************************
* naechste_freie_Kundennummer() Naechste Kundennummer (ERP) holen
****************************************************/
function naechste_freie_Kundennummer()
{
$sql = "select * from defaults";
$sql1 = "update defaults set customernumber='";
$rs2 = getAll("erp", $sql, "naechste_freie_Kundennummer");
if ($rs2[0]["customernumber"])
{
$kdnr = $rs2[0]["customernumber"] + 1;
$rc = query("erp", $sql1.$kdnr."'", "naechste_freie_Kundennummer");
if ($rc === -99)
{
echo "Kann keine Kundennummer erzeugen - Abbruch";
exit();
}
return $kdnr;
}
else
{
return false;
}
}
/**********************************************
* insert_Versandadresse($bestellung, $kundenid)
***********************************************/
function insert_Versandadresse($bestellung, $kundenid)
{
$set = $kundenid;
if ($bestellung["ship-address-2"] != "")
{
$set .= ",'".$bestellung["recipient-name"]."','".$bestellung["ship-address-1"]."','".$bestellung["ship-address-2"]."',";
}
else
{
$set .= ",'".$bestellung["recipient-name"]."','','".$bestellung["ship-address-1"]."',";
}
$set .= "'".$bestellung["ship-postal-code"]."',";
$set .= "'".$bestellung["ship-city"]."',";
if (array_key_exists($bestellung["ship-country"], $GLOBALS["LAND"]))
{
$set .= "'".utf8_encode($GLOBALS["LAND"][$bestellung["ship-country"]])."'";
}
else
{
$set .= "'".$bestellung["ship-country"]."'";
}
$sql = "insert into shipto (trans_id, shiptoname, shiptodepartment_1, shiptostreet, shiptozipcode, shiptocity, shiptocountry, module) values ($set,'CT')";
$rc = query("erp", $sql, "insert_Versandadresse");
if ($rc === -99)
{
return false;
}
$sql = "select shipto_id from shipto where trans_id=$kundenid AND module='CT' order by itime desc limit 1";
$rs = getAll("erp", $sql, "insert_Versandadresse");
if ($rs[0]["shipto_id"] > 0)
{
$sid = $rs[0]["shipto_id"];
return $sid;
}
else
{
echo "Fehler bei abweichender Anschrift ".$bestellung["recipient-name"];
return false;
}
}
/**********************************************
* check_update_Kundendaten($bestellung)
***********************************************/
function check_update_Kundendaten($bestellung)
{
$rc = query("erp","BEGIN WORK","check_update_Kundendaten");
if ($rc === -99)
{
echo "Probleme mit Transaktion. Abbruch!";
exit();
}
if (checkCustomer($bestellung['BuyerEmail'], $bestellung['BuyerName']) == "vorhanden") // Bestandskunde; BuyerEmail (Amazon eindeutig) oder BuyerName vorhanden
{
$msg = "update ";
$kdnr = checke_alte_Kundendaten($bestellung);
if ($kdnr == -1) // Kunde nicht gefunden, neu anlegen.
{
$msg = "insert ";
$kdnr = insert_neuen_Kunden($bestellung);
}
else if (!$kdnr)
{
echo $msg." ".$bestellung["BuyerName"]." fehlgeschlagen!<br>";
continue;
}
}
else // Neukunde
{
$msg = "insert ";
$kdnr = insert_neuen_Kunden($bestellung);
}
echo $bestellung["BuyerName"]." ".$bestellung["Name"]." $kdnr<br>";
// Ggf. Versandadressen eintragen
$versandadressennummer = 0;
if ($kdnr > 0)
{
if ((trim($bestellung["recipient-name"]) <> "") &&
($bestellung["Title"] <> $bestellung["recipient-title"] ||
trim($bestellung["Name"]) <> trim($bestellung["recipient-name"]) ||
$bestellung["AddressLine1"] <> $bestellung["ship-address-1"] ||
$bestellung["AddressLine2"] <> $bestellung["ship-address-2"] ||
$bestellung["PostalCode"] <> $bestellung["ship-postal-code"] ||
$bestellung["City"] <> $bestellung["ship-city"] ||
$bestellung["StateOrRegion"] <> $bestellung["ship-state"] ||
$bestellung["CountryCode"] <> $bestellung["ship-country"]
))
{
$rc = insert_Versandadresse($bestellung, $kdnr);
$versandadressennummer = $rc;
}
}
if (!$kdnr || $rc === -99)
{
echo $msg." ".$bestellung["BuyerName"]." fehlgeschlagen! ($kdnr, $rc)<br>";
$rc = query("erp", "ROLLBACK WORK", "check_update_Kundendaten");
if ($rc === -99)
{
echo "Probleme mit Transaktion. Abbruch!";
exit();
}
}
else
{
$rc = query("erp", "COMMIT WORK", "check_update_Kundendaten");
if ($rc === -99)
{
echo "Probleme mit Transaktion. Abbruch!";
exit();
}
}
return $kdnr."|".$versandadressennummer;
}
/**********************************************
* checke_alte_Kundendaten($bestellung)
***********************************************/
function checke_alte_Kundendaten($bestellung)
{
$sql = "select * from customer where ";
if ($bestellung["BuyerEmail"] != "") { $sql .= "email = '".$bestellung["BuyerEmail"]."'"; }
if ($bestellung["BuyerEmail"] != "" && $bestellung["BuyerName"] != "") { $sql .= " OR "; }
if ($bestellung["BuyerName"] != "") { $sql .= "user = '".$bestellung["BuyerName"]."'"; }
$rs = getAll("erp", $sql, "checke_alte_Kundendaten");
if (!$rs || count($rs) != 1) // Kunde nicht gefunden
{
return -1;
}
$set = "";
// Wenn Kunde gefunden, ab hier die Kundendaten auf den neusten Stand bringen
if ($rs[0]["name"] <> $bestellung["Name"])
{
$name = pg_escape_string($bestellung["Name"]);
$set.="name='".$name."',";
}
if ($rs[0]["greeting"] <> $bestellung["Title"])
{
$set.="greeting='".$bestellung["Title"]."',";
}
if ($bestellung["AddressLine2"] != "")
{
$department_1 = pg_escape_string($bestellung["AddressLine1"]);
$street = pg_escape_string($bestellung["AddressLine2"]);
if ($rs[0]["department_1"] <> $bestellung["AddressLine1"])
{
$set.="department_1='".$department_1."',";
}
if ($rs[0]["street"] <> $bestellung["AddressLine2"])
{
$set.="street='".$street."',";
}
}
else
{
$street = pg_escape_string($bestellung["AddressLine1"]);
if ($rs[0]["street"] <> $bestellung["AddressLine1"])
{
$set.="street='".$street."',";
}
}
if ($rs[0]["zipcode"] <> $bestellung["PostalCode"])
{
$set.="zipcode='".$bestellung["PostalCode"]."',";
}
if ($rs[0]["city"] <> $bestellung["City"])
{
$city = pg_escape_string($bestellung["City"]);
$set.="city='".$city."',";
}
if (array_key_exists($bestellung["CountryCode"], $GLOBALS["LAND"]))
{
if ($rs[0]["country"] <> $GLOBALS["LAND"][$bestellung["CountryCode"]])
{
$set.="country='".utf8_encode($GLOBALS["LAND"][$bestellung["CountryCode"]])."',";
}
}
else
{
if ($rs[0]["country"] <> $bestellung["CountryCode"])
{
$set.="country='".$bestellung["CountryCode"]."',";
}
}
if ($rs[0]["phone"] <> $bestellung["Phone"])
{
$set.="phone='".$bestellung["Phone"]."',";
}
if ($rs[0]["email"] <> $bestellung["BuyerEmail"])
{
$set.="email='".$bestellung["BuyerEmail"]."',";
}
if ($rs[0]["username"] <> $bestellung["BuyerName"])
{
$set.="username='".$bestellung["BuyerName"]."',";
}
if (array_key_exists($bestellung["CountryCode"], $GLOBALS["TAXID"]))
{
$localtaxid = $GLOBALS["TAXID"][$bestellung["CountryCode"]];
}
else
{
$localtaxid = 3; // Wenn nicht vorhanden, dann vermutlich Steuerschluessel Welt
}
if ($rs[0]["taxzone_id"] <> $localtaxid)
{
$set .= "taxzone_id=$localtaxid ";
}
if ($set)
{
$sql = "update customer set ".substr($set,0,-1)." where id=".$rs[0]["id"];
$rc = query("erp", $sql, "checke_alte_Kundendaten");
if ($rc === -99)
{
return false;
}
else
{
return $rs[0]["id"];
}
}
else
{
return $rs[0]["id"];
}
}
/**********************************************
* insert_neuen_Kunden($bestellung)
***********************************************/
function insert_neuen_Kunden($bestellung)
{
$newID = uniqid(rand(time(),1));
// Kundennummer generieren von der ERP
$kdnr = naechste_freie_Kundennummer();
$sql= "select count(*) as anzahl from customer where customernumber = '$kdnr'";
$rs = getAll("erp", $sql, "insert_neuen_Kunden");
if ($rs[0]["anzahl"] > 0) // Kundennummer gibt es schon, eine neue aus ERP
{
$kdnr = naechste_freie_Kundennummer();
}
$sql= "insert into customer (name,customernumber) values ('$newID','$kdnr')";
$rc = query("erp", $sql, "insert_neuen_Kunden");
if ($rc === -99)
{
return false;
}
$sql = "select * from customer where name = '$newID'";
$rs = getAll("erp", $sql, "insert_neuen_Kunden");
if (!$rs)
{
return false;
}
$name = pg_escape_string($bestellung["Name"]);
$set .= "set name='".$name."',";
if ($bestellung["Title"] != "")
{
$set .= "greeting='".$bestellung["Title"]."',";
}
if ($bestellung["AddressLine2"] != "")
{
$department_1 = pg_escape_string($bestellung["AddressLine1"]);
$street = pg_escape_string($bestellung["AddressLine2"]);
$set .= "department_1='".$department_1."',";
$set .= "street='".$street."',";
}
else
{
$street = pg_escape_string($bestellung["AddressLine1"]);
$set .= "street='".$street."',";
}
$set .= "zipcode='".$bestellung["PostalCode"]."',";
$city = pg_escape_string($bestellung["City"]);
$set .= "city='".$city."',";
if (array_key_exists($bestellung["CountryCode"], $GLOBALS["LAND"]))
{
$set .= "country='".utf8_encode($GLOBALS["LAND"][$bestellung["CountryCode"]])."',";
}
else
{
$set .= "country='".$bestellung["CountryCode"]."',";
}
$set .= "phone='".$bestellung["Phone"]."',";
$set .= "email='".$bestellung["BuyerEmail"]."',";
$set .= "username='".$bestellung["BuyerName"]."',";
if (array_key_exists($bestellung["CountryCode"], $GLOBALS["TAXID"]))
{
$localtaxid = $GLOBALS["TAXID"][$bestellung["CountryCode"]];
}
else
{
$localtaxid = 3; // Wenn nicht vorhanden, dann vermutlich Steuerschluessel Welt
}
$set .= "taxzone_id=$localtaxid ";
$sql = "update customer ".$set;
$sql .= "where id=".$rs[0]["id"];
$rc = query("erp", $sql, "insert_neuen_Kunden");
if ($rc === -99)
{
return false;
}
else
{
return $rs[0]["id"];
}
}
/**********************************************
* einfuegen_bestellte_Artikel($artikelliste, $AmazonOrderId, $zugehoerigeAuftragsID, $zugehoerigeAuftragsNummer)
***********************************************/
function einfuegen_bestellte_Artikel($artikelliste, $AmazonOrderId, $zugehoerigeAuftragsID, $zugehoerigeAuftragsNummer)
{
require "conf.php";
$ok = true;
$GLOBALS["VERSANDKOSTEN"] = 0;
$GLOBALS["GESCHENKVERPACKUNG"] = 0;
foreach ($artikelliste as $einzelartikel)
{
$sql = "select * from parts where partnumber='".$einzelartikel["SellerSKU"]."'";
$rs2 = getAll("erp", $sql, "einfuegen_bestellte_Artikel");
if ($rs2[0]["id"])
{
$artID = $rs2[0]["id"];
$artNr = $rs2[0]["partnumber"];
$ordnumber = $zugehoerigeAuftragsNummer;
$lastcost = $rs2[0]["lastcost"];
$longdescription = $rs2[0]["notes"];
$einzelpreis = round($einzelartikel["ItemPrice"] / $einzelartikel["QuantityOrdered"], 2, PHP_ROUND_HALF_UP) - round($einzelartikel["PromotionDiscount"] / $einzelartikel["QuantityOrdered"], 2, PHP_ROUND_HALF_UP);
$text = $rs2[0]["description"];
$sql = "insert into orderitems (trans_id, ordnumber, parts_id, description, longdescription, qty, cusordnumber, sellprice, lastcost, unit, ship, discount) values (";
$sql .= $zugehoerigeAuftragsID.","
.$ordnumber.",'"
.$artID."','"
.$text."','"
.$longdescription."',"
.$einzelartikel["QuantityOrdered"].",'"
.$AmazonOrderId."',"
.$einzelpreis.","
.$lastcost.","
."'Stck',0,0)";
echo " - Artikel:[ Artikel-ID:$artID Artikel-Nummer:<b>$artNr</b> ".$einzelartikel["Title"]." ]<br>";
$rc = query("erp", $sql, "einfuegen_bestellte_Artikel");
if ($rc === -99)
{
$ok = false;
break;
}
}
else if ($fehlendeSKU == "true") // Artikel nicht im Kivitendo, -> Amazon-Werte übernehmen
{
$sql = "select id, partnumber from parts where partnumber='".$platzhalterFehlendeSKU."'";
$rs3 = getAll("erp", $sql, "einfuegen_bestellte_Artikel");
if ($rs3[0]["id"])
{
$artID = $rs3[0]["id"];
$artNr = $rs3[0]["partnumber"]." (".$einzelartikel["SellerSKU"].")";
$einzelpreis = round($einzelartikel["ItemPrice"] / $einzelartikel["QuantityOrdered"], 2, PHP_ROUND_HALF_UP) - round($einzelartikel["PromotionDiscount"] / $einzelartikel["QuantityOrdered"], 2, PHP_ROUND_HALF_UP);
$text = $einzelartikel["Title"];
$sql = "insert into orderitems (trans_id, parts_id, description, qty, longdescription, sellprice, unit, ship, discount) values (";
$sql .= $zugehoerigeAuftragsID.",'"
.$artID."','"
.$text."',"
.$einzelartikel["QuantityOrdered"].",'"
.$AmazonOrderId."',"
.$einzelpreis.",'Stck',0,0)";
echo " - Artikel:[ Artikel-ID:$artID Artikel-Nummer:<b>$artNr</b> ".$einzelartikel["Title"]." ]<br>";
$rc = query("erp", $sql, "einfuegen_bestellte_Artikel");
if ($rc === -99)
{
$ok = false;
break;
}
}
}
$GLOBALS["VERSANDKOSTEN"] += $einzelartikel["ShippingPrice"] - $einzelartikel["ShippingDiscount"];
$GLOBALS["GESCHENKVERPACKUNG"] += $einzelartikel["GiftWrapPrice"];
}
return $ok;
}
/**********************************************
* hole_department_id($department_klarname)
***********************************************/
function hole_department_id($department_klarname)
{
$sql = "select id from department where description='".$department_klarname."'";
$abfrage = getAll("erp", $sql, "hole_department_id");
if ($abfrage[0]["id"])
{
return $abfrage[0]["id"];
}
return "NULL";
}
/**********************************************
* hole_payment_id($zahlungsart)
***********************************************/
function hole_payment_id($zahlungsart)
{
$sql = "select id from payment_terms where description='".$zahlungsart."'";
$abfrage = getAll("erp", $sql, "hole_payment_id");
if ($abfrage[0]["id"])
{
return $abfrage[0]["id"];
}
return "NULL";
}
/**********************************************
* erstelle_Auftrag($bestellung, $kundennummer, $versandadressennummer, $ERPusrID)
***********************************************/
function erstelle_Auftrag($bestellung, $kundennummer, $versandadressennummer, $ERPusrID)
{
require "conf.php";
$brutto = $bestellung["Amount"];
$netto = round($brutto / 1.19, 2, PHP_ROUND_HALF_UP);
// Hier beginnt die Transaktion
$rc = query("erp","BEGIN WORK","erstelle_Auftrag");
if ($rc === -99)
{
echo "Probleme mit Transaktion. Abbruch!"; exit();
}
$auftrag = naechste_freie_Auftragsnummer();
$sql = "select count(*) as anzahl from oe where ordnumber = '$auftrag'";
$rs = getAll("erp", $sql, "erstelle_Auftrag 1");
if ($rs[0]["anzahl"] > 0)
{
$auftrag = naechste_freie_Auftragsnummer();
}
$newID = uniqid (rand());
$sql = "insert into oe (notes,ordnumber,customer_id) values ('$newID','$auftrag','".$kundennummer."')";
$rc = query("erp", $sql, "erstelle_Auftrag 2");
if ($rc === -99)
{
echo "Auftrag ".$bestellung["AmazonOrderId"]." konnte nicht angelegt werden.<br>";
$rc = query("erp", "ROLLBACK WORK", "erstelle_Auftrag");
return false;
}
$sql = "select * from oe where notes = '$newID'";
$rs2 = getAll("erp", $sql, "erstelle_Auftrag 3");
if (!$rs2 > 0)
{
echo "Auftrag ".$bestellung["AmazonOrderId"]." konnte nicht angelegt werden.<br>";
$rc = query("erp", "ROLLBACK WORK", "erstelle_Auftrag");
return false;
}
$sql = "update oe set cusordnumber='".$bestellung["AmazonOrderId"]."', transdate='".$bestellung["PurchaseDate"]."', customer_id=".$kundennummer.", ";
if ($versandadressennummer > 0)
{
$sql .= "shipto_id=".$versandadressennummer.", ";
}
$sql .= "department_id=".hole_department_id($bestellung["MarketplaceId"]).", shippingpoint='".utf8_encode($GLOBALS["VERSAND"][$bestellung["FulfillmentChannel"]])."', ";
$sql .= "amount=".$brutto.", netamount=".$netto.", reqdate='".$bestellung["LastUpdateDate"]."', taxincluded='t', ";
// Versandadresse prüfen (selbige gibt wenn vorhanden den Steuerschluessel vor!
if ($bestellung["ship-country"] != "")
{
if (array_key_exists($bestellung["ship-country"], $GLOBALS["TAXID"]))
{
$localtaxid = $GLOBALS["TAXID"][$bestellung["ship-country"]];
}
else
{
$localtaxid = 3; // Wenn nicht vorhanden, dann vermutlich Steuerschluessel Welt
}
}
else
{
if (array_key_exists($bestellung["CountryCode"], $GLOBALS["TAXID"]))
{
$localtaxid = $GLOBALS["TAXID"][$bestellung["CountryCode"]];
}
else
{
$localtaxid = 3; // Wenn nicht vorhanden, dann vermutlich Steuerschluessel Welt
}
}
$sql .= "taxzone_id=$localtaxid, ";
$sql .= "payment_id=".hole_payment_id($bestellung["PaymentMethod"]).", ";
$bestelldatum = "Bestelldatum: ".date("d.m.Y", strtotime($bestellung["PurchaseDate"])).chr(13);
$versanddatum = "Versanddatum: ".date("d.m.Y", strtotime($bestellung["LastUpdateDate"])).chr(13);
if ($bestellung["CurrencyCode"] != "EUR")
{
$waehrungstext = chr(13)."Originalwaehrung: ".$bestellung["CurrencyCode"].chr(13)."Originalbetrag: ".$bestellung["Amount"]." ".$bestellung["CurrencyCode"].chr(13)."Kurs 1 ".$bestellung["CurrencyCode"]." = x.xx EUR";
}
$sql .= "notes='".$bestellung["OrderComment"]."', intnotes='".$bestelldatum.$versanddatum."SalesChannel ".$bestellung["SalesChannel"]." (".$bestellung["CountryCode"].")".chr(13)."Versand durch ".utf8_encode($GLOBALS["VERSAND"][$bestellung["FulfillmentChannel"]]).$waehrungstext."', ";
$sql .= "curr='".$bestellung["CurrencyCode"]."', employee_id=".$ERPusrID.", vendor_id=NULL ";
$sql .= "where id=".$rs2[0]["id"];
$rc = query("erp",$sql,"erstelle_Auftrag 4");
if ($rc === -99)
{
echo "Auftrag ".$bestellung["AmazonOrderId"]." konnte nicht angelegt werden.<br>";
$rc = query("erp", "ROLLBACK WORK", "erstelle_Auftrag");
if ($rc === -99)
{
echo "Probleme mit Transaktion. Abbruch!"; exit();
}
return false;
}
echo "Auftrag:[ Buchungsnummer:".$rs2[0]["id"]." AuftragsNummer:<b>".$auftrag."</b> ]<br>";
if (!einfuegen_bestellte_Artikel(array_values($bestellung['AmazonOrderIdProducts']), $bestellung["AmazonOrderId"], $rs2[0]["id"], $auftrag))
{
echo "Auftrag ".$bestellung["AmazonOrderId"]." konnte nicht angelegt werden.<br>";
$rc = query("erp", "ROLLBACK WORK", "erstelle_Auftrag");
if ($rc === -99)
{
echo "Probleme mit Transaktion. Abbruch!"; exit();
}
return false;
}
if ($GLOBALS["VERSANDKOSTEN"] > 0)
{
$sql = "select * from parts where partnumber='".$versandkosten."'";
$rsversand = getAll("erp", $sql, "erstelle_Auftrag");
if ($rsversand[0]["id"])
{
$artID = $rsversand[0]["id"];
$artNr = $rsversand[0]["partnumber"];
$einzelpreis = $GLOBALS["VERSANDKOSTEN"];
$text = $rsversand[0]["description"];
$sql = "insert into orderitems (trans_id, parts_id, description, qty, longdescription, sellprice, unit, ship, discount) values (";
$sql .= $rs2[0]["id"].",'"
.$artID."','"
.$text."',"
."1,'"
.$versandkosten."',"
.$einzelpreis.",'Stck',0,0)";
echo " - Artikel:[ Artikel-ID:$artID Artikel-Nummer:<b>$artNr</b> ".$text." ]<br>";
$rc = query("erp", $sql, "erstelle_Auftrag");
if ($rc === -99)
{
echo "Auftrag $auftrag : Fehler bei den Versandkosten<br>";
}
}
}
if ($GLOBALS["GESCHENKVERPACKUNG"] > 0)
{
$sql = "select * from parts where partnumber='".$geschenkverpackung."'";
$rsversand = getAll("erp", $sql, "erstelle_Auftrag");
if ($rsversand[0]["id"])
{
$artID = $rsversand[0]["id"];
$artNr = $rsversand[0]["partnumber"];
$einzelpreis = $GLOBALS["GESCHENKVERPACKUNG"];
$text = $rsversand[0]["description"];
$sql = "insert into orderitems (trans_id, parts_id, description, qty, longdescription, sellprice, unit, ship, discount) values (";
$sql .= $rs2[0]["id"].",'"
.$artID."','"
.$text."',"
."1,'"
.$geschenkverpackung."',"
.$einzelpreis.",'Stck',0,0)";
echo " - Artikel:[ Artikel-ID:$artID Artikel-Nummer:<b>$artNr</b> ".$text." ]<br>";
$rc = query("erp", $sql, "erstelle_Auftrag");
if ($rc === -99)
{
echo "Auftrag $auftrag : Fehler bei den Geschenkverpackungskosten<br>";
}
}
}
$rc = query("erp", "COMMIT WORK", "erstelle_Auftrag");
if ($rc === -99)
{
echo "Probleme mit Transaktion. Abbruch!"; exit();
}
return true;
}
/**********************************************
* checkAmazonOrderId($AmazonOrderId)
***********************************************/
function checkAmazonOrderId($AmazonOrderId)
{
require_once "DB.php";
require "conf.php";
$dsnP = array(
'phptype' => 'pgsql',
'username' => $ERPuser,
'password' => $ERPpass,
'hostspec' => $ERPhost,
'database' => $ERPdbname,
'port' => $ERPport
);
$status = "neu";
$dbP = @DB::connect($dsnP);
if (DB::isError($dbP)||!$dbP)
{
$status = "Keine Verbindung zur ERP<br>".$dbP->userinfo;
$dbP = false;
}
else
{
// Auftraege checken
$rs = $dbP->getall("select cusordnumber from oe where cusordnumber = '".$AmazonOrderId."'");
if (count($rs) >= 1)
{
$status = "auftrag";
}
// Lieferscheine checken
$rs = $dbP->getall("select cusordnumber from delivery_orders where cusordnumber = '".$AmazonOrderId."'");
if (count($rs) >= 1)
{
$status = "lieferschein";
}
// Rechnungen checken
$rs = $dbP->getall("select cusordnumber from ar where cusordnumber = '".$AmazonOrderId."'");
if (count($rs) >= 1)
{
$status = "rechnung";
}
// Emails checken
if ($status == "rechnung")
{
$rs = $dbP->getall("select cusordnumber from ar where cusordnumber = '".$AmazonOrderId."' and intnotes LIKE '%[email]%'");
if (count($rs) >= 1)
{
$status = "email";
}
}
}
return $status;
}
/**********************************************
* checkCustomer($BuyerEmail, $BuyerName)
***********************************************/
function checkCustomer($BuyerEmail, $BuyerName)
{
require_once "DB.php";
require "conf.php";
$dsnP = array(
'phptype' => 'pgsql',
'username' => $ERPuser,
'password' => $ERPpass,
'hostspec' => $ERPhost,
'database' => $ERPdbname,
'port' => $ERPport
);
$status = "neu";
$dbP = @DB::connect($dsnP);
if (DB::isError($dbP)||!$dbP)
{
$status = "Keine Verbindung zur ERP<br>".$dbP->userinfo;
$dbP = false;
}
else if ($BuyerEmail == "" && $BuyerName == "")
{
$status = "-";
}
else
{
// Email checken
if ($BuyerEmail != "")
{
$rs = $dbP->getall("select customernumber from customer where email = '".$BuyerEmail."'");
if (count($rs) == 1)
{
$status = "vorhanden";
}
}
if ($BuyerName != "")
{
// BuyerName checken
$rs = $dbP->getall("select customernumber from customer where username = '".$BuyerName."'");
if (count($rs) == 1)
{
$status = "vorhanden";
}
}
}
return $status;
}
?>
|
mark-sch/Finance5
|
io/erpfunctions.php
|
PHP
|
gpl-2.0
| 25,369
|
// your answer would go here
$(function (){
var container = $('#rating-container');
$('#max-value').val('');
var update_circles =function (){
for (var i = 0; i < container.attr('max-value'); i++){
container.append('<div class="rating-circle"></div>');
}
}
$('#save-rating').click(function(){
$.post('http://jquery-edx.azurewebsites.net/api/Rating',
{
value: $('.rating-chosen').length,
maxValue: container.attr('max-value')
},
function(data) {
$('#output').text(data.message);
}
);
})
$('#update-max-value').click(function(){
$('.rating-circle').remove();
input_num = parseInt($('#max-value').val());
if (Number.isInteger(input_num) && input_num > 0 && input_num < 100){
container.attr('max-value', input_num);
}
else{
alert('Please input number from 1 to 99');
}
update_circles();
});
container.delegate('.rating-circle', 'mouseover', function(){
$('.rating-chosen').addClass('rating-chosen-removed');
$('.rating-chosen').removeClass('rating-chosen');
$(this).prevAll().andSelf().addClass('rating-hover');
});
container.delegate('.rating-circle', 'mouseout', function(){
$('.rating-chosen-removed').addClass('rating-chosen');
$('.rating-chosen').removeClass('rating-chosen-removed');
$(this).prevAll().andSelf().removeClass('rating-hover');
});
container.delegate('.rating-circle', 'click', function(){
$(this).prevAll().andSelf().addClass('rating-chosen');
$(this).nextAll().removeClass('rating-chosen-removed rating-chosen');
});
update_circles();
});
|
mikedanylov/jQuery-practise
|
lab3/main.js
|
JavaScript
|
gpl-2.0
| 1,812
|
<div class="wrap kamn-easy-twitter-feed-widget-settings">
<?php
/** Get the plugin data. */
$kamn_easy_twitter_feed_widget_plugin_data = kamn_easy_twitter_feed_widget_plugin_data();
screen_icon();
?>
<h2><?php echo sprintf( __( '%1$s Settings', 'kamn-easy-twitter-feed-widget' ), $kamn_easy_twitter_feed_widget_plugin_data['Name'] ); ?></h2>
<?php settings_errors(); ?>
<div class="kamn-easy-twitter-feed-widget-promo-wrapper">
<a href="http://designorbital.com/premium-wordpress-themes/" class="button button-primary button-hero" target="_blank"><?php _e( 'Premium WordPress Themes', 'kamn-easy-twitter-feed-widget' ); ?></a>
<a href="http://designorbital.com/free-wordpress-themes/" class="button button-hero" target="_blank"><?php _e( 'Free WordPress Themes', 'kamn-easy-twitter-feed-widget' ); ?></a>
</div>
<form action="options.php" method="post" id="kamn-easy-twitter-feed-widget-form-wrapper">
<div id="kamn-easy-twitter-feed-widget-form-header" class="kamn-easy-twitter-feed-widget-clearfix">
<input type="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'kamn-easy-twitter-feed-widget' ); ?>">
</div>
<?php settings_fields( 'kamn_easy_twitter_feed_widget_options_group' ); ?>
<div id="kamn-easy-twitter-feed-widget-sidebar">
<ul id="kamn-easy-twitter-feed-widget-group-menu">
<li id="0_section_group_li" class="kamn-easy-twitter-feed-widget-group-tab-link-li active"><a href="javascript:void(0);" id="0_section_group_li_a" class="kamn-easy-twitter-feed-widget-group-tab-link-a" data-rel="0"><span><?php _e( 'Twitter Script Settings', 'kamn-easy-twitter-feed-widget' ); ?></span></a></li>
<li id="1_section_group_li" class="kamn-easy-twitter-feed-widget-group-tab-link-li"><a href="javascript:void(0);" id="1_section_group_li_a" class="kamn-easy-twitter-feed-widget-group-tab-link-a" data-rel="1"><span><?php _e( 'General Settings', 'kamn-easy-twitter-feed-widget' ); ?></span></a></li>
</ul>
</div>
<div id="kamn-easy-twitter-feed-widget-main">
<div id="0_section_group" class="kamn-easy-twitter-feed-widget-group-tab">
<?php do_settings_sections( 'kamn_easy_twitter_feed_widget_section_script_page' ); ?>
</div>
<div id="1_section_group" class="kamn-easy-twitter-feed-widget-group-tab">
<?php do_settings_sections( 'kamn_easy_twitter_feed_widget_section_general_page' ); ?>
</div>
</div>
<div class="kamn-easy-twitter-feed-widget-clear"></div>
<div id="kamn-easy-twitter-feed-widget-form-footer" class="kamn-easy-twitter-feed-widget-clearfix">
<input type="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'kamn-easy-twitter-feed-widget' ); ?>">
</div>
</form>
</div>
|
delfintrinidadIV/firstproject
|
wp-content/plugins/easy-twitter-feed-widget/lib/admin/page.php
|
PHP
|
gpl-2.0
| 2,851
|
/*
* Copyright (C) 2016 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.porogram.profosure1.messenger.exoplayer2.upstream;
import android.support.annotation.IntDef;
import android.text.TextUtils;
import com.porogram.profosure1.messenger.exoplayer2.util.Predicate;
import com.porogram.profosure1.messenger.exoplayer2.util.Util;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Map;
/**
* An HTTP {@link DataSource}.
*/
public interface HttpDataSource extends DataSource {
/**
* A factory for {@link HttpDataSource} instances.
*/
interface Factory extends DataSource.Factory {
@Override
HttpDataSource createDataSource();
}
/**
* A {@link Predicate} that rejects content types often used for pay-walls.
*/
Predicate<String> REJECT_PAYWALL_TYPES = new Predicate<String>() {
@Override
public boolean evaluate(String contentType) {
contentType = Util.toLowerInvariant(contentType);
return !TextUtils.isEmpty(contentType)
&& (!contentType.contains("text") || contentType.contains("text/vtt"))
&& !contentType.contains("html") && !contentType.contains("xml");
}
};
/**
* Thrown when an error is encountered when trying to read from a {@link HttpDataSource}.
*/
class HttpDataSourceException extends IOException {
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_OPEN, TYPE_READ, TYPE_CLOSE})
public @interface Type {}
public static final int TYPE_OPEN = 1;
public static final int TYPE_READ = 2;
public static final int TYPE_CLOSE = 3;
@Type
public final int type;
/**
* The {@link DataSpec} associated with the current connection.
*/
public final DataSpec dataSpec;
public HttpDataSourceException(DataSpec dataSpec, @Type int type) {
super();
this.dataSpec = dataSpec;
this.type = type;
}
public HttpDataSourceException(String message, DataSpec dataSpec, @Type int type) {
super(message);
this.dataSpec = dataSpec;
this.type = type;
}
public HttpDataSourceException(IOException cause, DataSpec dataSpec, @Type int type) {
super(cause);
this.dataSpec = dataSpec;
this.type = type;
}
public HttpDataSourceException(String message, IOException cause, DataSpec dataSpec,
@Type int type) {
super(message, cause);
this.dataSpec = dataSpec;
this.type = type;
}
}
/**
* Thrown when the content type is invalid.
*/
final class InvalidContentTypeException extends HttpDataSourceException {
public final String contentType;
public InvalidContentTypeException(String contentType, DataSpec dataSpec) {
super("Invalid content type: " + contentType, dataSpec, TYPE_OPEN);
this.contentType = contentType;
}
}
/**
* Thrown when an attempt to open a connection results in a response code not in the 2xx range.
*/
final class InvalidResponseCodeException extends HttpDataSourceException {
/**
* The response code that was outside of the 2xx range.
*/
public final int responseCode;
/**
* An unmodifiable map of the response header fields and values.
*/
public final Map<String, List<String>> headerFields;
public InvalidResponseCodeException(int responseCode, Map<String, List<String>> headerFields,
DataSpec dataSpec) {
super("Response code: " + responseCode, dataSpec, TYPE_OPEN);
this.responseCode = responseCode;
this.headerFields = headerFields;
}
}
@Override
long open(DataSpec dataSpec) throws HttpDataSourceException;
@Override
void close() throws HttpDataSourceException;
@Override
int read(byte[] buffer, int offset, int readLength) throws HttpDataSourceException;
/**
* Sets the value of a request header field. The value will be used for subsequent connections
* established by the source.
*
* @param name The name of the header field.
* @param value The value of the field.
*/
void setRequestProperty(String name, String value);
/**
* Clears the value of a request header field. The change will apply to subsequent connections
* established by the source.
*
* @param name The name of the header field.
*/
void clearRequestProperty(String name);
/**
* Clears all request header fields that were set by {@link #setRequestProperty(String, String)}.
*/
void clearAllRequestProperties();
/**
* Returns the headers provided in the response, or {@code null} if response headers are
* unavailable.
*/
Map<String, List<String>> getResponseHeaders();
}
|
profosure/porogram
|
TMessagesProj/src/main/java/com/porogram/profosure1/messenger/exoplayer2/upstream/HttpDataSource.java
|
Java
|
gpl-2.0
| 5,274
|
/*
* Copyright (C) 2011 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 android.renderscript.cts;
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.content.res.Resources;
import android.renderscript.*;
import com.android.cts.stub.R;
// Renderscript activity
public class RenderscriptGLStubActivity extends Activity {
class StubActivityRS {
private Resources mRes;
private RenderScriptGL mRS;
private ScriptC mScript;
public StubActivityRS() {
}
// This provides us with the renderscript context and resources that
// allow us to create the script that does rendering
public void init(RenderScriptGL rs, Resources res) {
mRS = rs;
mRes = res;
initRS();
}
private void initRS() {
mScript = new ScriptC_stub_activity(mRS, mRes, R.raw.stub_activity);
mRS.bindRootScript(mScript);
}
}
class HelloWorldView extends RSSurfaceView {
// Renderscipt context
private RenderScriptGL mRS;
// Script that does the rendering
private StubActivityRS mRender;
public HelloWorldView(Context context) {
super(context);
ensureRenderScript();
}
private void ensureRenderScript() {
if (mRS == null) {
// Initialize renderscript with desired surface characteristics.
// In this case, just use the defaults
RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
mRS = createRenderScriptGL(sc);
// Create an instance of the script that does the rendering
mRender = new StubActivityRS();
mRender.init(mRS, getResources());
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ensureRenderScript();
}
@Override
protected void onDetachedFromWindow() {
// Handle the system event and clean up
mRender = null;
if (mRS != null) {
mRS = null;
destroyRenderScriptGL();
}
}
public void forceDestroy() {
onDetachedFromWindow();
}
}
// Custom view to use with RenderScript
private HelloWorldView mView;
private HelloWorldView mView2;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create our view and set it as the content of our Activity
mView = new HelloWorldView(this);
setContentView(mView);
}
public void recreateView() {
HelloWorldView oldView = mView;
mView = new HelloWorldView(this);
setContentView(mView);
oldView.forceDestroy();
}
public void destroyAll() {
if (mView != null) {
mView.forceDestroy();
}
if (mView2 != null) {
mView2.forceDestroy();
}
}
public void recreateMultiView() {
HelloWorldView oldView = mView;
mView = new HelloWorldView(this);
mView2 = new HelloWorldView(this);
setContentView(mView);
setContentView(mView2);
oldView.forceDestroy();
}
@Override
protected void onResume() {
// Ideally an app should implement onResume() and onPause()
// to take appropriate action when the activity loses focus
super.onResume();
mView.resume();
}
@Override
protected void onPause() {
// Ideally an app should implement onResume() and onPause()
// to take appropriate action when the activity loses focus
super.onPause();
mView.pause();
}
}
|
rex-xxx/mt6572_x201
|
cts/tests/src/android/renderscript/cts/RenderscriptGLStubActivity.java
|
Java
|
gpl-2.0
| 4,399
|
using Jarvis.Server.Data;
using Newtonsoft.Json;
using System;
namespace Jarvis.Server.Common
{
/// <summary>
/// Converter telling JSON.Net how to handle <see cref="DateTime"/> type
/// </summary>
internal class TimeSpanJsonConverter : JsonConverter
{
public override bool CanRead
{
get { return true; }
}
public override bool CanConvert(Type objectType)
{
return typeof(TimeSpan) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
TimeSpan fromJavaTime = new TimeSpan((long.Parse(reader.Value.ToString()) * TimeSpan.TicksPerMillisecond));
return fromJavaTime;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
double millis = ((TimeSpan)value).TotalMilliseconds;
writer.WriteValue(Math.Floor(millis));
}
}
}
|
npag/JarVIs-Server
|
Jarvis/Jarvis/Server/Common/TimeSpanJsonConverter.cs
|
C#
|
gpl-2.0
| 1,038
|
/*
* YABIM
* Version: 0.1
*
* Yet Another Basic Image Manipulator
*
* Authors :
* A.Chazot <alban.chazot@insa-cvl.fr>
* A.Gourd <auxidevelopper@auxisuite.fr>
*
* 2016
*/
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
achazot/YABIM
|
main.cpp
|
C++
|
gpl-2.0
| 355
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Tue Feb 14 12:32:37 EET 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.primefaces.event.map.PointSelectEvent (primefaces-3.1.1 3.1.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-02-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.primefaces.event.map.PointSelectEvent (primefaces-3.1.1 3.1.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/primefaces/event/map/PointSelectEvent.html" title="class in org.primefaces.event.map"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/primefaces/event/map//class-usePointSelectEvent.html" target="_top"><B>FRAMES</B></A>
<A HREF="PointSelectEvent.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.primefaces.event.map.PointSelectEvent</B></H2>
</CENTER>
No usage of org.primefaces.event.map.PointSelectEvent
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/primefaces/event/map/PointSelectEvent.html" title="class in org.primefaces.event.map"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/primefaces/event/map//class-usePointSelectEvent.html" target="_top"><B>FRAMES</B></A>
<A HREF="PointSelectEvent.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2012. All Rights Reserved.
</BODY>
</HTML>
|
UnaCloud/unacloudIaaS1.0
|
UnaCloudWebPortal/lib/primefaces/apidocs/org/primefaces/event/map/class-use/PointSelectEvent.html
|
HTML
|
gpl-2.0
| 6,129
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ImportExport\Test\Unit\Model\Import\Config;
class SchemaLocatorTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $_moduleReaderMock;
/**
* @var \Magento\ImportExport\Model\Import\Config\SchemaLocator
*/
protected $_model;
protected function setUp()
{
$this->_moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class);
$this->_moduleReaderMock->expects(
$this->any()
)->method(
'getModuleDir'
)->with(
'etc',
'Magento_ImportExport'
)->will(
$this->returnValue('schema_dir')
);
$this->_model = new \Magento\ImportExport\Model\Import\Config\SchemaLocator($this->_moduleReaderMock);
}
public function testGetSchema()
{
$this->assertEquals('schema_dir/import_merged.xsd', $this->_model->getSchema());
}
public function testGetPerFileSchema()
{
$this->assertEquals('schema_dir/import.xsd', $this->_model->getPerFileSchema());
}
}
|
kunj1988/Magento2
|
app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/SchemaLocatorTest.php
|
PHP
|
gpl-2.0
| 1,239
|
<!DOCTYPE html>
<meta charset='utf-8'>
<style>
body {
font: 12px Arial Narrow;
}
text {
font: 12px Arial Narrow;
}
.lighten {
opacity: 0.3;
}
/* Histogram styling*/
.histPlot .title text {
fill: #000;
font: bold 16px Arial Narrow;
}
.histPlot .axis .axisLabel {
fill: #000;
font: 14px Arial Narrow;
}
.histPlot .x.axis .tick.major text {
fill: #000;
font: 12px Arial Narrow;
}
.histPlot .barLabel.italic {
fill: #000;
font: italic 16px Arial Narrow;
}
.histPlot .barLabel.bold {
fill: #000;
font: bold 16px Arial Narrow;
}
.histPlot .bar rect {
fill: #ecb525;
shape-rendering: crispEdges;
stroke: #000;
stroke-width: 1px;
}
/* Barplot styling*/
.barPlot .title text {
fill: #000;
font: bold 16px Arial Narrow;
}
.barPlot .axis .axisLabel {
fill: #000;
font: 14px Arial Narrow;
}
.barPlot .x.axis .tick.major text {
fill: #000;
font: 12px Arial Narrow;
}
.barPlot .barLabel.italic {
fill: #000;
font: italic 16px Arial Narrow;
}
.barPlot .barLabel.bold {
fill: #000;
font: bold 16px Arial Narrow;
}
.barPlot .bar rect {
fill: #ecb525;
shape-rendering: crispEdges;
stroke: #000;
stroke-width: 1px;
}
/* Double Barplot styling*/
.doubleBarPlot .title text {
fill: #000;
font: bold 16px Arial Narrow;
}
.doubleBarPlot .axis .axisLabel {
fill: #000;
font: 12px Arial Narrow;
}
.doubleBarPlot .x.axis .tick.major text {
fill: #000;
font: 12px Arial Narrow;
}
.doubleBarPlot .barLabel {
fill: #000;
font: bold 13px Arial Narrow;
}
.doubleBarPlot .bar0 rect {
fill: #ecb525;
shape-rendering: crispEdges;
stroke: #000;
stroke-width: 1px;
}
.doubleBarPlot .bar1 rect {
fill: #5228ff;
shape-rendering: crispEdges;
stroke: #000;
stroke-width: 1px;
}
/* Stacked Barplot styling*/
.stackedBarPlot .title text {
fill: #000;
font: bold 16px Arial Narrow;
}
.stackedBarPlot .axis .axisLabel {
fill: #000;
font: 12px Arial Narrow;
}
.stackedBarPlot .x.axis .tick.major text {
fill: #000;
font: 10px Arial Narrow;
}
.stackedBarPlot .barLabel.italic {
fill: #000;
font: italic 13px Arial Narrow;
}
.stackedBarPlot .barLabel.bold {
fill: #000;
font: bold 13px Arial Narrow;
}
.stackedBarPlot .bar rect {
shape-rendering: crispEdges;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<div id='rasterPreview'></div>
<script src='libs/d3.min.js'></script>
<script src='libs/queue.v1.min.js'></script>
<script>
// A formatter for counts.
var formatCount = d3.format(',.0f'),
formatPercent = d3.format('.1%');
var margin = {top: 75, right: 30, bottom: 150, left: 30},
width = 750 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
queue()
.defer(d3.csv, 'stairsLength.csv')
.defer(d3.csv, 'minRailsWidth.csv')
.defer(d3.csv, 'maxRailsWidth.csv')
.defer(d3.csv, 'railsSlope.csv')
.defer(d3.csv, 'pandusSlope.csv')
.defer(d3.csv, 'turnstileWidth.csv')
.defer(d3.csv, 'doorWidth.csv')
//.defer(d3.csv, 'taperWidth.csv')
//.defer(d3.csv, 'doorAndTaperWidth.csv')
.defer(d3.csv, 'stairwayWidth.csv')
.defer(d3.csv, 'liftWidth.csv')
//.defer(d3.csv, 'cabinWidth.csv')
.defer(d3.csv, 'cabinDepth.csv')
.defer(d3.csv, 'minTaperTransfers.csv')
.defer(d3.csv, 'minStepsTransfers.csv')
.defer(d3.csv, 'minRailStepsTransfers.csv')
.defer(d3.csv, 'minLiftStepsTransfers.csv')
.defer(d3.csv, 'minTaperStations.csv')
.defer(d3.csv, 'minStepsStations.csv')
.defer(d3.csv, 'minRailStepsStations.csv')
.defer(d3.csv, 'minLiftStepsStations.csv')
.defer(d3.csv, 'routesByLine.csv')
.await(ready);
function ready(error, stairsLength, minRailsWidth, maxRailsWidth, railsSlope, pandusSlope, turnstileWidth, doorWidth, stairwayWidth, liftWidth, cabinDepth, minTaperTransfers, minStepsTransfers, minRailStepsTransfers, minLiftStepsTransfers, minTaperStations, minStepsStations, minRailStepsStations, minLiftStepsStations, routesByLine) {
// Calculating frequences
cabinDepthFreq = frequencyData(cabinDepth, [[1250, 1400], [1400, 1550], [2200, 2250]]);
minTaperTransfersFreq = frequencyData(minTaperTransfers, [[800, 900], [900, 1000], [1000, 1100]]);
minStepsTransfersFreq = frequencyData(minStepsTransfers, [[20, 30], [30, 40], [40, 50], [50, 60], [60, 70], [70, 80], [80, 90]]);
minRailStepsTransfersFreq = frequencyData(minRailStepsTransfers, [[20, 30], [30, 40], [40, 50], [50, 60], [60, 70], [70, 80], [80, 90]]);
minLiftStepsTransfersFreq = frequencyData(minLiftStepsTransfers, [[20, 30], [30, 40], [40, 50], [50, 60], [60, 70], [70, 80], [80, 90]]);
minStepsStationsFreq = frequencyData(minStepsStations, [[0, 10], [10, 20], [20, 30], [30, 40], [40, 50], [50, 60], [60, 70], [70, 80], [80, 90], [90, 100]]);
minRailStepsStationsFreq = frequencyData(minRailStepsStations, [[0, 10], [10, 20], [20, 30], [30, 40], [40, 50], [50, 60], [60, 70], [70, 80], [80, 90], [90, 100]]);
minLiftStepsStationsFreq = frequencyData(minLiftStepsStations, [[0, 10], [10, 20], [20, 30], [30, 40], [40, 50], [50, 60], [60, 70], [70, 80], [80, 90], [90, 100]]);
drawBarplot(cabinDepthFreq, 'График 3. Глубина кабины лифтов', 'Миллиметры (мм)');
drawBarplot(minTaperTransfersFreq, 'График 17. Самое узкое место на переходах', 'Миллиметры (мм)');
plotHist(stairsLength, [0, 3, 10, 15, 20, 25, 30, 35, 40, 45, 50], 'График 6. Длина лестниц', 'Количество ступеней (шт.)');
plotHist(minRailsWidth, [250, 300, 350, 400, 450, 500], 'График 7. Минимальная ширина рельс', 'Миллиметры (мм)');
plotHist(maxRailsWidth, [500, 600, 700, 800, 900, 1000, 1100, 1200], 'График 8. Максимальная ширина рельс', 'Миллиметры (мм)');
plotHist(railsSlope, [25, 30, 35, 40, 45, 50], 'График 9. Уклон рельс', 'Проценты (%)');
plotHist(pandusSlope, [0, 5, 8, 11, 20, 40, 50], 'График 10. Уклон пандусов', 'Проценты (%)');
plotHist(turnstileWidth, [500, 600, 750, 850, 1100], 'График 11. Ширина турникетов', 'Миллиметры (мм)');
plotHist(doorWidth, [700, 800, 900, 1000, 1100], 'График 12. Ширина дверей', 'Миллиметры (мм)');
plotHist(liftWidth, [800, 850, 900, 950, 1000], 'График 2. Ширина дверного проема лифтов', 'Миллиметры (мм)');
plotHist(minStepsTransfers, [0, 10, 20, 30, 40, 50, 60, 70, 80, 90], 'График 19. Протяженность лестниц на переходах', 'Количество ступеней (шт.)');
plotHist(minRailStepsTransfers, [0, 10, 20, 30, 40, 50, 60, 70], 'Протяженность лестниц, не дублированных рельсами и пандусами, на переходах', 'Количество ступеней (шт.)');
plotHist(minLiftStepsTransfers, [0, 10, 20, 30, 40, 50, 60, 70, 80, 90], 'Протяженность лестниц, не дублированных лифтами, на переходах', 'Количество ступеней (шт.)');
plotHist(minTaperStations, [500, 600, 700, 800, 900, 1000], 'График 16. Самое узкое место на маршрутах', 'Миллиметры (мм)');
plotHist(minStepsStations, [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120], 'График 18. Протяженность лестниц на маршрутах', 'Количество ступеней (шт.)');
drawDoubleBarplot(minStepsStationsFreq, minRailStepsStationsFreq, 'График 21. Протяженность лестниц на маршрутах c учетом рельс и пандусов', 'Количество ступеней (шт.)');
plotHist(minRailStepsStations, [0, 10, 20, 30, 40, 50, 60, 70, 80, 90], 'График 20. Протяженность лестниц, не дублированных рельсами и пандусами, на маршрутах', 'Количество ступеней (шт.)');
drawDoubleBarplot(minStepsStationsFreq, minLiftStepsStationsFreq, 'График 24. Протяженность лестниц на маршрутах c учетом лифтов', 'Количество ступеней (шт.)');
plotHist(minLiftStepsStations, [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120], 'График 23. Протяженность лестниц, не дублированных лифтами, на маршрутах', 'Количество ступеней (шт.)');
drawDoubleBarplot(minStepsTransfersFreq, minRailStepsTransfersFreq, 'График Х. Протяженность лестниц на переходах c учетом рельс и пандусов', 'Количество ступеней (шт.)');
drawDoubleBarplot(minStepsTransfersFreq, minLiftStepsTransfersFreq, 'График Х. Протяженность лестниц на переходах c учетом лифтов', 'Количество ступеней (шт.)');
drawStackedBarplot(routesByLine, ['routesInByLine', 'Null'], 'График 13. Количество маршрутов на вход');
drawStackedBarplot(routesByLine, ['routesOutByLine', 'Null'], 'График 14. Количество маршрутов на выход');
drawStackedBarplot(routesByLine, ['wheelchairFriendlyRoutesInByLine', 'wheelchairNotFriendlyRoutesInByLine'], 'График 29. Количество маршрутов на вход, доступных для инвалидов-колясочников');
drawStackedBarplot(routesByLine, ['wheelchairFriendlyRoutesOutByLine', 'wheelchairNotFriendlyRoutesOutByLine'], 'График 30. Количество маршрутов на выход, доступных для инвалидов-колясочников');
drawStackedBarplot(routesByLine, ['handicappedFriendlyRoutesInByLine', 'handicappedNotFriendlyRoutesInByLine'], 'График 32. Количество маршрутов на вход, доступных для людей с затруднениями передвижения');
drawStackedBarplot(routesByLine, ['handicappedFriendlyRoutesOutByLine', 'handicappedNotFriendlyRoutesOutByLine'], 'График 33. Количество маршрутов на выход, доступных для людей с затруднениями передвижения');
drawStackedBarplot(routesByLine, ['luggageFriendlyRoutesInByLine', 'luggageNotFriendlyRoutesInByLine'], 'График 35. Количество маршрутов на вход, доступных для людей с детскими колясками и габаритным багажом');
drawStackedBarplot(routesByLine, ['luggageFriendlyRoutesOutByLine', 'luggageNotFriendlyRoutesOutByLine'], 'График 36. Количество маршрутов на выход, доступных для людей с детскими колясками и габаритным багажом');
drawStackedBarplot(routesByLine, ['stairwayAvailableRoutesByLine', 'stairwayUnavailableRoutesByLine'], 'График 26. Количество маршрутов с эскалаторами');
drawStackedBarplot(routesByLine, ['liftAvailableRoutesByLine', 'liftUnavailableRoutesByLine'], 'График 28. Количество маршрутов с лифтами');
drawStackedBarplot(routesByLine, ['transfersByLine', 'Null'], 'График 15. Количество переходов');
drawStackedBarplot(routesByLine, ['stairwayAvailableTransfersByLine', 'stairwayUnavailableTransfersByLine'], 'График 27. Количество переходов с эскалаторами');
drawStackedBarplot(routesByLine, ['wheelchairFriendlyTransfersByLine', 'wheelchairNotFriendlyTransfersByLine'], 'График 31. Количество переходов, доступных для инвалидов-колясочников');
drawStackedBarplot(routesByLine, ['handicappedFriendlyTransfersByLine', 'handicappedNotFriendlyTransfersByLine'], 'График 34. Количество переходов, доступных для людей с затруднениями передвижения');
drawStackedBarplot(routesByLine, ['luggageFriendlyTransfersByLine', 'luggageNotFriendlyTransfersByLine'], 'График 37. Количество переходов, доступных для людей с детскими колясками и габаритным багажом');
};
function plotHist(histData, bins, title, xAxisLabel) {
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
//.bins(5)
.bins(bins)
(histData.map(function(d) {return +d.value}));
console.log(d3.min(histData, function(d) { return (+d.value); }) + ' - '
+ d3.max(histData, function(d) { return (+d.value); }));
var minThreshold = d3.min(data, function(d) { return d.x; }),
maxThreshold = d3.max(data, function(d) { return (d.x + d.dx); }),
total = d3.sum(data, function(d) { return d.y; });
var x = d3.scale.linear()
.domain([minThreshold, maxThreshold])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.tickValues(bins)
.tickPadding(10)
.orient('bottom');
var svg = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
//.attr('id', title)
.call(xmlnsFix)
.append('g')
.attr('class', 'histPlot')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var bar = svg.selectAll('.bar')
.data(data)
.enter().append('g')
.attr('class', 'bar')
.attr('transform', function(d) { return 'translate(' + x(d.x) + ',' + y(d.y) + ')'; });
bar.append('rect')
//.attr('x', 1)
.attr('width', function(d, i) { return x(data[i].dx + minThreshold); })
.attr('height', function(d) { return height - y(d.y); });
bar.append('text')
.attr('class', 'barLabel bold')
//.attr('dy', '.75em')
.attr('y', -26)
.attr('x', function(d, i) { return x(data[i].dx + minThreshold) / 2; })
.attr('text-anchor', 'middle')
.text(function(d) { return d.y > 0 ? formatCount(d.y) : ''; });
//.text(function(d) { return d.y > 0 ? formatCount(d.y) + ' (' + formatPercent(d.y/total) +') ' : ''; });
bar.append('text')
.attr('class', 'barLabel italic')
//.attr('dy', '.75em')
.attr('y', -7)
.attr('x', function(d, i) { return x(data[i].dx + minThreshold) / 2; })
.attr('text-anchor', 'middle')
.text(function(d) { return d.y > 0 ? formatPercent(d.y/total) : ''; });
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis)
.append('text')
.attr('transform', 'translate(' + width/2 + ',' + 2 * margin.bottom/3 + ')')
//.attr('dx', '0.35em')
.attr('class', 'axisLabel')
//.style('font', 'bold 10px Arial') // <- X axis title
.style('text-anchor', 'middle')
.text(xAxisLabel);
svg.append('g')
.attr('class', 'y axis')
//.call(yAxis)
.append('text')
.attr('class', 'axisLabel')
//.attr('transform', 'translate(' + 0 + ',' + (-margin.top/2) + ')')
.attr('transform', 'rotate(-90)')
.attr('x', -height/3)
.attr('y', -margin.left/2)
//.attr('dy', '1.21em')
.style('text-anchor', 'middle')
.text('Количество');
svg.append('g')
.attr('class', 'title')
.attr('transform', 'translate(' + width/2 + ',' + (-margin.top/1.5) + ')')
.append('text')
.style('text-anchor', 'middle')
.text(title);
};
function drawStackedBarplot(data, stackLevels, title) {
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(['#3770c8', '#afc6e9', '#00aa44', '#ffd42a',
'#ff7f2a', '#37c8ab', '#803200', '#abc837',
'#b3b3b3', '#ff2a2a', '#bc5fd3', '#55ddff']);
/*
Арбатско-Покровская - #3770c8
Бутовская - #afc6e9
Замоскворецкая - #00aa44
Калининско-Солнцевская - #ffd42a
Калужско-Рижская - #ff7f2a
Каховская - #37c8ab
Кольцевая - #803200
Люблинско-Дмитровская - #abc837
Серпуховско-Тимирязевская - #b3b3b3
Сокольническая - #ff2a2a
Таганско-Краснопресненская - #bc5fd3
Филевская - #55ddff
*/
var xAxis = d3.svg.axis()
.scale(x)
//.tickValues(['АПЛ', 'БЛ', 'ЗЛ', 'КСЛ', 'КРЛ', 'КХЛ', 'КЛ', 'ЛДЛ', 'СТЛ', 'СЛ', 'ТКЛ', 'ФЛ']) // <-- Remove|Comment to show xAxis ticks
.tickPadding(10)
.orient('bottom');
/*var yAxis = d3.svg.axis()
.scale(y)
.orient('left');*/
var svg = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
//.attr('id', title)
.call(xmlnsFix)
.append('g')
.attr('class', 'stackedBarPlot')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
color.domain(data.map(function(d) { return d.lineName}));
data.forEach(function(d) {
var y0 = 0;
//d.routes = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.routes = stackLevels.map(function(name) { return {name: name, line: d.lineName, y0: y0, y1: y0 += +d[name] } });
d.total = d.routes[d.routes.length - 1].y1;
});
x.domain(data.map(function(d) { return d.lineName; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr('x', -10)
.attr('y', +3)
.call(wrap, x.rangeBand())
//.attr("dx", "-.8em")
//.attr("dy", ".15em")
.attr("transform", function(d) { return "rotate(-90)";});
svg.append('g')
.attr('class', 'y axis')
//.call(yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('class', 'axisLabel')
.attr('x', -height/3)
.attr('y', -margin.left/2)
//.attr('dy', '1.21em')
.style('text-anchor', 'end')
.text('Количество');
var line = svg.selectAll('.line')
.data(data)
.enter().append('g')
.attr('class', 'line')
.attr('transform', function(d) { return 'translate(' + x(d.lineName) + ',0)'; });
var bar = line.selectAll('.bar')
.data(function(d) { return d.routes; })
.enter().append('g')
.attr('class', 'bar');
//.attr('transform', function(d) { return 'translate(' + y(d.y1) + ',0)'; });
bar.append('rect')
.attr('class', function(d) { return d.name == stackLevels[0] ? 'bright' : 'lighten'; })
.attr('width', x.rangeBand())
.attr('y', function(d) { return y(d.y1); })
.attr('height', function(d) { return y(d.y0) - y(d.y1); })
.style('fill', function(d) { return color(d.line);});
//Simple barLabel
/*var barLabel = bar.append('text')
.attr('class', 'barLabel bold')
//.attr('dy', '.75em')
.attr('y', function(d) { return y(d.y1) - 5; })
.attr('x', x.rangeBand() / 2)
.attr('text-anchor', 'middle')
.text(function(d) { return d.y1 > 0 ? formatCount(d.y1) : ''; });*/
//Stacked barLabels
var barLabel = bar.append('text')
.attr('class', 'barLabel')
//.attr('dy', '.75em')
.attr('text-anchor', 'middle')
.text(null);
barLabel.append("tspan").attr('x', x.rangeBand() / 2).attr('y', function(d) { return y(d.y1) - 20; }).text(function(d) { return d.name == stackLevels[1] ? formatCount(d.y0) + ' из ' + formatCount(d.y1) : ''; }).style('font-weight', 'bold');
barLabel.append("tspan").attr('x', x.rangeBand() / 2).attr('y', function(d) { return y(d.y1) - 5; }).text(function(d) { return d.name == stackLevels[1] ? formatPercent(d.y0/d.y1) : ''; }).style('font-style', 'italic');
svg.append('g')
.attr('class', 'title')
.attr('transform', 'translate(' + width/2 + ',' + (-margin.top/2) + ')')
.append('text')
.style('text-anchor', 'middle')
.text(title);
};
function drawBarplot(data, title) {
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
//.tickValues() // <-- Remove|Comment to show xAxis ticks
.tickPadding(10)
.orient('bottom');
/*var yAxis = d3.svg.axis()
.scale(y)
.orient('left');*/
var total = d3.sum(data, function(d) { return d.frequency; });
var svg = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
//.attr('id', title)
.call(xmlnsFix)
.append('g')
.attr('class', 'barPlot')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
x.domain(data.map(function(d) { return d.range; }));
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'y axis')
//.call(yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('class', 'axisLabel')
.attr('x', -height/3)
.attr('y', -margin.left/2)
//.attr('dy', '1.21em')
.style('text-anchor', 'end')
.text('Количество');
var bar = svg.selectAll('.bar')
.data(data)
.enter().append('g')
.attr('class', 'bar')
.attr('transform', function(d) { return 'translate(' + x(d.range) + ',0)'; });
bar.append('rect')
.attr('width', x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
bar.append('text')
.attr('class', 'barLabel bold')
//.attr('dy', '.75em')
.attr('y', function(d) { return y(d.frequency) - 7; })
.attr('x', x.rangeBand() / 2)
.attr('text-anchor', 'middle')
.text(function(d) { return d.frequency > 0 ? formatCount(d.frequency) + ' (' + formatPercent(d.frequency/total) +') ' : ''; });
svg.append('g')
.attr('class', 'title')
.attr('transform', 'translate(' + width/2 + ',' + (-margin.top/2) + ')')
.append('text')
.style('text-anchor', 'middle')
.text(title);
};
function drawDoubleBarplot(data, data2, title) {
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .3);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
//.tickValues() // <-- Remove|Comment to show xAxis ticks
.tickPadding(10)
.orient('bottom');
/*var yAxis = d3.svg.axis()
.scale(y)
.orient('left');*/
var total = d3.sum(data, function(d) { return d.frequency; });
var svg = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
//.attr('id', title)
.call(xmlnsFix)
.append('g')
.attr('class', 'doubleBarPlot')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var maxFreq = d3.max([d3.max(data, function(d) { return d.frequency; }), d3.max(data2, function(d) { return d.frequency; })]);
x.domain(data.map(function(d) { return d.range; }));
y.domain([0, maxFreq]);
//y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'y axis')
//.call(yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('class', 'axisLabel')
.attr('x', -height/3)
.attr('y', -margin.left/2)
//.attr('dy', '1.21em')
.style('text-anchor', 'end')
.text('Количество');
var bar0 = svg.selectAll('.bar0')
.data(data)
.enter().append('g')
.attr('class', 'bar0')
.attr('transform', function(d) { return 'translate(' + x(d.range) + ',0)'; });
bar0.append('rect')
.attr('width', x.rangeBand()/2)
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
bar0.append('text')
.attr('class', 'barLabel')
//.attr('dy', '.75em')
.attr('y', function(d) { return y(d.frequency) - 5; })
.attr('x', x.rangeBand() / 4)
.attr('text-anchor', 'middle')
.text(function(d) { return d.frequency > 0 ? formatCount(d.frequency) : ''; });
var bar1 = svg.selectAll('.bar1')
.data(data2)
.enter().append('g')
.attr('class', 'bar1')
.attr('transform', function(d) { return 'translate(' + x(d.range) + ',0)'; });
bar1.append('rect')
.attr('width', x.rangeBand()/2)
.attr("x", x.rangeBand()/2)
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
bar1.append('text')
.attr('class', 'barLabel')
//.attr('dy', '.75em')
.attr('y', function(d) { return y(d.frequency) - 5; })
.attr('x', 3 * x.rangeBand() / 4)
.attr('text-anchor', 'middle')
.text(function(d) { return d.frequency > 0 ? formatCount(d.frequency) : ''; });
svg.append('g')
.attr('class', 'title')
.attr('transform', 'translate(' + width/2 + ',' + (-margin.top/2) + ')')
.append('text')
.style('text-anchor', 'middle')
.text(title);
};
function frequencyData(data, ranges) {
var freqData = [];
//Nest data by values(groupping)
var nest = d3.nest()
.key(function(d) { return +d.value; }).sortKeys(d3.ascending)
.rollup(function(leaves) { return leaves.length; })
.entries(data);
//Calculate frequency for range
function frequency(nest, range) {
var result = {range: range[0] + ' - ' + range[1], frequency: 0};
nest.forEach(function(d) {
if ((Number(d.key) >= range[0]) && (Number(d.key) < range[1])) {
result.frequency += d.values;
};
});
return result;
};
//Push ranges and frequency to array
ranges.forEach(function(d) { freqData.push(frequency(nest, d)); });
//Sorting ranges
freqData.sort(function(a, b) {
return a.range.split('-')[0] - b.range.split('-')[0];
});
return freqData;
};
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split('-').reverse(),
word,
lineNumber = 0,
lineHeight = 10, // px
x = text.attr("x")
y = text.attr("y"),
text.text(null);
while (word = words.pop()) {
text.append("tspan").attr("x", x).attr("y", parseInt(y) + (lineNumber++ * lineHeight))
.text(function() { return words.length == 0 ? word : word + '-';});
}
});
}
function xmlnsFix(svg) {
// removing attributes so they aren't doubled up
svg.node().removeAttribute('xmlns');
svg.node().removeAttribute('xlink');
// These are needed for for valid SVG 1.1
if (!svg.node().hasAttributeNS(d3.ns.prefix.xmlns, 'xmlns')) {
svg.node().setAttributeNS(d3.ns.prefix.xmlns, 'xmlns', d3.ns.prefix.svg);
}
if (!svg.node().hasAttributeNS(d3.ns.prefix.xmlns, 'xmlns:xlink')) {
svg.node().setAttributeNS(d3.ns.prefix.xmlns, 'xmlns:xlink', d3.ns.prefix.xlink);
}
};
</script>
</body>
|
nextgis/metro4all
|
utils/index.html
|
HTML
|
gpl-2.0
| 28,216
|
terracotta-cache-utils
======================
Operations tool set for Terracotta via ehcache.
This package contains handy tools to help operate teams to answer typical queries like
1. How many objects are in my cache?
2. Print all keys(strings) and possible values (strings)
3. Can you check if this business key exists.
Build
The project is maven based and have few profiles for various versions of ehcache / terracotta. Review the pom.xml for the profiles and build.
To create a tar package
mvn clean install
this will create a ehcache-tools-bin.tar.gz which can be deployed on any host.
Installation
1. Unzip ehcache-tools-bin.tar.gz to any directory. (TOOLS_HOME).
2. Copy terracotta license file into TOOLS_HOME/config
3. Edit/Copy the ehcache.xml file into TOOLS_HOME/config.
Tools Provided
ehcacheping : Ping utility to check health of terracotta cluster. This is a 2 step process. Loads abut 10K entries to a cache , disconnect and then read 10K entires back and verifies.
Usage tcPing [1/2] [unique id] [number of elements]
tcPing needs to be executed in a 2 step process. The first argument 1 is to load and 2 is retrieve and avalidate
ehcachecli is a command line cli with following utilities
./ehcachecli.sh -h
Syntax: ./ehcachecli.sh [cacheKeyValuePrint|cacheKeysPrint|cacheSize] [arguments.....]
cacheKeyValuePrint - Prints the Keys and values (only string or list/string) for a given cache.
cacheKeysPrint - Prints the Keys in a cache or all caches.
cacheSize - Prints the total number of cache entries in each cache in a continous loop.
tcPing - Health Check of the cluster
|
lanimall/terracotta-cache-utils
|
README.md
|
Markdown
|
gpl-2.0
| 1,615
|
__author__ = 'george'
from baseclass import Plugin
import time
from apscheduler.scheduler import Scheduler
class AreWeDone(Plugin):
def __init__(self, skype):
super(AreWeDone, self).__init__(skype)
self.command = "arewedoneyet"
self.sched = Scheduler()
self.sched.start()
self.sched.add_cron_job(self.set_topic, hour="*", minute=2, day_of_week="monun")
def message_received(self, args, status, msg):
cur_time = time.localtime()
if cur_time.tm_mday == 31 or cur_time.tm_mday == 1:
time_left = 1 - cur_time.tm_mday % 31
hours_left = 23 - cur_time.tm_hour
mins_left = 59 - cur_time.tm_min
msg.Chat.SendMessage("%d days, %d hours and %d mins left until we are done" % (time_left, hours_left, mins_left))
print "%d days, %d hours and %d mins left until we are done" % (time_left, hours_left, mins_left)
else:
msg.Chat.SendMessage("You are now done. Please visit http://www.nav.no for more information")
def set_topic(self):
channel = "#stigrk85/$jvlomax;b43a0c90a2592b9b"
chat = self.skype.Chat(channel)
cur_time = time.localtime()
days_left = 1 - cur_time.tm_mday % 31
time_left = 24 - cur_time.tm_hour + days_left * 24
if cur_time.tm_hour >= 21 or cur_time.tm_hour < 6:
tod = "night"
else:
tod= "day"
if days_left > 0:
left = "second"
else:
left = "final"
if cur_time.tm_mday == 1:
chat.SendMessage("/topic {} of the {} day - {} hours remain".format(tod, left, time_left))
else:
chat.SendMessage("Congratulations, You have survived. Please visit http://www.nav.no for more information".format(tod, left, time_left))
|
jvlomax/Beaker-bot
|
plugins/arewedone.py
|
Python
|
gpl-2.0
| 1,837
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
*
* Copyright (C) 2007-2008 Richard Hughes <richard@hughsie.com>
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* SECTION:pk-common
* @short_description: Common utility functions for PackageKit
*
* This file contains functions that may be useful.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/utsname.h>
#include <glib.h>
#include <packagekit-glib2/pk-common.h>
#include <packagekit-glib2/pk-common-private.h>
#include <packagekit-glib2/pk-enum.h>
/**
* pk_iso8601_present:
*
* Return value: The current iso8601 date and time
*
* Since: 0.5.2
**/
gchar *
pk_iso8601_present (void)
{
GTimeVal timeval;
gchar *timespec;
/* get current time */
g_get_current_time (&timeval);
timespec = g_time_val_to_iso8601 (&timeval);
return timespec;
}
/**
* pk_iso8601_from_date:
* @date: a %GDate to convert
*
* Return value: If valid then a new ISO8601 date, else NULL
*
* Since: 0.5.2
**/
gchar *
pk_iso8601_from_date (const GDate *date)
{
gsize retval;
gchar iso_date[128];
if (date == NULL)
return NULL;
retval = g_date_strftime (iso_date, 128, "%F", date);
if (retval == 0)
return NULL;
return g_strdup (iso_date);
}
/**
* pk_iso8601_to_date: (skip)
* @iso_date: The ISO8601 date to convert
*
* Return value: If valid then a new %GDate, else NULL
*
* Since: 0.5.2
**/
GDate *
pk_iso8601_to_date (const gchar *iso_date)
{
gboolean ret = FALSE;
guint retval;
guint d = 0;
guint m = 0;
guint y = 0;
GTimeVal time_val;
GDate *date = NULL;
if (iso_date == NULL || iso_date[0] == '\0')
goto out;
/* try to parse complete ISO8601 date */
if (g_strstr_len (iso_date, -1, " ") != NULL)
ret = g_time_val_from_iso8601 (iso_date, &time_val);
if (ret && time_val.tv_sec != 0) {
g_debug ("Parsed %s %i", iso_date, ret);
date = g_date_new ();
g_date_set_time_val (date, &time_val);
goto out;
}
/* g_time_val_from_iso8601() blows goats and won't
* accept a valid ISO8601 formatted date without a
* time value - try and parse this case */
retval = sscanf (iso_date, "%u-%u-%u", &y, &m, &d);
if (retval != 3)
goto out;
/* check it's valid */
ret = g_date_valid_dmy (d, m, y);
if (!ret)
goto out;
/* create valid object */
date = g_date_new_dmy (d, m, y);
out:
return date;
}
/**
* pk_iso8601_to_datetime: (skip)
* @iso_date: The ISO8601 date to convert
*
* Return value: If valid then a new %GDateTime, else NULL
*
* Since: 0.8.11
**/
GDateTime *
pk_iso8601_to_datetime (const gchar *iso_date)
{
gboolean ret = FALSE;
guint retval;
guint d = 0;
guint m = 0;
guint y = 0;
GTimeVal time_val;
GDateTime *date = NULL;
if (iso_date == NULL || iso_date[0] == '\0')
goto out;
/* try to parse complete ISO8601 date */
if (g_strstr_len (iso_date, -1, " ") != NULL)
ret = g_time_val_from_iso8601 (iso_date, &time_val);
if (ret && time_val.tv_sec != 0) {
g_debug ("Parsed %s %i", iso_date, ret);
date = g_date_time_new_from_timeval_utc (&time_val);
goto out;
}
/* g_time_val_from_iso8601() blows goats and won't
* accept a valid ISO8601 formatted date without a
* time value - try and parse this case */
retval = sscanf (iso_date, "%u-%u-%u", &y, &m, &d);
if (retval != 3)
goto out;
/* create valid object */
date = g_date_time_new_utc (y, m, d, 0, 0, 0);
out:
return date;
}
/**
* pk_ptr_array_to_strv:
* @array: (element-type utf8): the GPtrArray of strings
*
* Form a composite string array of strings.
* The data in the GPtrArray is copied.
*
* Return value: (transfer full) (array zero-terminated=1): the string array, or %NULL if invalid
*
* Since: 0.5.2
**/
gchar **
pk_ptr_array_to_strv (GPtrArray *array)
{
gchar **value;
const gchar *value_temp;
guint i;
g_return_val_if_fail (array != NULL, NULL);
/* copy the array to a strv */
value = g_new0 (gchar *, array->len + 1);
for (i = 0; i < array->len; i++) {
value_temp = (const gchar *) g_ptr_array_index (array, i);
value[i] = g_strdup (value_temp);
}
return value;
}
/**
* pk_get_machine_type:
*
* Return value: The current machine ID, e.g. "i386"
* Note: Don't use this function if you can get this data from /etc/foo
**/
static gchar *
pk_get_distro_id_machine_type (void)
{
gint retval;
struct utsname buf;
retval = uname (&buf);
if (retval != 0)
return g_strdup ("unknown");
return g_strdup (buf.machine);
}
/**
* pk_parse_os_release:
*
* Internal helper to parse os-release
**/
static gboolean
pk_parse_os_release (gchar **id, gchar **version_id, GError **error)
{
const gchar *filename = "/etc/os-release";
gboolean ret;
g_autofree gchar *contents = NULL;
g_autoptr(GKeyFile) key_file = NULL;
g_autoptr(GString) str = NULL;
/* load data */
if (!g_file_test (filename, G_FILE_TEST_EXISTS))
filename = "/usr/lib/os-release";
if (!g_file_get_contents (filename, &contents, NULL, error))
return FALSE;
/* make a valid GKeyFile from the .ini data by prepending a header */
str = g_string_new (contents);
g_string_prepend (str, "[os-release]\n");
key_file = g_key_file_new ();
ret = g_key_file_load_from_data (key_file, str->str, -1, G_KEY_FILE_NONE, error);
if (!ret) {
return FALSE;
}
/* get keys */
if (id != NULL) {
*id = g_key_file_get_string (key_file, "os-release", "ID", error);
if (*id == NULL)
return FALSE;
}
if (version_id != NULL) {
*version_id = g_key_file_get_string (key_file, "os-release", "VERSION_ID", error);
if (*version_id == NULL)
return FALSE;
}
return TRUE;
}
/**
* pk_get_distro_id:
*
* Return value: the distro-id, typically "distro;version;arch"
**/
gchar *
pk_get_distro_id (void)
{
gboolean ret;
g_autoptr(GError) error = NULL;
g_autofree gchar *arch = NULL;
g_autofree gchar *name = NULL;
g_autofree gchar *version = NULL;
/* we don't want distro specific results in 'make check' */
if (g_getenv ("PK_SELF_TEST") != NULL)
return g_strdup ("selftest;11.91;i686");
ret = pk_parse_os_release (&name, &version, &error);
if (!ret) {
g_warning ("failed to load os-release: %s", error->message);
return NULL;
}
arch = pk_get_distro_id_machine_type ();
return g_strdup_printf ("%s;%s;%s", name, version, arch);
}
/**
* pk_get_distro_version_id:
*
* Return value: the distro version, e.g. "23", as specified by VERSION_ID in /etc/os-release
**/
gchar *
pk_get_distro_version_id (GError **error)
{
gboolean ret;
gchar *version_id = NULL;
ret = pk_parse_os_release (NULL, &version_id, error);
if (!ret)
return NULL;
return version_id;
}
|
lots0logs/PackageKit
|
lib/packagekit-glib2/pk-common.c
|
C
|
gpl-2.0
| 7,353
|
exports.config = {
seleniumServerJar: '../node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar',
// seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
chromeDriver: '../node_modules/protractor/selenium/chromedriver',
specs: [
'./spec/*_spec.js',
],
// Patterns to exclude.
exclude: [
'excludeTest_spec.js'
],
capabilities: {
'browserName': 'chrome'
// 'browserName': 'firefox'
// 'browserName': 'safari'
},
//
// multiCapabilities: [
// {
// 'browserName': 'chrome',
// },
// {
// 'browserName': 'firefox',
// },
// ],
};
|
peterhendrick/meane2e
|
test/conf.js
|
JavaScript
|
gpl-2.0
| 619
|
<?php
/**
* @package AcySMS for Joomla!
* @version 3.1.0
* @author acyba.com
* @copyright (C) 2009-2016 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class ACYSMSIntegration_virtuemart_1_integration extends ACYSMSIntegration_default_integration{
var $tableName = '#__vm_user_info';
var $componentName = 'virtuemart_1';
var $displayedName = 'VirtueMart 1';
var $primaryField = 'user_id';
var $nameField = 'first_name';
var $emailField = 'email';
var $joomidField = 'user_id';
var $editUserURL = 'index.php?page=admin.user_form&option=com_virtuemart&user_id=';
var $addUserURL = 'index.php?option=com_users&task=user.add';
var $tableAlias = 'virtuemartusers_1';
var $useJoomlaName = 0;
var $integrationType = 'ecommerceIntegration';
public function getPhoneField(){
$tableFields = array();
$oneField = new stdClass();
$oneField->name = $oneField->column = 'phone_1';
$tableFields[] = $oneField;
$oneField = new stdClass();
$oneField->name = $oneField->column = 'phone_2';
$tableFields[] = $oneField;
return $tableFields;
}
public function getQueryUsers($search, $order, $filters){
$db = JFactory::getDBO();
$config = ACYSMS::config();
$user = JFactory::getUser();
$searchFields = array('virtuemartusers_1.first_name', 'virtuemartusers_1.last_name', 'joomusers.email', 'virtuemartusers_1.user_id', 'virtuemartusers_1.'.$config->get('virtuemart_1_field'));
$result = new stdClass();
if(!empty($search)){
$searchVal = '\'%'.acysms_getEscaped($search, true).'%\'';
$filters[] = implode(" LIKE $searchVal OR ", $searchFields)." LIKE $searchVal";
}
$query = 'SELECT virtuemartusers_1.*, virtuemartusers_1.user_id as receiver_id, CONCAT_WS(" ",virtuemartusers_1.first_name,virtuemartusers_1.last_name) as receiver_name, joomusers.email as receiver_email, virtuemartusers_1.'.$config->get('virtuemart_1_field').' as receiver_phone
FROM #__vm_user_info as virtuemartusers_1
JOIN '.ACYSMS::table('users', false).' as joomusers
ON joomusers.id = virtuemartusers_1.user_id';
if(!empty($filters)){
$query .= ' WHERE ('.implode(') AND (', $filters).')';
}
if(!empty($order)){
$query .= ' ORDER BY '.$order->value.' '.$order->dir;
}
$queryCount = 'SELECT COUNT(virtuemartusers_1.user_id) FROM #__vm_user_info as virtuemartusers_1';
if(!empty($filters)){
$queryCount .= ' LEFT JOIN '.ACYSMS::table('users', false).' as joomusers ON virtuemartusers_1.user_id = joomusers.id';
$queryCount .= ' WHERE ('.implode(') AND (', $filters).')';
}
$db->setQuery($queryCount);
$result->count = $db->loadResult();
$result->query = $query;
return $result;
}
function getStatDetailsQuery($queryConditions, $search){
$db = JFactory::getDBO();
$result = new stdClass();
$config = ACYSMS::config();
$queryConditions->where[] = 'statsdetails_receiver_table = "virtuemart_1"';
$searchFields = array('CONCAT_WS(" ",virtuemartusers_1.first_name,virtuemartusers_1.last_name)', 'joomusers.email', 'virtuemartusers_1.'.$config->get('virtuemart_1_field'), 'stats.statsdetails_message_id', 'stats.statsdetails_status', 'message.message_subject');
if(!empty($search)){
$searchVal = '\'%'.acysms_getEscaped($search, true).'%\'';
$queryConditions->where[] = implode(" LIKE $searchVal OR ", $searchFields)." LIKE $searchVal";
}
$query = 'SELECT statsdetails.*, message.message_id as message_id, statsdetails.statsdetails_sentdate as message_sentdate, message.message_subject as message_subject, CONCAT_WS(" ",virtuemartusers_1.first_name,virtuemartusers_1.last_name) as receiver_name, joomusers.email as receiver_email, virtuemartusers_1.'.$config->get('virtuemart_1_field').' as receiver_phone, statsdetails.statsdetails_status as message_status, virtuemartusers_1.user_id as receiver_id
FROM '.ACYSMS::table('statsdetails').' AS statsdetails
LEFT JOIN '.ACYSMS::table('message').' AS message ON statsdetails.statsdetails_message_id = message.message_id
LEFT JOIN #__vm_user_info as virtuemartusers_1 ON statsdetails.statsdetails_receiver_id = virtuemartusers_1.user_id
LEFT JOIN '.ACYSMS::table('users', false).' AS joomusers ON virtuemartusers_1.user_id = joomusers.id ';
$query .= ' WHERE ('.implode(') AND (', $queryConditions->where).')';
if(!empty($queryConditions->order)){
$query .= ' ORDER BY '.$queryConditions->order->value.' '.$queryConditions->order->dir;
}
$query .= ' LIMIT '.$queryConditions->offset;
if(!empty($queryConditions->limit)) $query .= ', '.$queryConditions->limit;
$queryCount = 'SELECT COUNT(statsdetails.statsdetails_message_id)
FROM '.ACYSMS::table('statsdetails').' AS statsdetails
LEFT JOIN '.ACYSMS::table('message').' AS message ON statsdetails.statsdetails_message_id = message.message_id
LEFT JOIN #__vm_user_info as virtuemartusers_1 ON statsdetails.statsdetails_receiver_id = virtuemartusers_1.user_id
LEFT JOIN '.ACYSMS::table('users', false).' AS joomusers ON virtuemartusers_1.user_id = joomusers.id ';
$queryCount .= ' WHERE ('.implode(') AND (', $queryConditions->where).')';
$db->setQuery($queryCount);
$result->count = $db->loadResult();
$result->query = $query;
return $result;
}
function initQuery(&$acyquery){
$config = ACYSMS::config();
$acyquery->from = '#__users as joomusers ';
$acyquery->join['virtuemartusers_1'] = 'JOIN #__vm_user_info as virtuemartusers_1 ON joomusers.id = virtuemartusers_1.user_id ';
$acyquery->where[] = 'joomusers.block=0 AND CHAR_LENGTH(virtuemartusers_1.`'.$config->get('virtuemart_1_field').'`) > 3';
return $acyquery;
}
function isPresent(){
$file = ACYSMS_ROOT.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'version.php';
if(!file_exists($file)) return false;
include_once($file);
$vmversion = new vmVersion();
if(empty($vmversion->RELEASE)) return false;
return true;
}
function addUsersInformations(&$queueMessage){
$config = ACYSMS::config();
$db = JFactory::getDBO();
$userId = array();
$juserid = array();
$virtueMartUser = array();
foreach($queueMessage as $messageID => $oneMessage){
if(empty($oneMessage->queue_receiver_id)) continue;
$userId[$oneMessage->queue_receiver_id] = intval($oneMessage->queue_receiver_id);
}
JArrayHelper::toInteger($userId);
$query = 'SELECT *, `'.$config->get('virtuemart_1_field').'` as receiver_phone, CONCAT_WS(" ",first_name, last_name) as receiver_name FROM #__vm_user_info WHERE user_id IN ("'.implode('","', $userId).'")';
$db->setQuery($query);
$virtueMartUser = $db->loadObjectList('user_id');
if(empty($virtueMartUser)) return false;
JArrayHelper::toInteger($userId);
$query = 'SELECT joomusers.* FROM #__vm_user_info as virtuemartusers_1
JOIN #__users as joomusers
ON joomusers.id = virtuemartusers_1.user_id
WHERE virtuemartusers_1.user_id IN ('.implode(',', $userId).')';
$db->setQuery($query);
$joomuserArray = $db->loadObjectList('id');
foreach($queueMessage as $messageID => $oneMessage){
if(empty($oneMessage->queue_receiver_id)) continue;
if(empty($virtueMartUser[$oneMessage->queue_receiver_id])) continue;
$queueMessage[$messageID]->virtueMart_1 = $virtueMartUser[$oneMessage->queue_receiver_id];
$queueMessage[$messageID]->receiver_phone = $queueMessage[$messageID]->virtueMart_1->receiver_phone;
$queueMessage[$messageID]->receiver_name = $queueMessage[$messageID]->virtueMart_1->receiver_name;
$queueMessage[$messageID]->receiver_id = $oneMessage->queue_receiver_id;
if(!empty($queueMessage[$messageID]->virtueMart_1->user_id) && !empty($joomuserArray[$queueMessage[$messageID]->virtueMart_1->user_id])){
$queueMessage[$messageID]->joomla = $joomuserArray[$queueMessage[$messageID]->virtueMart_1->user_id];
$queueMessage[$messageID]->receiver_email = $queueMessage[$messageID]->joomla->email;
}
}
}
public function getReceiversByName($name, $isFront, $receiverId){
if(empty($name)) return;
$db = JFactory::getDBO();
$query = 'SELECT CONCAT_WS(" ",virtuemartusers_1.first_name, virtuemartusers_1.last_name) AS name, joomusers.'.$this->primaryField.' AS receiverId
FROM #__vm_user_info AS virtuemartusers_1
JOIN '.ACYSMS::table('users', false).' as joomusers
ON joomusers.id = virtuemartusers_1.user_id
WHERE virtuemartusers_1.first_name LIKE '.$db->Quote('%'.$name.'%').'
OR virtuemartusers_1.last_name LIKE '.$db->Quote('%'.$name.'%').'
LIMIT 10';
$db->setQuery($query);
return $db->loadObjectList();
}
}
|
sajithaliyanage/CMS
|
administrator/components/com_acysms/integration/virtuemart_1/integration.php
|
PHP
|
gpl-2.0
| 8,621
|
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// The exception thrown when an error occurs during JSON serialization or deserialization.
/// </summary>
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
[Serializable]
#endif
public class JsonException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class.
/// </summary>
public JsonException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public JsonException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonException(string message, Exception innerException)
: base(message, innerException)
{
}
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="ArgumentNullException">The <paramref name="info"/> parameter is <c>null</c>.</exception>
/// <exception cref="SerializationException">The class name is <c>null</c> or <see cref="Exception.HResult"/> is zero (0).</exception>
public JsonException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
return new JsonException(message);
}
}
}
|
wfpcoslv/maps-examples
|
desktop_clients/Visual Studio/Crear beneficiarios/Json100r3/Source/Src/Newtonsoft.Json/JsonException.cs
|
C#
|
gpl-2.0
| 3,981
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.