package view.scene.raid
{
    import flash.display.*;
    import flash.events.*;
    import flash.geom.*;
    import flash.filters.*;
    import flash.utils.*;
    import mx.core.*;
    import mx.controls.Label;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.text.TextFormatAlign;

    import org.libspark.thread.Thread;
    import org.libspark.thread.utils.ParallelExecutor;
    import org.libspark.thread.threads.between.BeTweenAS3Thread;

    import model.*;
    import model.events.*;

    import view.image.raid.*;
    import view.*;
    import view.scene.BaseScene;
    import view.utils.*;

    import controller.RaidCtrl;
    import controller.RaidChatCtrl;
    import controller.RaidDataCtrl;

    /**
     * 渦情報表示クラス
     *
     */
    public class RaidInfo extends BaseScene
    {
        CONFIG::LOCALE_JP
        private static const _TRANS_AREA_CLOSE_AT:String = "残り[__CLOSE_TIME__]";
        CONFIG::LOCALE_EN
        private static const _TRANS_AREA_CLOSE_AT:String = "[__CLOSE_TIME__]";
        CONFIG::LOCALE_TCN
        private static const _TRANS_AREA_CLOSE_AT:String = "剩餘[__CLOSE_TIME__]";
        CONFIG::LOCALE_SCN
        private static const _TRANS_AREA_CLOSE_AT:String = "剩余[__CLOSE_TIME__]";
        CONFIG::LOCALE_KR
        private static const _TRANS_AREA_CLOSE_AT:String = "";
        CONFIG::LOCALE_FR
        private static const _TRANS_AREA_CLOSE_AT:String = "Reste [__CLOSE_TIME__]";
        CONFIG::LOCALE_ID
        private static const _TRANS_AREA_CLOSE_AT:String = "";
        CONFIG::LOCALE_TH
        private static const _TRANS_AREA_CLOSE_AT:String = "เวลาที่เหลือ[__CLOSE_TIME__]";

        CONFIG::LOCALE_JP
        private static const _TRANS_BTL_CNT_MSG:String = "戦闘行動中の渦の個数と最大個数です";
        CONFIG::LOCALE_EN
        private static const _TRANS_BTL_CNT_MSG:String = "The number of active and maximum possible vortex battles.";
        CONFIG::LOCALE_TCN
        private static const _TRANS_BTL_CNT_MSG:String = "戰鬥進行中的渦的數量以及最大數量";
        CONFIG::LOCALE_SCN
        private static const _TRANS_BTL_CNT_MSG:String = "战斗中的漩涡个数及个数上限值。";
        CONFIG::LOCALE_KR
        private static const _TRANS_BTL_CNT_MSG:String = "";
        CONFIG::LOCALE_FR
        private static const _TRANS_BTL_CNT_MSG:String = "Voici le nombre de Vortex et le nombre maximal de Vortex dans lesquels des combats ont lieu.";
        CONFIG::LOCALE_ID
        private static const _TRANS_BTL_CNT_MSG:String = "";
        CONFIG::LOCALE_TH
        private static const _TRANS_BTL_CNT_MSG:String = "จำนวนน้ำวนในขณะต่อสู้กับจำนวนสูงสุด"; // 戦闘行動中の渦の個数と最大個数です

        CONFIG::LOCALE_JP
        private static const _TRANS_MAP_NAME_HEX:String      = "隠者の道";
        CONFIG::LOCALE_JP
        private static const _TRANS_MAP_NAME_SHADOW:String   = "影斬り森";
        CONFIG::LOCALE_JP
        private static const _TRANS_MAP_NAME_MOON:String     = "幻影城";
        CONFIG::LOCALE_JP
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "翼竜の宝物庫";
        CONFIG::LOCALE_JP
        private static const _TRANS_MAP_NAME_ANGEL:String    = "聖女の玉座";

        CONFIG::LOCALE_EN
        private static const _TRANS_MAP_NAME_HEX:String      = "Hermit Road";
        CONFIG::LOCALE_EN
        private static const _TRANS_MAP_NAME_SHADOW:String   = "Shadowthief Forest";
        CONFIG::LOCALE_EN
        private static const _TRANS_MAP_NAME_MOON:String     = "The Phantom Castle";
        CONFIG::LOCALE_EN
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "The Wyvern's Treasure";
        CONFIG::LOCALE_EN
        private static const _TRANS_MAP_NAME_ANGEL:String    = "Throne of the saint";

        CONFIG::LOCALE_TCN
        private static const _TRANS_MAP_NAME_HEX:String      = "隱者之道";
        CONFIG::LOCALE_TCN
        private static const _TRANS_MAP_NAME_SHADOW:String   = "斬影森林";
        CONFIG::LOCALE_TCN
        private static const _TRANS_MAP_NAME_MOON:String     = "幻影城";
        CONFIG::LOCALE_TCN
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "翼龍的藏寶庫";
        CONFIG::LOCALE_TCN
        private static const _TRANS_MAP_NAME_ANGEL:String    = "聖女的玉座";

        CONFIG::LOCALE_SCN
        private static const _TRANS_MAP_NAME_HEX:String      = "隐士之道";
        CONFIG::LOCALE_SCN
        private static const _TRANS_MAP_NAME_SHADOW:String   = "斩影之森";
        CONFIG::LOCALE_SCN
        private static const _TRANS_MAP_NAME_MOON:String     = "幻影城";
        CONFIG::LOCALE_SCN
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "翼龙的宝物库";
        CONFIG::LOCALE_SCN
        private static const _TRANS_MAP_NAME_ANGEL:String    = "圣女的宝座";

        CONFIG::LOCALE_KR
        private static const _TRANS_MAP_NAME_HEX:String      = "";
        CONFIG::LOCALE_KR
        private static const _TRANS_MAP_NAME_SHADOW:String   = "";
        CONFIG::LOCALE_KR
        private static const _TRANS_MAP_NAME_MOON:String     = "";
        CONFIG::LOCALE_KR
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "";
        CONFIG::LOCALE_KR
        private static const _TRANS_MAP_NAME_ANGEL:String    = "";

        CONFIG::LOCALE_FR
        private static const _TRANS_MAP_NAME_HEX:String      = "Route des Ermites";
        CONFIG::LOCALE_FR
        private static const _TRANS_MAP_NAME_SHADOW:String   = "Forêt voleuse d'ombres";
        CONFIG::LOCALE_FR
        private static const _TRANS_MAP_NAME_MOON:String     = "Château du Fantôme";
        CONFIG::LOCALE_FR
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "Coffre de Wyvern";
        CONFIG::LOCALE_FR
        private static const _TRANS_MAP_NAME_ANGEL:String    = "Trône de Rrine";

        CONFIG::LOCALE_ID
        private static const _TRANS_MAP_NAME_HEX:String      = "";
        CONFIG::LOCALE_ID
        private static const _TRANS_MAP_NAME_SHADOW:String   = "";
        CONFIG::LOCALE_ID
        private static const _TRANS_MAP_NAME_MOON:String     = "";
        CONFIG::LOCALE_ID
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "";
        CONFIG::LOCALE_ID
        private static const _TRANS_MAP_NAME_ANGEL:String    = "";

        CONFIG::LOCALE_TH
        private static const _TRANS_MAP_NAME_HEX:String      = "ถนนลักซ่อน"; // 隠者の道
        CONFIG::LOCALE_TH
        private static const _TRANS_MAP_NAME_SHADOW:String   = "ป่าตัดเงา"; // 影斬り森
        CONFIG::LOCALE_TH
        private static const _TRANS_MAP_NAME_MOON:String     = "ปราสาทเงาลวง"; // 幻影城
        CONFIG::LOCALE_TH
        private static const _TRANS_MAP_NAME_ANEMONEA:String = "คลังสมบัติมังกรบิน"; // 翼竜の宝物庫
        CONFIG::LOCALE_TH
        private static const _TRANS_MAP_NAME_ANGEL:String    = "ที่อยู่ของนักบุญหญิง"; // 聖女の玉座

        private static const _MAP_NAME_LIST:Array = [
            _TRANS_MAP_NAME_HEX,
            _TRANS_MAP_NAME_SHADOW,
            _TRANS_MAP_NAME_MOON,
            _TRANS_MAP_NAME_ANEMONEA,
            _TRANS_MAP_NAME_ANGEL
            ];
        private static const _PAGE_MAX:int = 10;

        private static const _RANKING_UPDATE_TIME:int = 1000*60*3; // 3分毎に更新

        // コントローラー
        private var _ctrl:RaidCtrl = RaidCtrl.instance;

        protected var _container:UIComponent = new UIComponent();       // 表示コンテナ

        private var _infoImage:RaidInfoImage = new RaidInfoImage();

        // 選択中の渦
        private var _selectPrf:Profound = null;

        // 渦の情報
        private var _closeAtTimeLabel:Label = new Label();
        private var _prfName:Label = new Label();
        private var _bossName:Label = new Label();
        private var _bossHp:Label = new Label();
        private var _countLabel:Label = new Label();
        private var _hpGauge:BossHPGauge = new BossHPGauge();
        private var _timeGauge:TimeLimitGauge = new TimeLimitGauge();
        private var _timeGaugeUpdate:Boolean = false;
        private var _caption:TextField = new TextField();
        private var _itemsLabel:Label = new Label();

        private var _cntMsgText:TextField = new TextField();

        private var _time:Timer;  // 消滅監視用タイマー

        // ランキング
        private var _ranking:ProfoundRankingList = new ProfoundRankingList();
        private var _rankPage:int = 0;
        private var _updateTime:Timer;  // 更新用タイマー

        private const _Y:int = 32;

        private const _LABEL_X:int           = 115;
        private const _LABEL_PRF_NAME_X:int  = 70;
        private const _LABEL_CLOSE_AT_Y:int  = 63;
        private const _LABEL_PRF_NAME_Y:int  = 8;
        private const _LABEL_BOSS_X:int      = 100;
        private const _LABEL_BOSS_NAME_Y:int = 25;
        private const _LABEL_BOSS_HP_X:int   = 95;
        private const _LABEL_BOSS_HP_Y:int   = 43;
        private const _LABEL_W:int           = 160;
        private const _LABEL_PRF_NAME_W:int  = 210;
        private const _LABEL_BOSS_W:int      = 180;
        private const _LABEL_H:int           = 20;
        private const _LABEL_ITEM_NAME_X:int = 338;
        private const _LABEL_ITEM_NAME_Y:int = _LABEL_PRF_NAME_Y;
        private const _LABEL_ITEM_NAME_W:int = 165;
        private const _URL_BTN_X:int         = 540;
        private const _URL_BTN_Y:int         = 260;

        private const _LABEL_CNT_X:int  = 435;
        private const _LABEL_CNT_Y:int  = 485;
        private const _LABEL_CNT_W:int  = 50;
        private const _LABEL_CNT_H:int  = 40;

        private const _CAPTION_X:int = 285;
        private const _CAPTION_Y:int = 43;
        private const _CAPTION_W:int = 220;
        private const _CAPTION_H:int = 50;

        /**
         * コンストラクタ
         *
         */
        public function RaidInfo()
        {
        }

        public override function init():void
        {
            y = _Y;

            _closeAtTimeLabel.x      = _LABEL_X;
            _closeAtTimeLabel.y      = _LABEL_CLOSE_AT_Y;
            _closeAtTimeLabel.width  = _LABEL_W;
            _closeAtTimeLabel.height = _LABEL_H;
            _closeAtTimeLabel.setStyle("textAlign", "right");
            _closeAtTimeLabel.setStyle("color", "0xFFFFFF");
            _closeAtTimeLabel.text = "";

            _prfName.x      = _LABEL_PRF_NAME_X;
            _prfName.y      = _LABEL_PRF_NAME_Y;
            _prfName.width  = _LABEL_PRF_NAME_W;
            _prfName.height = _LABEL_H;
            _prfName.setStyle("textAlign", "right");
            _prfName.setStyle("color", "0xFFFFFF");
            _prfName.text = "";

            _bossName.x      = _LABEL_BOSS_X;
            _bossName.y      = _LABEL_BOSS_NAME_Y;
            _bossName.width  = _LABEL_BOSS_W;
            _bossName.height = _LABEL_H;
            _bossName.setStyle("textAlign", "right");
            _bossName.setStyle("fontWeight", "bold");
            _bossName.setStyle("color", "0xFFFFFF");
            _bossName.text = "";

            _bossHp.x      = _LABEL_BOSS_HP_X;
            _bossHp.y      = _LABEL_BOSS_HP_Y;
            _bossHp.width  = _LABEL_BOSS_W;
            _bossHp.height = _LABEL_H;
            _bossHp.setStyle("textAlign", "right");
            _bossHp.setStyle("color", "0xFFFFFF");
            _bossHp.text = "";

            _countLabel.x      = _LABEL_CNT_X;
            _countLabel.y      = _LABEL_CNT_Y;
            _countLabel.width  = _LABEL_CNT_W;
            _countLabel.height = _LABEL_CNT_H;
            _countLabel.styleName = "RaidCountLabel";
            _countLabel.filters = [new GlowFilter(0x000000, 1, 1.5, 1.5, 16, 1),];
            _countLabel.text = ProfoundInventory.battleProfoundCount.toString();

            _caption.x = _CAPTION_X;
            _caption.y = _CAPTION_Y;
            _caption.width = _CAPTION_W;
            _caption.height = _CAPTION_H;
            _caption.textColor = 0xFFFFFF;
            _caption.mouseEnabled = false;
            _caption.wordWrap = true;
            _caption.multiline = true;
            _caption.alpha = 1.0;
            _caption.htmlText = "";

            _itemsLabel.x      = _LABEL_ITEM_NAME_X;
            _itemsLabel.y      = _LABEL_ITEM_NAME_Y;
            _itemsLabel.width  = _LABEL_ITEM_NAME_W;
            _itemsLabel.height = _LABEL_H;
            _itemsLabel.setStyle("textAlign", "left");
            _itemsLabel.setStyle("color", "0xFFFFFF");
            _itemsLabel.text = "";

            var txtFormat:TextFormat = new TextFormat();
            txtFormat.align = TextFormatAlign.CENTER;
            _cntMsgText.defaultTextFormat = txtFormat;
            _cntMsgText.text = _TRANS_BTL_CNT_MSG;
            _cntMsgText.height = _LABEL_H;
            _cntMsgText.width = _cntMsgText.textWidth + 10;
            _cntMsgText.x = _LABEL_CNT_X - (_cntMsgText.textWidth / 3 * 2);
            _cntMsgText.y = _LABEL_CNT_Y + _LABEL_H;
            _cntMsgText.alpha  = 1.0;
            _cntMsgText.background = true;
            _cntMsgText.backgroundColor = 0x000000;
            _cntMsgText.textColor = 0xFFFFFF;
            _cntMsgText.border = true;
            _cntMsgText.borderColor = 0x4CE1FF;
            _cntMsgText.visible = false;
            _countLabel.addEventListener(MouseEvent.MOUSE_OVER,cntLabelMouseOverHandler);
            _countLabel.addEventListener(MouseEvent.MOUSE_OUT,cntLabelMouseOutHandler);

            _hpGauge.setHP(0,0);
            _hpGauge.visible = false;

            _timeGauge.setTime(0,0);
            _timeGauge.visible = false;
            _infoImage.limit = false;

            setRankPage(_rankPage,true);
            _ranking.updateMyRank(0,true);

            _container.addChild(_infoImage);
            _container.addChild(_prfName);
            _container.addChild(_bossName);
            _container.addChild(_bossHp);
            //_container.addChild(_countLabel);
            _container.addChild(_cntMsgText);
            _container.addChild(_closeAtTimeLabel);
            _container.addChild(_hpGauge);
            _container.addChild(_timeGauge);
            _container.addChild(_caption);
            _container.addChild(_itemsLabel);
            _ranking.getShowThread(_container,20).start();
            addChild(_container);

            _infoImage.setRankButtonFunc(rankNextButtonHandler,rankBackButtonHandler);

            _time = new Timer(1000);
            _time.addEventListener(TimerEvent.TIMER, updateDuration);
            _time.start();
            _updateTime = new Timer(_RANKING_UPDATE_TIME);
            _updateTime.addEventListener(TimerEvent.TIMER, updateRankingHandler);
            _updateTime.start();

            RaidDataCtrl.instance.addEventListener(RaidDataCtrl.BOSS_HP_UPDATE,updateBossHPHandler);

            visible = false;
        }

        // 後始末処理
        public override function final():void
        {
            RaidDataCtrl.instance.removeEventListener(RaidDataCtrl.BOSS_HP_UPDATE,updateBossHPHandler);

            _updateTime.stop();
            _updateTime.removeEventListener(TimerEvent.TIMER, updateRankingHandler);

            _time.stop();
            _time.removeEventListener(TimerEvent.TIMER, updateDuration);

            _countLabel.removeEventListener(MouseEvent.MOUSE_OVER,cntLabelMouseOverHandler);
            _countLabel.removeEventListener(MouseEvent.MOUSE_OUT,cntLabelMouseOutHandler);

            _infoImage.getHideThread().start();
            _ranking.getHideThread().start();
            RemoveChild.apply(_container);
        }

        private function cntLabelMouseOverHandler(e:MouseEvent):void
        {
            _cntMsgText.visible = true;
        }

        private function cntLabelMouseOutHandler(e:MouseEvent):void
        {
            _cntMsgText.visible = false;
        }

        public function setButtonFunctions(startFunc:Function,giveFunc:Function,urlFunc:Function):void
        {
            _infoImage.setBossButtonFunc(startFunc,giveFunc,urlFunc);
        }

        public function set buttonVisibles(v:Boolean):void
        {
            _infoImage.bossDuelButtonVisible = v;
        }

        public function buttonVisibleCheck():void
        {
            if (_selectPrf) {
                if (_selectPrf.isFinished) {
                    _infoImage.bossDuelButtonVisible = false;
                } else {
                    _infoImage.bossDuelButtonVisible = true;
                }
            } else {
                _infoImage.bossDuelButtonVisible = false;
            }
        }

        public function setProfoundInfo(prf:Profound):void
        {
            log.writeLog(log.LV_FATAL, this,"setProfoundInfo", prf.id,prf.isFinished);
            var prfRank:ProfoundRanking = ProfoundRanking.getProfoundRanking(prf.id);
            _selectPrf = prf;
            if (prf.isFinished) {
                _infoImage.bossDuelButtonVisible = false;
            } else {
                _infoImage.bossDuelButtonVisible = true;
            }
            _prfName.text = prf.profoundData.name;
            _bossName.text = prf.bossName;
            _caption.htmlText = prf.profoundData.caption;
            _infoImage.limit = false;
            setBossHp();
            setTimeLimit();
            setCloseAtTime();
            setItems();
            if (prfRank) prfRank.setUpdateFunc(rankingUpdateHandler,myRankUpdateHandler);
            _rankPage = 0;
            setRankPage(_rankPage);
            if (_selectPrf) _ranking.updateMyRank(_selectPrf.id);
            visible = true;
        }

        public function clearProfoundInfo():void
        {
            log.writeLog(log.LV_FATAL, this,"clearProfound",_selectPrf);
            if (_selectPrf) {
                var prfRank:ProfoundRanking = ProfoundRanking.getProfoundRanking(_selectPrf.id);
                _infoImage.bossDuelButtonVisible = false;
                _infoImage.limit = false;
                _prfName.text = "";
                _bossName.text = "";
                _caption.htmlText = "";
                setBossHp(true);
                setTimeLimit(true);
                setItems(true);
                _hpGauge.setHP(0,0);
                _hpGauge.visible = false;
                _closeAtTimeLabel.text = "";
                if (prfRank) prfRank.setUpdateFunc(null,null);
                setRankPage(0,true);
                _ranking.updateMyRank(0,true);
                _selectPrf = null;
                visible = false;
            }
        }

        public function updateBossHp():void
        {
            setBossHp();
        }

        public function updateProfoundState(prf:Profound):void
        {
            _bossName.text = prf.bossName;
            setBossHp();
        }

        private function setCloseAtTime():void
        {
            if (_selectPrf) {
                var lastTime:String = TimeFormat.toString(_selectPrf.closeAtRestTime);
                _closeAtTimeLabel.text = _TRANS_AREA_CLOSE_AT.replace("__CLOSE_TIME__",lastTime);
            }
        }
        private function setBossHp(clear:Boolean=false):void
        {
            var nowHp:int = 0;
            var maxHp:int = 0;
            var setText:String = "";
            if (_selectPrf && !clear) {
                maxHp = _selectPrf.profoundData.coreMonsterMaxHp;
                if (maxHp > 0) nowHp = maxHp - _selectPrf.viewDamage;
                if (nowHp <= 0) nowHp = 0;
                setText = nowHp.toString() + "/" + maxHp.toString();
                _hpGauge.setHP(nowHp,maxHp);
                _hpGauge.visible = true;
                _hpGauge.getUpdateHPThread(nowHp).start();
            }
            _bossHp.text = setText;
        }
        private function setTimeLimit(clear:Boolean=false):void
        {
            if (_selectPrf && !clear) {
                var startTime:Number = _selectPrf.createdAt.getTime();
                var closeTime:Number = 0.0;
                if (_selectPrf.closeAt) closeTime = _selectPrf.closeAt.getTime();
                var nowDate:Date = new Date();
                var nowTime:Number = nowDate.getTime();
                var max:int = Math.round(closeTime-startTime);
                var now:int = Math.round(closeTime-nowTime);
                _infoImage.limit = _timeGauge.timeLimitAlert;
                _timeGauge.setTime(now,max);
                _timeGauge.visible = true;
                timeGaugeUpdate();
                _timeGaugeUpdate = true;
            } else {
                _infoImage.limit = false;
                _timeGauge.setTime(0,0);
                _timeGauge.visible = false;
                _timeGaugeUpdate = false;
            }
        }
        private function timeGaugeUpdate():void
        {
            if (_selectPrf&&_selectPrf.closeAt) {
                _infoImage.limit = _timeGauge.timeLimitAlert;
                var closeTime:Number = _selectPrf.closeAt.getTime();
                var nowDate:Date = new Date();
                var nowTime:Number = nowDate.getTime();
                var now:int = Math.round(closeTime-nowTime);
                _timeGauge.getUpdateTimeThread(now).start();
            }
        }
        private function setItems(clear:Boolean=false):void
        {
            if (_selectPrf && !clear) {
                var setTexts:Array = [];
                var setData:Array =  _selectPrf.profoundData.allItems;
                for (var  i:int  = 0; i < setData.length; i++) {
                    var t:String = "";
                    switch (setData[i]["type"])
                    {
                    case Const.TG_CHARA_CARD:
                        var cc:CharaCard = CharaCard.ID(setData[i]["id"]);
                        t = "Lv"+ cc.level + cc.name + "×"  +setData[i]["num"].toString();
                        break;
                    case Const.TG_SLOT_CARD:
                        switch (setData[i]["sctType"])
                        {
                        case Const.SCT_WEAPON:
                            t = WeaponCard.ID(setData[i]["id"]).name + "×"  +setData[i]["num"].toString();
                            break;
                        case Const.SCT_EQUIP:
                            t = EquipCard.ID(setData[i]["id"]).name + "×"  +setData[i]["num"].toString();
                            break;
                        case Const.SCT_EVENT:
                            t = EventCard.ID(setData[i]["id"]).name + "×"  +setData[i]["num"].toString();
                            break;
                        default:
                        }
                        break;
                    case Const.TG_AVATAR_ITEM:
                        t = AvatarItem.ID(setData[i]["id"]).name + "×"  +setData[i]["num"].toString();
                        break;
                    case Const.TG_AVATAR_PART:
                        t = AvatarPart.ID(setData[i]["id"]).name + "×"  +setData[i]["num"].toString();
                        break;
                    case Const.TG_GEM:
                        t = setData[i]["num"] + "Gem";
                        break;
                    case Const.TG_OWN_CARD:
                        break;
                    case Const.TG_NONE:
                    case Const.TG_BONUS_GAME:
                    default:
                    }
                    setTexts.push(t);
                }
                _itemsLabel.text = setTexts.join("、");
            } else {
                _itemsLabel.text = "";
            }
        }
        private function updateBossHPHandler(e:Event):void
        {
            log.writeLog(log.LV_DEBUG, this,"updateBossHPHandler !!!!!");
            setBossHp();
        }

        private function rankNextButtonHandler():void
        {
            // log.writeLog(log.LV_FATAL, this,"NextButtonHandler", _rankPage);
            _rankPage -= 1;
            if (_rankPage < 0) _rankPage = 0;
            setRankPage(_rankPage);
        }
        private function rankBackButtonHandler():void
        {
            // log.writeLog(log.LV_FATAL, this,"BackButtonHandler", _rankPage);
            _rankPage += 1;
            if (_rankPage >= _ranking.pageMax) _rankPage = _ranking.pageMax - 1;
            setRankPage(_rankPage);
        }
        private function rankingUpdateHandler():void
        {
            // log.writeLog(log.LV_FATAL, this,"rankingUpdateHandler");
            setRankPage(_rankPage);
        }
        private function myRankUpdateHandler():void
        {
            // log.writeLog(log.LV_FATAL, this,"myRankUpdateHandler");
            if (_selectPrf) _ranking.updateMyRank(_selectPrf.id);
        }
        private function updateRankingHandler(e:Event):void
        {
            // log.writeLog(log.LV_FATAL, this,"updateRankingHandler");
            setRankPage(_rankPage);
            if (_selectPrf) _ranking.updateMyRank(_selectPrf.id);
        }
        public function updateRanking():void
        {
            log.writeLog(log.LV_FATAL, this,"updateRanking");
            if (_selectPrf) _ranking.resetRanking(_selectPrf.id);
            setRankPage(_rankPage);
            if (_selectPrf) _ranking.updateMyRank(_selectPrf.id);
        }
        private function updateDuration(e:Event):void
        {
            setCloseAtTime();
            if (_timeGaugeUpdate) {
                timeGaugeUpdate();
            }
        }

        public function get selectProfound():Profound
        {
            return _selectPrf;
        }

        private function setRankPage(p:int,clear:Boolean=false):void
        {
            // log.writeLog(log.LV_FATAL, this,"setRankPage",clear);
            var max:int = clear ? 1 : _ranking.pageMax;
            _infoImage.setPage(p+1,max);
            if (_selectPrf) {
                _ranking.pageChange(_selectPrf.id,p,clear);
                _ranking.updateMyRank(_selectPrf.id,clear);
            }
        }

        public function updateBtlPrfCount():void
        {
            _countLabel.text = ProfoundInventory.battleProfoundCount.toString();
        }

        // 選択中の渦へのリンクを返す
        public function get selectPrfURL():String
        {
            return (_selectPrf) ? _selectPrf.prfURL : "";
        }

        public function set infoMonsId(id:int):void
        {
            //_infoImage.monsterId = id;
        }
    }
}


set Path=%PATH%;C:\laztoapk\downloads\android-sdk-windows\platform-tools
set GRADLE_HOME=C:\laztoapk\downloads\gradle-4.10\
set PATH=%PATH%;%GRADLE_HOME%\bin
gradle clean build --info


package org.telegram.ui.Components.voip;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewOutlineProvider;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;

import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.voip.Instance;
import org.telegram.messenger.voip.VideoCameraCapturer;
import org.telegram.messenger.voip.VoIPBaseService;
import org.telegram.messenger.voip.VoIPService;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.VoIPFragment;

public class VoIPPiPView implements VoIPBaseService.StateListener, NotificationCenter.NotificationCenterDelegate {

    public final static int ANIMATION_ENTER_TYPE_SCALE = 0;
    public final static int ANIMATION_ENTER_TYPE_TRANSITION = 1;
    public final static int ANIMATION_ENTER_TYPE_NONE = 3;

    private final static float SCALE_NORMAL = 0.25f;
    private final static float SCALE_EXPANDED = 0.4f;

    public FrameLayout windowView;
    public static boolean switchingToPip = false;
    FloatingView floatingView;

    private static VoIPPiPView instance;
    private static VoIPPiPView expandedInstance;
    public boolean expanded;
    private boolean expandedAnimationInProgress;
    private WindowManager windowManager;
    public WindowManager.LayoutParams windowLayoutParams;

    public final int parentWidth;
    public final int parentHeight;

    public static int topInset;
    public static int bottomInset;

    ImageView closeIcon;
    ImageView enlargeIcon;
    View topShadow;

    ValueAnimator expandAnimator;

    public final VoIPTextureView currentUserTextureView;
    public final VoIPTextureView callingUserTextureView;

    float progressToCameraMini;
    ValueAnimator animatorToCameraMini;
    ValueAnimator.AnimatorUpdateListener animatorToCameraMiniUpdater = valueAnimator -> {
        progressToCameraMini = (float) valueAnimator.getAnimatedValue();
        floatingView.invalidate();
    };

    float[] point = new float[2];
    int[] location = new int[2];

    public int xOffset;
    public int yOffset;

    boolean currentUserIsVideo;
    boolean callingUserIsVideo;

    float startX;
    float startY;
    boolean moving;
    long startTime;
    int animationIndex = -1;

    Runnable collapseRunnable = new Runnable() {
        @Override
        public void run() {
            if (instance != null) {
                instance.floatingView.expand(false);
            }
        }
    };

    AnimatorSet moveToBoundsAnimator;
    private ValueAnimator.AnimatorUpdateListener updateXlistener = new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            float x = (float) valueAnimator.getAnimatedValue();
            windowLayoutParams.x = (int) x;
            if (windowView.getParent() != null) {
                windowManager.updateViewLayout(windowView, windowLayoutParams);
            }
        }
    };

    private ValueAnimator.AnimatorUpdateListener updateYlistener = new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            float y = (float) valueAnimator.getAnimatedValue();
            windowLayoutParams.y = (int) y;
            if (windowView.getParent() != null) {
                windowManager.updateViewLayout(windowView, windowLayoutParams);
            }
        }
    };

    public static void show(Activity activity, int parentWidth, int parentHeight, int animationType) {
        if (instance != null || VideoCameraCapturer.eglBase == null) {
            return;
        }
        WindowManager.LayoutParams windowLayoutParams = createWindowLayoutParams(activity, parentWidth, parentHeight, SCALE_NORMAL);
        instance = new VoIPPiPView(activity, parentWidth, parentHeight, false);

        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        instance.windowManager = wm;
        instance.windowLayoutParams = windowLayoutParams;
        SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("voippipconfig", Context.MODE_PRIVATE);
        float x = preferences.getFloat("relativeX", 1f);
        float y = preferences.getFloat("relativeY", 0f);

        instance.setRelativePosition(x, y);
        NotificationCenter.getGlobalInstance().addObserver(instance, NotificationCenter.didEndCall);
        wm.addView(instance.windowView, windowLayoutParams);

        instance.currentUserTextureView.renderer.init(VideoCameraCapturer.eglBase.getEglBaseContext(), null);
        instance.callingUserTextureView.renderer.init(VideoCameraCapturer.eglBase.getEglBaseContext(), null);

        if (animationType == ANIMATION_ENTER_TYPE_SCALE) {
            instance.windowView.setScaleX(0.5f);
            instance.windowView.setScaleY(0.5f);
            instance.windowView.setAlpha(0f);
            instance.windowView.animate().alpha(1f).scaleY(1f).scaleX(1f).start();

            if (VoIPService.getSharedInstance() != null) {
                VoIPService.getSharedInstance().setSinks(instance.currentUserTextureView.renderer, instance.callingUserTextureView.renderer);
            }

        } else if (animationType == ANIMATION_ENTER_TYPE_TRANSITION) {
            instance.windowView.setAlpha(0f);

            if (VoIPService.getSharedInstance() != null) {
                VoIPService.getSharedInstance().setBackgroundSinks(instance.currentUserTextureView.renderer, instance.callingUserTextureView.renderer);
            }
        }
    }

    private static WindowManager.LayoutParams createWindowLayoutParams(Context context, int parentWidth, int parentHeight, float scale) {
        WindowManager.LayoutParams windowLayoutParams = new WindowManager.LayoutParams();

        int topPadding = (int) (parentHeight * SCALE_EXPANDED * 1.05f - parentHeight * SCALE_EXPANDED) / 2;
        int leftPadding = (int) (parentWidth * SCALE_EXPANDED * 1.05f - parentWidth * SCALE_EXPANDED) / 2;

        windowLayoutParams.height = (int) (parentHeight * scale + 2 * topPadding);
        windowLayoutParams.width = (int) (parentWidth * scale + 2 * leftPadding);

        windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        windowLayoutParams.format = PixelFormat.TRANSLUCENT;

        if (AndroidUtilities.checkInlinePermissions(context)) {
            if (Build.VERSION.SDK_INT >= 26) {
                windowLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                windowLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            }
        } else {
            windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            windowLayoutParams.flags |= WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
        }

        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED |
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;

        return windowLayoutParams;
    }

    public static void prepareForTransition() {
        if (expandedInstance != null) {
            instance.expandAnimator.cancel();
        }
    }

    public static void finish() {
        if (switchingToPip) {
            return;
        }
        if (expandedInstance != null) {
            expandedInstance.finishInternal();
        }
        if (instance != null) {
            instance.finishInternal();
        }
        expandedInstance = null;
        instance = null;
    }

    public static boolean isExpanding() {
        return instance.expanded;
    }

    private void setRelativePosition(float x, float y) {
        float width = AndroidUtilities.displaySize.x;
        float height = AndroidUtilities.displaySize.y;

        float leftPadding = AndroidUtilities.dp(16);
        float rightPadding = AndroidUtilities.dp(16);
        float topPadding = AndroidUtilities.dp(60);
        float bottomPadding = AndroidUtilities.dp(16);

        float widthNormal = parentWidth * SCALE_NORMAL;
        float heightNormal = parentHeight * SCALE_NORMAL;

        float floatingWidth = floatingView.getMeasuredWidth() == 0 ? widthNormal : floatingView.getMeasuredWidth();
        float floatingHeight = floatingView.getMeasuredWidth() == 0 ? heightNormal : floatingView.getMeasuredHeight();

        windowLayoutParams.x = (int) (x * (width - leftPadding - rightPadding - floatingWidth) - (xOffset - leftPadding));
        windowLayoutParams.y = (int) (y * (height - topPadding - bottomPadding - floatingHeight) - (yOffset - topPadding));

        if (windowView.getParent() != null) {
            windowManager.updateViewLayout(windowView, windowLayoutParams);
        }
    }

    public static VoIPPiPView getInstance() {
        if (expandedInstance != null) {
            return expandedInstance;
        }
        return instance;
    }

    public VoIPPiPView(@NonNull Context context, int parentWidth, int parentHeight, boolean expanded) {
        this.parentWidth = parentWidth;
        this.parentHeight = parentHeight;

        yOffset = (int) (parentHeight * SCALE_EXPANDED * 1.05f - parentHeight * SCALE_EXPANDED) / 2;
        xOffset = (int) (parentWidth * SCALE_EXPANDED * 1.05f - parentWidth * SCALE_EXPANDED) / 2;

        Drawable outerDrawable = ContextCompat.getDrawable(context, R.drawable.calls_pip_outershadow);
        windowView = new FrameLayout(context) {
            @Override
            protected void onDraw(Canvas canvas) {
                canvas.save();
                canvas.scale(floatingView.getScaleX(), floatingView.getScaleY(), floatingView.getLeft() + floatingView.getPivotX(), floatingView.getTop() + floatingView.getPivotY());
                outerDrawable.setBounds(
                        floatingView.getLeft() - AndroidUtilities.dp(2),
                        floatingView.getTop() - AndroidUtilities.dp(2),
                        floatingView.getRight() + AndroidUtilities.dp(2),
                        floatingView.getBottom() + AndroidUtilities.dp(2)
                );
                outerDrawable.draw(canvas);
                canvas.restore();
                super.onDraw(canvas);

            }
        };
        windowView.setWillNotDraw(false);
        windowView.setPadding(xOffset, yOffset, xOffset, yOffset);
        floatingView = new FloatingView(context);

        callingUserTextureView = new VoIPTextureView(context, false);
        currentUserTextureView = new VoIPTextureView(context, false);
        currentUserTextureView.renderer.setMirror(true);

        floatingView.addView(callingUserTextureView);
        floatingView.addView(currentUserTextureView);
        floatingView.setBackgroundColor(Color.GRAY);
        windowView.addView(floatingView);
        windowView.setClipChildren(false);
        windowView.setClipToPadding(false);

        if (expanded) {
            topShadow = new View(context);
            topShadow.setBackground(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ColorUtils.setAlphaComponent(Color.BLACK, (int) (255 * 0.3f)), Color.TRANSPARENT}));
            floatingView.addView(topShadow, FrameLayout.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(60));

            closeIcon = new ImageView(context);
            closeIcon.setImageResource(R.drawable.pip_close);
            closeIcon.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8));
            closeIcon.setContentDescription(LocaleController.getString("Close", R.string.Close));
            floatingView.addView(closeIcon, LayoutHelper.createFrame(40, 40, Gravity.TOP | Gravity.RIGHT, 4, 4, 4, 0));

            enlargeIcon = new ImageView(context);
            enlargeIcon.setImageResource(R.drawable.pip_enlarge);
            enlargeIcon.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8));
            enlargeIcon.setContentDescription(LocaleController.getString("Open", R.string.Open));
            floatingView.addView(enlargeIcon, LayoutHelper.createFrame(40, 40, Gravity.TOP | Gravity.LEFT, 4, 4, 4, 0));

            closeIcon.setOnClickListener((v) -> {
                VoIPService service = VoIPService.getSharedInstance();
                if (service != null) {
                    service.hangUp();
                } else {
                    finish();
                }
            });

            enlargeIcon.setOnClickListener((v) -> {
                if (context instanceof LaunchActivity && !ApplicationLoader.mainInterfacePaused) {
                    VoIPFragment.show((Activity) context);
                } else if (context instanceof LaunchActivity) {
                    Intent intent = new Intent(context, LaunchActivity.class);
                    intent.setAction("voip");
                    context.startActivity(intent);
                }
            });
        }

        VoIPService service = VoIPService.getSharedInstance();
        if (service != null) {
            service.registerStateListener(this);
        }
        updateViewState();
    }

    private void finishInternal() {
        currentUserTextureView.renderer.release();
        callingUserTextureView.renderer.release();
        VoIPService service = VoIPService.getSharedInstance();
        if (service != null) {
            service.unregisterStateListener(this);
        }
        windowView.setVisibility(View.GONE);
        if (windowView.getParent() != null) {
            floatingView.getRelativePosition(point);
            float x = Math.min(1f, Math.max(0f, point[0]));
            float y = Math.min(1f, Math.max(0f, point[1]));
            SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("voippipconfig", Context.MODE_PRIVATE);
            preferences.edit()
                    .putFloat("relativeX", x)
                    .putFloat("relativeY", y)
                    .apply();

            try {
                windowManager.removeView(windowView);
            } catch (Throwable e) {
                FileLog.e(e);
            }
        }
        NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.didEndCall);
    }

    @Override
    public void onStateChanged(int state) {
        if (state == VoIPBaseService.STATE_ENDED || state == VoIPService.STATE_BUSY || state == VoIPService.STATE_FAILED || state == VoIPService.STATE_HANGING_UP) {
            AndroidUtilities.runOnUIThread(() -> finish(), 200);
        }
        VoIPService service = VoIPService.getSharedInstance();
        if (service == null) {
            finish();
            return;
        }
        if (state == VoIPService.STATE_ESTABLISHED && !service.isVideoAvailable()) {
            finish();
            return;
        }
        updateViewState();
    }

    @Override
    public void onSignalBarsCountChanged(int count) {

    }

    @Override
    public void onAudioSettingsChanged() {

    }

    @Override
    public void onMediaStateUpdated(int audioState, int videoState) {
        updateViewState();
    }

    @Override
    public void onCameraSwitch(boolean isFrontFace) {
        updateViewState();
    }

    @Override
    public void onVideoAvailableChange(boolean isAvailable) {

    }

    @Override
    public void onScreenOnChange(boolean screenOn) {
        VoIPService service = VoIPService.getSharedInstance();
        if (service == null) {
            return;
        }
        if (!screenOn && currentUserIsVideo) {
            service.setVideoState(Instance.VIDEO_STATE_PAUSED);
        } else if (screenOn && service.getVideoState() == Instance.VIDEO_STATE_PAUSED) {
            service.setVideoState(Instance.VIDEO_STATE_ACTIVE);
        }
    }

    private void updateViewState() {
        boolean animated = floatingView.getMeasuredWidth() != 0;
        boolean callingUserWasVideo = callingUserIsVideo;

        VoIPService service = VoIPService.getSharedInstance();
        if (service != null) {
            callingUserIsVideo = service.getCurrentVideoState() == Instance.VIDEO_STATE_ACTIVE;
            currentUserIsVideo = service.getVideoState() == Instance.VIDEO_STATE_ACTIVE || service.getVideoState() == Instance.VIDEO_STATE_PAUSED;
            currentUserTextureView.renderer.setMirror(service.isFrontFaceCamera());
        }

        if (!animated) {
            progressToCameraMini = callingUserIsVideo ? 1f : 0f;
        } else {
            if (callingUserWasVideo != callingUserIsVideo) {
                if (animatorToCameraMini != null) {
                    animatorToCameraMini.cancel();
                }
                animatorToCameraMini = ValueAnimator.ofFloat(progressToCameraMini, callingUserIsVideo ? 1f : 0f);
                animatorToCameraMini.addUpdateListener(animatorToCameraMiniUpdater);
                animatorToCameraMini.setDuration(300).setInterpolator(CubicBezierInterpolator.DEFAULT);
                animatorToCameraMini.start();
            }
        }

    }

    public void onTransitionEnd() {
        if (VoIPService.getSharedInstance() != null) {
            VoIPService.getSharedInstance().swapSinks();
        }
    }

    public void onPause() {
        if (windowLayoutParams.type == WindowManager.LayoutParams.LAST_APPLICATION_WINDOW) {
            VoIPService service = VoIPService.getSharedInstance();
            if (currentUserIsVideo) {
                service.setVideoState(Instance.VIDEO_STATE_PAUSED);
            }
        }
    }

    public void onResume() {
        VoIPService service = VoIPService.getSharedInstance();
        if (service != null && service.getVideoState() == Instance.VIDEO_STATE_PAUSED) {
            service.setVideoState(Instance.VIDEO_STATE_ACTIVE);
        }
    }

    @Override
    public void didReceivedNotification(int id, int account, Object... args) {
        if (id == NotificationCenter.didEndCall) {
            finish();
        }
    }

    private class FloatingView extends FrameLayout {

        float touchSlop;

        float leftPadding;
        float rightPadding;
        float topPadding;
        float bottomPadding;

        public FloatingView(@NonNull Context context) {
            super(context);

            touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                setOutlineProvider(new ViewOutlineProvider() {
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void getOutline(View view, Outline outline) {
                        outline.setRoundRect(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight(), 1f / view.getScaleX() * AndroidUtilities.dp(4));
                    }
                });
                setClipToOutline(true);
            }
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            leftPadding = AndroidUtilities.dp(16);
            rightPadding = AndroidUtilities.dp(16);
            topPadding = AndroidUtilities.dp(60);
            bottomPadding = AndroidUtilities.dp(16);
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            currentUserTextureView.setPivotX(callingUserTextureView.getMeasuredWidth());
            currentUserTextureView.setPivotY(callingUserTextureView.getMeasuredHeight());
            currentUserTextureView.setTranslationX(-AndroidUtilities.dp(4) * (1f / getScaleX()) * progressToCameraMini);
            currentUserTextureView.setTranslationY(-AndroidUtilities.dp(4) * (1f / getScaleY()) * progressToCameraMini);
            currentUserTextureView.setRoundCorners(AndroidUtilities.dp(8) * (1f / getScaleY()) * progressToCameraMini);
            currentUserTextureView.setScaleX(0.4f + 0.6f * (1f - progressToCameraMini));
            currentUserTextureView.setScaleY(0.4f + 0.6f * (1f - progressToCameraMini));
            super.dispatchDraw(canvas);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (expandedAnimationInProgress || switchingToPip || instance == null) {
                return false;
            }
            AndroidUtilities.cancelRunOnUIThread(collapseRunnable);
            float x = event.getRawX();
            float y = event.getRawY();
            ViewParent parent = getParent();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX = x;
                    startY = y;
                    startTime = System.currentTimeMillis();
                    //  animate().scaleY(1.05f).scaleX(1.05f).setDuration(150).start();
                    if (moveToBoundsAnimator != null) {
                        moveToBoundsAnimator.cancel();
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = x - startX;
                    float dy = y - startY;
                    if (!moving && (dx * dx + dy * dy) > touchSlop * touchSlop) {
                        if (parent != null) {
                            parent.requestDisallowInterceptTouchEvent(true);
                        }
                        moving = true;
                        startX = x;
                        startY = y;
                        dx = 0;
                        dy = 0;
                    }
                    if (moving) {
                        windowLayoutParams.x += dx;
                        windowLayoutParams.y += dy;
                        startX = x;
                        startY = y;
                        if (windowView.getParent() != null) {
                            windowManager.updateViewLayout(windowView, windowLayoutParams);
                        }
                    }
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    //     animate().scaleX(1f).scaleY(1f).start();
                    if (moveToBoundsAnimator != null) {
                        moveToBoundsAnimator.cancel();
                    }
                    if (event.getAction() == MotionEvent.ACTION_UP && !moving && System.currentTimeMillis() - startTime < 150) {
                        instance.floatingView.expand(!instance.expanded);
                        moving = false;
                        return false;
                    }
                    if (parent != null) {
                        parent.requestDisallowInterceptTouchEvent(false);

                        int parentWidth = AndroidUtilities.displaySize.x;
                        int parentHeight = AndroidUtilities.displaySize.y + topInset;

                        float maxTop = topPadding;
                        float maxBottom = bottomPadding;

                        float left = windowLayoutParams.x + floatingView.getLeft();
                        float right = left + floatingView.getMeasuredWidth();
                        float top = windowLayoutParams.y + floatingView.getTop();
                        float bottom = top + floatingView.getMeasuredHeight();

                        moveToBoundsAnimator = new AnimatorSet();

                        if (left < leftPadding) {
                            ValueAnimator animator = ValueAnimator.ofFloat(windowLayoutParams.x, leftPadding - floatingView.getLeft());
                            animator.addUpdateListener(updateXlistener);
                            moveToBoundsAnimator.playTogether(animator);
                        } else if (right > parentWidth - rightPadding) {
                            ValueAnimator animator = ValueAnimator.ofFloat(windowLayoutParams.x, parentWidth - floatingView.getRight() - rightPadding);
                            animator.addUpdateListener(updateXlistener);
                            moveToBoundsAnimator.playTogether(animator);
                        }

                        if (top < maxTop) {
                            ValueAnimator animator = ValueAnimator.ofFloat(windowLayoutParams.y, maxTop - floatingView.getTop());
                            animator.addUpdateListener(updateYlistener);
                            moveToBoundsAnimator.playTogether(animator);
                        } else if (bottom > parentHeight - maxBottom) {
                            ValueAnimator animator = ValueAnimator.ofFloat(windowLayoutParams.y, parentHeight - floatingView.getMeasuredHeight() - maxBottom);
                            animator.addUpdateListener(updateYlistener);
                            moveToBoundsAnimator.playTogether(animator);
                        }
                        moveToBoundsAnimator.setDuration(150).setInterpolator(CubicBezierInterpolator.DEFAULT);
                        moveToBoundsAnimator.start();
                    }
                    moving = false;
                    if (instance.expanded) {
                        AndroidUtilities.runOnUIThread(collapseRunnable, 3000);
                    }
                    break;
            }
            return true;
        }

        private void getRelativePosition(float[] point) {
            float width = AndroidUtilities.displaySize.x;
            float height = AndroidUtilities.displaySize.y;

            point[0] = (windowLayoutParams.x + floatingView.getLeft() - leftPadding) / (width - leftPadding - rightPadding - floatingView.getMeasuredWidth());
            point[1] = (windowLayoutParams.y + floatingView.getTop() - topPadding) / (height - topPadding - bottomPadding - floatingView.getMeasuredHeight());
            point[0] = Math.min(1f, Math.max(0, point[0]));
            point[1] = Math.min(1f, Math.max(0, point[1]));
        }

        private void expand(boolean expanded) {
            AndroidUtilities.cancelRunOnUIThread(collapseRunnable);
            if (instance == null || expandedAnimationInProgress || instance.expanded == expanded) {
                return;
            }
            instance.expanded = expanded;

            float widthNormal = parentWidth * SCALE_NORMAL + 2 * xOffset;
            float heightNormal = parentHeight * SCALE_NORMAL + 2 * yOffset;

            float widthExpanded = parentWidth * SCALE_EXPANDED + 2 * xOffset;
            float heightExpanded = parentHeight * SCALE_EXPANDED + 2 * yOffset;

            expandedAnimationInProgress = true;
            if (expanded) {
                WindowManager.LayoutParams layoutParams = createWindowLayoutParams(instance.windowView.getContext(), parentWidth, parentHeight, SCALE_EXPANDED);
                VoIPPiPView pipViewExpanded = new VoIPPiPView(getContext(), parentWidth, parentHeight, true);

                getRelativePosition(point);
                float cX = point[0];
                float cY = point[1];

                layoutParams.x = (int) (windowLayoutParams.x - (widthExpanded - widthNormal) * cX);
                layoutParams.y = (int) (windowLayoutParams.y - (heightExpanded - heightNormal) * cY);

                windowManager.addView(pipViewExpanded.windowView, layoutParams);
                pipViewExpanded.windowView.setAlpha(1f);
                pipViewExpanded.windowLayoutParams = layoutParams;
                pipViewExpanded.windowManager = windowManager;
                expandedInstance = pipViewExpanded;

                swapRender(instance, expandedInstance);

                float scale = SCALE_NORMAL / SCALE_EXPANDED * floatingView.getScaleX();

                pipViewExpanded.floatingView.setPivotX(cX * parentWidth * SCALE_EXPANDED);
                pipViewExpanded.floatingView.setPivotY(cY * parentHeight * SCALE_EXPANDED);
                pipViewExpanded.floatingView.setScaleX(scale);
                pipViewExpanded.floatingView.setScaleY(scale);
                expandedInstance.topShadow.setAlpha(0f);
                expandedInstance.closeIcon.setAlpha(0f);
                expandedInstance.enlargeIcon.setAlpha(0f);

                AndroidUtilities.runOnUIThread(() -> {
                    if (expandedInstance == null) {
                        return;
                    }

                    windowView.setAlpha(0f);
                    try {
                        windowManager.removeView(windowView);
                    } catch (Throwable e) {
                        FileLog.e(e);
                    }
                    animate().cancel();

                    float animateToScale = 1f;

                    showUi(true);
                    ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1f);
                    valueAnimator.addUpdateListener(a -> {
                        float v = (float) a.getAnimatedValue();
                        float sc = scale * (1f - v) + animateToScale * v;
                        pipViewExpanded.floatingView.setScaleX(sc);
                        pipViewExpanded.floatingView.setScaleY(sc);
                        pipViewExpanded.floatingView.invalidate();
                        pipViewExpanded.windowView.invalidate();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            pipViewExpanded.floatingView.invalidateOutline();
                        }
                    });
                    valueAnimator.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            expandedAnimationInProgress = false;
                        }
                    });
                    valueAnimator.setDuration(300).setInterpolator(CubicBezierInterpolator.DEFAULT);
                    valueAnimator.start();
                    expandAnimator = valueAnimator;
                }, 64);
            } else {
                if (expandedInstance == null) {
                    return;
                }
                expandedInstance.floatingView.getRelativePosition(point);
                float cX = point[0];
                float cY = point[1];

                instance.windowLayoutParams.x = (int) (expandedInstance.windowLayoutParams.x + (widthExpanded - widthNormal) * cX);
                instance.windowLayoutParams.y = (int) (expandedInstance.windowLayoutParams.y + (heightExpanded - heightNormal) * cY);

                float scale = SCALE_NORMAL / SCALE_EXPANDED * floatingView.getScaleX();

                expandedInstance.floatingView.setPivotX(cX * parentWidth * SCALE_EXPANDED);
                expandedInstance.floatingView.setPivotY(cY * parentHeight * SCALE_EXPANDED);

                showUi(false);
                ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1f);
                valueAnimator.addUpdateListener(a -> {
                    float v = (float) a.getAnimatedValue();
                    float sc = (1f - v) + scale * v;
                    if (expandedInstance != null) {
                        expandedInstance.floatingView.setScaleX(sc);
                        expandedInstance.floatingView.setScaleY(sc);
                        expandedInstance.floatingView.invalidate();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            expandedInstance.floatingView.invalidateOutline();
                        }
                        expandedInstance.windowView.invalidate();
                    }
                });
                valueAnimator.setDuration(300).setInterpolator(CubicBezierInterpolator.DEFAULT);
                valueAnimator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (expandedInstance == null) {
                            return;
                        }
                        swapRender(expandedInstance, instance);
                        instance.windowView.setAlpha(1f);
                        windowManager.addView(instance.windowView, instance.windowLayoutParams);
                        AndroidUtilities.runOnUIThread(() -> {
                            if (instance == null || expandedInstance == null) {
                                return;
                            }
                            expandedInstance.windowView.setAlpha(0);
                            expandedInstance.finishInternal();
                            expandedAnimationInProgress = false;
                            if (expanded) {
                                AndroidUtilities.runOnUIThread(collapseRunnable, 3000);
                            }
                        }, 64);
                    }
                });
                valueAnimator.start();
                expandAnimator = valueAnimator;
            }
        }

        private void showUi(boolean show) {
            if (expandedInstance == null) {
                return;
            }
            if (show) {
                expandedInstance.topShadow.setAlpha(0f);
                expandedInstance.closeIcon.setAlpha(0f);
                expandedInstance.enlargeIcon.setAlpha(0f);
            }
            expandedInstance.topShadow.animate().alpha(show ? 1f : 0).setDuration(300).setInterpolator(CubicBezierInterpolator.DEFAULT).start();
            expandedInstance.closeIcon.animate().alpha(show ? 1f : 0).setDuration(300).setInterpolator(CubicBezierInterpolator.DEFAULT).start();
            expandedInstance.enlargeIcon.animate().alpha(show ? 1f : 0).setDuration(300).setInterpolator(CubicBezierInterpolator.DEFAULT).start();
        }

        private void swapRender(VoIPPiPView from, VoIPPiPView to) {
            to.currentUserTextureView.setStub(from.currentUserTextureView);
            to.callingUserTextureView.setStub(from.callingUserTextureView);
            from.currentUserTextureView.renderer.release();
            from.callingUserTextureView.renderer.release();
            if (VideoCameraCapturer.eglBase == null) {
                return;
            }
            to.currentUserTextureView.renderer.init(VideoCameraCapturer.eglBase.getEglBaseContext(), null);
            to.callingUserTextureView.renderer.init(VideoCameraCapturer.eglBase.getEglBaseContext(), null);

            if (VoIPService.getSharedInstance() != null) {
                VoIPService.getSharedInstance().setSinks(to.currentUserTextureView.renderer, to.callingUserTextureView.renderer);
            }
        }
    }
}


fileFormatVersion: 2
guid: 284de240e9b728e46a532ce45b7a4664
folderAsset: yes
timeCreated: 1461490137
licenseType: Pro
DefaultImporter:
  userData:
  assetBundleName:
  assetBundleVariant:


select * from person;
select * from person


/**
 * Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors
 * All rights reserved.
 *
 * This source code is licensed under the FreeBSD license found in the
 * LICENSE file in the root directory of this source tree.
 */

module.exports = exports = function (pathQmBinary) {
    var qm = require(pathQmBinary); // This loads only c++ functions of qm
    exports = qm.statistics;

    //!STARTJSDOC

    /**
	 * Calculates the z-score for a point sampled from a Gaussian distribution. The z-score indicates
	 * how many standard deviations an element is from the meam and can be calculated using
	 * the following formula: `z = (x - mu) / sigma`.
	 * @param {Number} x - The sampled point.
	 * @param {Number} mu - Mean of the distribution.
	 * @param {Number} sigma - Variance of the distribution.
     * @returns {number} The z-score of the sampled point.
     * @example
     * // import modules
     * var stat = require('qminer').statistics;
     * // calculate the z-score of the sampled point
     * var point = 10;
     * var mu    = 5;
     * var sigma = 5;
     * var zScore = stat.getZScore(point, mu, sigma); // returns 1
	 */
    exports.getZScore = function (x, mu, sigma) {
    	return (x - mu) / sigma;
    }

    //!ENDJSDOC

    return exports;
}


// Package errors provides simple error handling primitives.
//
// The traditional error handling idiom in Go is roughly akin to
//
//     if err != nil {
//             return err
//     }
//
// which applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
//
// Adding context to an error
//
// The errors.Wrap function returns a new error that adds context to the
// original error by recording a stack trace at the point Wrap is called,
// and the supplied message. For example
//
//     _, err := ioutil.ReadAll(r)
//     if err != nil {
//             return errors.Wrap(err, "read failed")
//     }
//
// If additional control is required the errors.WithStack and errors.WithMessage
// functions destructure errors.Wrap into its component operations of annotating
// an error with a stack trace and an a message, respectively.
//
// Retrieving the cause of an error
//
// Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface
//
//     type causer interface {
//             Cause() error
//     }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the original cause. For example:
//
//     switch err := errors.Cause(err).(type) {
//     case *MyError:
//             // handle specifically
//     default:
//             // unknown error
//     }
//
// causer interface is not exported by this package, but is considered a part
// of stable public API.
//
// Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported
//
//     %s    print the error. If the error has a Cause it will be
//           printed recursively
//     %v    see %s
//     %+v   extended format. Each Frame of the error's StackTrace will
//           be printed in detail.
//
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
//
//     type stackTracer interface {
//             StackTrace() errors.StackTrace
//     }
//
// Where errors.StackTrace is defined as
//
//     type StackTrace []Frame
//
// The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example:
//
//     if err, ok := err.(stackTracer); ok {
//             for _, f := range err.StackTrace() {
//                     fmt.Printf("%+s:%d", f)
//             }
//     }
//
// stackTracer interface is not exported by this package, but is considered a part
// of stable public API.
//
// See the documentation for Frame.Format for more details.
package errors

import (
	"fmt"
	"io"
)

// New returns an error with the supplied message.
// New also records the stack trace at the point it was called.
func New(message string) error {
	return &fundamental{
		msg:   message,
		stack: callers(),
	}
}

// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
func Errorf(format string, args ...interface{}) error {
	return &fundamental{
		msg:   fmt.Sprintf(format, args...),
		stack: callers(),
	}
}

// fundamental is an error that has a message and a stack, but no caller.
type fundamental struct {
	msg string
	*stack
}

func (f *fundamental) Error() string { return f.msg }

func (f *fundamental) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			io.WriteString(s, f.msg)
			f.stack.Format(s, verb)
			return
		}
		fallthrough
	case 's':
		io.WriteString(s, f.msg)
	case 'q':
		fmt.Fprintf(s, "%q", f.msg)
	}
}

// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, WithStack returns nil.
func WithStack(err error) error {
	if err == nil {
		return nil
	}
	return &withStack{
		err,
		callers(),
	}
}

type withStack struct {
	error
	*stack
}

func (w *withStack) Cause() error { return w.error }

func (w *withStack) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			fmt.Fprintf(s, "%+v", w.Cause())
			w.stack.Format(s, verb)
			return
		}
		fallthrough
	case 's':
		io.WriteString(s, w.Error())
	case 'q':
		fmt.Fprintf(s, "%q", w.Error())
	}
}

// Wrap returns an error annotating err with a stack trace
// at the point Wrap is called, and the supplied message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
	if err == nil {
		return nil
	}
	err = &withMessage{
		cause: err,
		msg:   message,
	}
	return &withStack{
		err,
		callers(),
	}
}

// Wrapf returns an error annotating err with a stack trace
// at the point Wrapf is call, and the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
	if err == nil {
		return nil
	}
	err = &withMessage{
		cause: err,
		msg:   fmt.Sprintf(format, args...),
	}
	return &withStack{
		err,
		callers(),
	}
}

// WithMessage annotates err with a new message.
// If err is nil, WithMessage returns nil.
func WithMessage(err error, message string) error {
	if err == nil {
		return nil
	}
	return &withMessage{
		cause: err,
		msg:   message,
	}
}

type withMessage struct {
	cause error
	msg   string
}

func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
func (w *withMessage) Cause() error  { return w.cause }

func (w *withMessage) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			fmt.Fprintf(s, "%+v\n", w.Cause())
			io.WriteString(s, w.msg)
			return
		}
		fallthrough
	case 's', 'q':
		io.WriteString(s, w.Error())
	}
}

// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
//
//     type causer interface {
//            Cause() error
//     }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
// investigation.
func Cause(err error) error {
	type causer interface {
		Cause() error
	}

	for err != nil {
		cause, ok := err.(causer)
		if !ok {
			break
		}
		err = cause.Cause()
	}
	return err
}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.camel.component.hipchat;

import java.net.URI;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.DefaultComponent;
import org.apache.camel.util.URISupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents the component that manages {@link HipchatEndpoint}. Hipchat is an Atlassian software for team chat.
 *
 * The hipchat component uses the OAuth2 Hipchat API to produce/consume messages. For more details about Hipchat API
 *
 * @see Hipchat API. You can get the Oauth2 auth token at @see
 *      Hipchat Auth Token. The messages produced and consumed would
 *      be from/to owner of the provided auth token.
 */
@Component("hipchat")
public class HipchatComponent extends DefaultComponent {

    private static final Logger LOG = LoggerFactory.getLogger(HipchatComponent.class);

    public HipchatComponent() {
    }

    public HipchatComponent(CamelContext context) {
        super(context);
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        HipchatEndpoint endpoint = getHipchatEndpoint(uri);
        setProperties(endpoint, parameters);
        if (endpoint.getConfiguration().getAuthToken() == null) {
            throw new HipchatException("OAuth 2 auth token must be specified");
        }
        parseUri(remaining, endpoint);
        LOG.debug("Using Hipchat API URL: {}", endpoint.getConfiguration().hipChatUrl());
        return endpoint;
    }

    private void parseUri(String remaining, HipchatEndpoint endpoint) throws Exception {
        String uri = URISupport.normalizeUri(remaining);

        URI hipChatUri = new URI(uri);
        if (hipChatUri.getHost() != null) {
            endpoint.getConfiguration().setHost(hipChatUri.getHost());
            if (hipChatUri.getPort() != -1) {
                endpoint.getConfiguration().setPort(hipChatUri.getPort());
            }
            endpoint.getConfiguration().setProtocol(hipChatUri.getScheme());
        }
    }

    protected HipchatEndpoint getHipchatEndpoint(String uri) {
        return new HipchatEndpoint(uri, this);
    }
}


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>wxSQLite3: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

wxSQLite3
    3.0.4

Main Page

Classes

Files

Class List

Class Hierarchy

Class Members

wxSQLite3FunctionContext Member List

This is the complete list of members for wxSQLite3FunctionContext, including all inherited members.

ExecAggregateFinalize(void *ctx)	wxSQLite3FunctionContext	static

ExecAggregateStep(void *ctx, int argc, void **argv)	wxSQLite3FunctionContext	static

ExecAuthorizer(void *, int type, const char *arg1, const char *arg2, const char *arg3, const char *arg4)	wxSQLite3FunctionContext	static

ExecCommitHook(void *hook)	wxSQLite3FunctionContext	static

ExecRollbackHook(void *hook)	wxSQLite3FunctionContext	static

ExecScalarFunction(void *ctx, int argc, void **argv)	wxSQLite3FunctionContext	static

ExecUpdateHook(void *hook, int type, const char *database, const char *table, wxsqlite_int64 rowid)	wxSQLite3FunctionContext	static

ExecWriteAheadLogHook(void *hook, void *dbHandle, const char *database, int numPages)	wxSQLite3FunctionContext	static

GetAggregateCount()	wxSQLite3FunctionContext

GetAggregateStruct(int len)	wxSQLite3FunctionContext

GetArgCount()	wxSQLite3FunctionContext

GetArgType(int argIndex)	wxSQLite3FunctionContext

GetBlob(int argIndex, int &len)	wxSQLite3FunctionContext

GetBlob(int argIndex, wxMemoryBuffer &buffer)	wxSQLite3FunctionContext

GetDouble(int argIndex, double nullValue=0)	wxSQLite3FunctionContext

GetInt(int argIndex, int nullValue=0)	wxSQLite3FunctionContext

GetInt64(int argIndex, wxLongLong nullValue=0)	wxSQLite3FunctionContext

GetString(int argIndex, const wxString &nullValue=wxEmptyString)	wxSQLite3FunctionContext

IsNull(int argIndex)	wxSQLite3FunctionContext

SetResult(int value)	wxSQLite3FunctionContext

SetResult(wxLongLong value)	wxSQLite3FunctionContext

SetResult(double value)	wxSQLite3FunctionContext

SetResult(const wxString &value)	wxSQLite3FunctionContext

SetResult(unsigned char *value, int len)	wxSQLite3FunctionContext

SetResult(const wxMemoryBuffer &buffer)	wxSQLite3FunctionContext

SetResultArg(int argIndex)	wxSQLite3FunctionContext

SetResultError(const wxString &errmsg)	wxSQLite3FunctionContext

SetResultNull()	wxSQLite3FunctionContext

SetResultZeroBlob(int blobSize)	wxSQLite3FunctionContext

<address class="footer">
Generated on Thu Aug 29 2013 10:05:54 for wxSQLite3 by

 1.8.5
</address>


namespace FSharpx

module Async =
    open Operators
    open FSharpx.Collections

    /// Sequentially compose two actions, passing any value produced by the second as an argument to the first.
    let inline bind f m = async.Bind(m,f)
    /// Inject a value into the async type
    let inline returnM x = returnM async x
    /// Sequentially compose two actions, passing any value produced by the first as an argument to the second.
    let inline (>>=) m f = bindM async m f
    /// Flipped >>=
    let inline (=<<) f m = bindM async m f
    /// Sequential application
    let inline (<*>) f m = applyM async async f m
    /// Sequential application
    let inline ap m f = f <*> m
    /// Flipped map
    let inline pipe m f = liftM async f m
    let inline pipe2 x y f = returnM f <*> x <*> y
    let inline pipe3 x y z f = returnM f <*> x <*> y <*> z
    /// Transforms an async value by using a specified mapping function.
    let inline map f m = pipe m f
    /// Promote a function to a monad/applicative, scanning the monadic/applicative arguments from left to right.
    let inline lift2 f x y = returnM f <*> x <*> y
    /// Infix map
    let inline (<!>) f m = pipe m f
    /// Sequence actions, discarding the value of the first argument.
    let inline ( *>) x y = pipe2 x y (fun _ z -> z)
    /// Sequence actions, discarding the value of the second argument.
    let inline ( <*) x y = pipe2 x y (fun z _ -> z)

    /// Sequentially compose two async actions, discarding any value produced by the first
    let inline (>>.) m f = bindM async m (fun _ -> f)
    /// Left-to-right Kleisli composition
    let inline (>=>) f g = fun x -> f x >>= g
    /// Right-to-left Kleisli composition
    let inline (<=<) x = flip (>=>) x

    let foldM f s =
        Seq.fold (fun acc t -> acc >>= (flip f) t) (returnM s)

    let inline sequence s =
        let inline cons a b = lift2 List.cons a b
        List.foldBack cons s (returnM [])

    let inline mapM f x = sequence (List.map f x)


Tests of the built-in exceptions' detail messages.


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/test/task_runner_test_template.h"

namespace base {

namespace test {

TaskTracker::TaskTracker() : task_runs_(0), task_runs_cv_(&lock_) {}

TaskTracker::~TaskTracker() {}

Closure TaskTracker::WrapTask(const Closure& task, int i) {
  return Bind(&TaskTracker::RunTask, this, task, i);
}

void TaskTracker::RunTask(const Closure& task, int i) {
  AutoLock lock(lock_);
  if (!task.is_null()) {
    task.Run();
  }
  ++task_run_counts_[i];
  ++task_runs_;
  task_runs_cv_.Signal();
}

std::map<int, int> TaskTracker::GetTaskRunCounts() const {
  AutoLock lock(lock_);
  return task_run_counts_;
}

void TaskTracker::WaitForCompletedTasks(int count) {
  AutoLock lock(lock_);
  while (task_runs_ < count)
    task_runs_cv_.Wait();
}

void ExpectRunsTasksOnCurrentThread(bool expected_value,
                                    TaskRunner* task_runner) {
  EXPECT_EQ(expected_value, task_runner->RunsTasksOnCurrentThread());
}

}  // namespace test

}  // namespace base