예제 #1
0
void QuantizeLSF(
 FLOAT  fLsf[],                
 FLOAT  fQLsf[]
)
{

	INT32 j;

   FLOAT fDist1;
	FLOAT	fDist2;

   FLOAT   fRes[LPCORDER];
	
	FLOAT	fLsfQTemp1[LPCORDER];
	FLOAT	fLsfQTemp2[LPCORDER];

	FLOAT fQuantBuff1[LPCORDER];
	FLOAT fQuantBuff2[LPCORDER];

	FLOAT fWeight[LPCORDER];


	 CalcWeight( fLsf, fWeight );

	MAPredictor(fLsf,  cfPredictor1, fpPredHistory, fRes);
	VQQuant(fRes,fWeight,fQuantBuff1);
	InvMAPredictor(fQuantBuff1, cfPredictor1, fpPredHistory, fLsfQTemp1);
	fDist1=GetDistortion(fLsf,fLsfQTemp1,fWeight,LPCORDER);


   MAPredictor(fLsf,  cfPredictor2, fpPredHistory, fRes);
	VQQuant(fRes,fWeight,fQuantBuff2);
	InvMAPredictor(fQuantBuff2, cfPredictor2, fpPredHistory, fLsfQTemp2);
	fDist2=GetDistortion(fLsf,fLsfQTemp2,fWeight,LPCORDER);


	if(fDist1>fDist2)
	{
			for( j = 0 ; j < LPCORDER ; j++ ) 
			{
				fQLsf[j]=fLsfQTemp2[j];
			}
			UpdateHistory(fQuantBuff2);
	}
	else
	{
			for( j = 0 ; j < LPCORDER ; j++ ) 
			{
				fQLsf[j]=fLsfQTemp1[j];
			}
			UpdateHistory(fQuantBuff1);
	}

    return;
}
예제 #2
0
	void Plugin::handleHistoryTriggered ()
	{
		const QString& id = sender ()->
				property ("Liznoo/BatteryID").toString ();
		if (!Battery2History_.contains (id) ||
				Battery2Dialog_.contains (id))
		{
			auto dia = static_cast<BatteryHistoryDialog*> (Battery2Dialog_.value (id));
			if (dia)
				dia->close ();
			return;
		}

		auto dialog = new BatteryHistoryDialog (HistSize);
		dialog->UpdateHistory (Battery2History_ [id], Battery2LastInfo_ [id]);
		dialog->setAttribute (Qt::WA_DeleteOnClose);
		Battery2Dialog_ [id] = dialog;
		connect (dialog,
				SIGNAL (destroyed (QObject*)),
				this,
				SLOT (handleBatteryDialogDestroyed ()));
		dialog->show ();
		dialog->activateWindow ();
		dialog->raise ();
	}
예제 #3
0
파일: hist.c 프로젝트: zhu-jz/rodent_code
void sHistory::OnGoodMove(sPosition *p, int lastMove, int move, int depth, int ply)
{
     if (MoveChangesMaterialBalance(p,move) ) return;
     UpdateCutoff(move); // update table used for cutoff decisions
     UpdateHistory(p, move, depth);
     UpdateKillers(move, ply);
}
예제 #4
0
  float PIDControler::Run(int Target){
    //比例项
    float prop = Target;
    //本次单次积分项
    float inte = prop * ki;
    //微分项
    float diff = MoveCtrl::DiffAngle(targetHistory[0], Target);
    diff = diff * 0.7 + diffHistory * 0.3;

    //限制单次积分步长
    inte = min(intStep, max(-intStep, inte));

    //限制积分项饱和
    inte += intSum;
    inte = min(intMaxSum, max(-intMaxSum, inte));

    //计算结果
    float result = prop * kp + inte + diff * kd;
    result = min(128.0f, max(-128.0f, result));

    //调节死区:线性映射
    //float zt = deadZone + (128.0f - deadZone)*(fabs(result)) / 128.0f;
    //result = (result < 0.0f) ? (- zt) : zt;

    //更新历史记录
    UpdateHistory(Target, diff);
    intSum = inte;

    //原本的策略是,这里返回一个历史累计值
    //没必要强行和原来的一致吧……
    return result / 128.0f * MAX_MOTOR_SPEED;
  }
예제 #5
0
int32_t PigsGUI::RunAcquisition() {
    // Runs acquisition as a loop
    if(fVerbose) std::cout<<__PRETTY_FUNCTION__ << std::endl;
    int32_t ret=0;
    int32_t ch;
    Float_t currentAcqTime  = -2.0;     // used to check if we need to reconfigure channels
    Float_t previousAcqTime = -1.0;
    fStartDAQ->SetState(kButtonDown);
    fStopDAQ->SetState(kButtonUp);
    fUseIntegration->SetState(kButtonDisabled);
    keepAcquiring = kTRUE;
    while(keepAcquiring) {                      // Acquisition loop
        currentAcqTime  = daq->GetAcquisitionLoopTime();
        if(currentAcqTime != previousAcqTime) { // Acquisition time changed, reconfigure channels
            for (ch=0; ch<4;ch++) ret += daq->ConfigureChannel(ch);
            previousAcqTime = currentAcqTime;
        }
        ret += daq->AcquisitionSingleLoop();    // Run data acquisition
        if(!ret) {
            daq->RefreshCurrHist();             // transfer data to TH1F
            for (ch=0; ch<4;ch++) {
                cCurrHCanvas->GetPad(ch+1)->cd();
                daq->getCurrHist(ch)->Draw();         // plot latest TH1F
                cCurrHCanvas->GetPad(ch+1)->Update();
                ev->spectrum[ch]        = daq->getCurrHist(ch); // save current measurement
                ev->realTime[ch]        = daq->getRealTime(ch);
                ev->deadTime[ch]        = daq->getDeadTime(ch);
                ev->goodCounts[ch]      = daq->getGoodCounts(ch);
                ev->totCounts[ch]       = daq->getTotCounts(ch);
                ev->scaleFactor[ch]     = fScaleFactor[ch];
                ev->countsPerSecond[ch] = daq->getCountsPerSecond(ch);
                if (useIntegration)                             // detector response
                    ev->detectorResponse[ch]= this->CalcResponseV2(ch);
                else
                    ev->detectorResponse[ch]= this->CalcResponseV1(ch);
            }
            ev->acqTime = daq->GetAcquisitionLoopTime();
            NormalizeFuzzyInputs();
            ev->arrowAngle = UpdateArrow();      // Updates the arrow tab, calculates the arrow angle
            gSystem->ProcessEvents();
            cCurrHCanvas->Modified(); 
            storage->getTree()->Fill();
            UpdateHistory();                     // Updates the history & average tabs

        }
        fHCurrHProgressBar->SetPosition(1);
    }
    storage->getTree()->Write();                 // This may be excessive, but we have SSD for storage :)
    fStartDAQ->SetState(kButtonUp);
    fStopDAQ->SetState(kButtonDisabled);
    fUseIntegration->SetState(kButtonUp);
    return ret;
}
예제 #6
0
/* ----------------------------- MNI Header -----------------------------------
@NAME       : CopyOthers
@INPUT      : ParentCDF  - CDF ID of the parent file
              ChildCDF   - CDF ID of the child file
              NumExclude - number of variables to exclude from the copy
              Exclude    - list of variable ID's to be excluded
              TimeStamp  - line to add to the history attribute
@OUTPUT     : 
@RETURNS    : TRUE if successfull
              FALSE if any of micopy_all_var_defs(), ncendef(), 
                 or mi_copy_all_var_values() indicate failure
@DESCRIPTION: Copies the definitions and values of all variables except 
              those in the exclusion list.  Also calls UpdateHistory() to
              update the history line.  The child file should be in 
              definition mode when CopyOthers() is called; it will be
	      ncendef()'d (put in update mode) before variable values are
	      copied, and left that way on exit.
@METHOD     : 
@GLOBALS    : 
@CALLS      : UpdateHistory
@CREATED    : fall 1993, Greg Ward
@MODIFIED   : 
---------------------------------------------------------------------------- */
Boolean CopyOthers (int ParentCDF, int ChildCDF, 
		    int NumExclude, int Exclude[],
		    char *TimeStamp)
{
#ifdef DEBUG
   printf ("CopyOthers:\n");
   printf (" copying variable definitions...\n");
#endif

   if (micopy_all_var_defs(ParentCDF, ChildCDF, NumExclude, Exclude) == MI_ERROR)
   {
      sprintf (ErrMsg, "Error copying variable definitions: %s", 
	       NCErrMsg (ncerr, errno));
      ncclose (ChildCDF);
      return (FALSE);
   }

#ifdef DEBUG
   printf (" updating history...\n");
#endif 

   UpdateHistory (ChildCDF, TimeStamp);

#ifdef DEBUG
   printf (" ncendef'ing and copying variable values...\n");
#endif
   if (ncendef (ChildCDF) == MI_ERROR)
   {
      sprintf (ErrMsg, "Error updating file (ncendef): %s",
	       NCErrMsg (ncerr, errno));
      ncclose (ChildCDF);
      return (FALSE);
   }

   if (micopy_all_var_values(ParentCDF, ChildCDF, NumExclude, Exclude) == MI_ERROR)
   {
      sprintf (ErrMsg, "Error copying variable values: %s", 
	       NCErrMsg (ncerr, errno));
      ncclose (ChildCDF);
      return (FALSE);
   }

   return (TRUE);

}     /* CopyOthers () */
예제 #7
0
	void Plugin::handleHistoryTriggered ()
	{
		const QString& id = sender ()->
				property ("Liznoo/BatteryID").toString ();
		if (!Battery2History_.contains (id) ||
				Battery2Dialog_.contains (id))
			return;

		auto dialog = new BatteryHistoryDialog (HistSize);
		dialog->UpdateHistory (Battery2History_ [id]);
		dialog->setAttribute (Qt::WA_DeleteOnClose);
		Battery2Dialog_ [id] = dialog;
		connect (dialog,
				SIGNAL (destroyed (QObject*)),
				this,
				SLOT (handleBatteryDialogDestroyed ()));
		dialog->show ();
	}
예제 #8
0
SubMainFrame::SubMainFrame( wxWindow* parent, int id, wxString title, wxPoint pos, wxSize size, int style )
:
MainFrame( parent, id, title, pos, size, style )
{

    //Set the target fro droping file onto the application
    SetDropTarget(new DnDFile());

    //Store the Recent Projects menu in the inherited class
    wxMenu *fileMenu = GetMenuBar()->GetMenu(0);
    wxMenuItem * emptyItem = fileMenu->FindItem(IDX_MENU_EMPTY, &m_menuRecentImages);

    UpdateHistory();

    int statusWidths[] = {-2,-1, -1, -1};
    GetStatusBar()->SetStatusWidths(4, statusWidths );

    Init();

}
예제 #9
0
void JamDetector::HandleTimer(void)
{
    int8_t rssi;
    bool   didExceedThreshold = true;

    VerifyOrExit(mEnabled);

    rssi = otPlatRadioGetRssi(&GetInstance());

    // If the RSSI is valid, check if it exceeds the threshold
    // and try to update the history bit map
    if (rssi != OT_RADIO_RSSI_INVALID)
    {
        didExceedThreshold = (rssi >= mRssiThreshold);
        UpdateHistory(didExceedThreshold);
    }

    // If the RSSI sample does not exceed the threshold, go back to max sample interval
    // Otherwise, divide the sample interval by half while ensuring it does not go lower
    // than minimum sample interval.

    if (!didExceedThreshold)
    {
        mSampleInterval = kMaxSampleInterval;
    }
    else
    {
        mSampleInterval /= 2;

        if (mSampleInterval < kMinSampleInterval)
        {
            mSampleInterval = kMinSampleInterval;
        }
    }

    mTimer.Start(mSampleInterval + Random::GetUint32InRange(0, kMaxRandomDelay));

exit:
    return;
}
예제 #10
0
	void Plugin::handleHistoryTriggered (const QString& id)
	{
		if (!Battery2History_.contains (id) ||
				Battery2Dialog_.contains (id))
		{
			if (auto dia = Battery2Dialog_.value (id))
				dia->close ();
			return;
		}

		auto dialog = new BatteryHistoryDialog (HistSize, UpdateMsecs / 1000.);
		dialog->UpdateHistory (Battery2History_ [id], Battery2LastInfo_ [id]);
		dialog->setAttribute (Qt::WA_DeleteOnClose);
		Battery2Dialog_ [id] = dialog;
		connect (dialog,
				SIGNAL (destroyed (QObject*)),
				this,
				SLOT (handleBatteryDialogDestroyed ()));
		dialog->show ();
		dialog->activateWindow ();
		dialog->raise ();
	}
예제 #11
0
//Add the file to the File History
void SubMainFrame::AddFileToHistory(wxString strFilename)
{
    ConfigFile *clientConfig = Globals::Instance()->GetConfig();

    std::vector<std::string> listFileHistory =  clientConfig->getArray("FileHistory");

    for(std::vector<std::string>::iterator iter = listFileHistory.begin(); iter != listFileHistory.end(); iter++)
    {
        if(strFilename == wxString((*iter).c_str(), wxConvLocal))
        {
            listFileHistory.erase(iter);
            break;
        }
    }
    listFileHistory.push_back(std::string(strFilename.mb_str()));

    while(listFileHistory.size() > clientConfig->getInteger("FileHistorySize",4))
    {
        listFileHistory.erase(listFileHistory.begin());
    }
    clientConfig->setArray("FileHistory", listFileHistory);

    UpdateHistory();
}
void RPG_MeshTrailEffectComponent::PerFrameUpdate()
{
  float fTime = Vision::GetTimer()->GetTime();
  UpdateHistory(fTime);
  UpdateMesh(fTime);
}
예제 #13
0
파일: hist.c 프로젝트: zhu-jz/rodent_code
void sHistory::UpdateSortOnly(sPosition *p, int move, int depth, int ply)
{
     if (MoveChangesMaterialBalance(p,move) ) return;
     UpdateHistory(p, move, depth);
     UpdateKillers(move, ply);
}
예제 #14
0
int Search(POS *p, int ply, int alpha, int beta, int depth, int was_null, int last_move, int last_capt_sq, int *pv) {

  int best, score, null_score, move, new_depth, new_pv[MAX_PLY];
  int fl_check, fl_prunable_node, fl_prunable_move, mv_type, reduction;
  int is_pv = (beta > alpha + 1);
  int mv_tried = 0, quiet_tried = 0, fl_futility = 0;

  int mv_played[MAX_MOVES];
  int mv_hist_score;
  int victim, last_capt;

  MOVES m[1];
  UNDO u[1];

  assert(ply > 0);

  // Quiescence search entry point

  if (depth <= 0)
    return QuiesceChecks(p, ply, alpha, beta, pv);

  // Periodically check for timeout, ponderhit or stop command

  nodes++;
  CheckTimeout();

  // Quick exit on a timeout or on a statically detected draw
  
  if (abort_search) return 0;
  if (ply) *pv = 0;
  if (IsDraw(p)) return DrawScore(p);

  // Mate distance pruning

  int checkmatingScore = MATE - ply;
  if (checkmatingScore < beta) {
    beta = checkmatingScore;
    if (alpha >= checkmatingScore)
    return alpha;
  }

  int checkmatedScore = -MATE + ply;
  if (checkmatedScore > alpha) {
    alpha = checkmatedScore;
    if (beta <= checkmatedScore)
    return beta;
  }

  // Retrieving data from transposition table. We hope for a cutoff
  // or at least for a move to improve move ordering.

  move = 0;
  if (TransRetrieve(p->hash_key, &move, &score, alpha, beta, depth, ply)) {
    
    // For move ordering purposes, a cutoff from hash is treated
    // exactly like a cutoff from search

    if (score >= beta) UpdateHistory(p, last_move, move, depth, ply);

    // In pv nodes only exact scores are returned. This is done because
    // there is much more pruning and reductions in zero-window nodes,
    // so retrieving such scores in pv nodes works like retrieving scores
    // from slightly lower depth.

    if (!is_pv || (score > alpha && score < beta))
      return score;
  }

  // Safeguard against exceeding ply limit
  
  if (ply >= MAX_PLY - 1)
    return Eval.Return(p, 1);

  // Are we in check? Knowing that is useful when it comes 
  // to pruning/reduction decisions

  fl_check = InCheck(p);

  // INTERNAL ITERATIVE DEEPENING - we try to get a hash move to improve move ordering

  if (!move && is_pv && depth >= 6 && !fl_check) {
    Search(p, ply, alpha, beta, depth - 2, 0, 0, -1, new_pv);
    if (abort_search) return 0;
    TransRetrieve(p->hash_key, &move, &score, alpha, beta, depth, ply);
  }

  // Can we prune this node?

  fl_prunable_node = !fl_check 
                   && !is_pv 
                   && alpha > -MAX_EVAL
                   && beta < MAX_EVAL;

  // Beta pruning / static null move

  if (use_beta_pruning
  && fl_prunable_node
  && depth <= 3
  && !was_null) {
    int sc = Eval.Return(p, 1) - 120 * depth; // TODO: Tune me!
    if (sc > beta) return sc;
  }

  // Null move

  if (use_nullmove
  && fl_prunable_node
  && depth > 1
  && !was_null
  && MayNull(p)
  ) {
    int eval = Eval.Return(p, 1);
    if (eval > beta) {

      new_depth = depth - ((823 + 67 * depth) / 256); // simplified Stockfish formula

      // omit null move search if normal search to the same depth wouldn't exceed beta
      // (sometimes we can check it for free via hash table)

      if (TransRetrieve(p->hash_key, &move, &null_score, alpha, beta, new_depth, ply)) {
        if (null_score < beta) goto avoid_null;
      }

      p->DoNull(u);
      if (new_depth > 0) score = -Search(p, ply + 1, -beta, -beta + 1, new_depth, 1, 0, -1, new_pv);
      else               score = -QuiesceChecks(p, ply + 1, -beta, -beta + 1, new_pv);
      p->UndoNull(u);

      // Verification search (nb. immediate null move within it is prohibited)

      if (new_depth > 6 && score >= beta && use_null_verification)
         score = Search(p, ply, alpha, beta, new_depth - 5, 1, move, -1, new_pv);

      if (abort_search ) return 0;
      if (score >= beta) return score;
    }
  } 
  
  avoid_null:

  // end of null move code

  // Razoring based on Toga II 3.0

  if (use_razoring
  && fl_prunable_node
  && !move
  && !was_null
  && !(p->Pawns(p->side) & bbRelRank[p->side][RANK_7]) // no pawns to promote in one move
  && depth <= 3) {
    int threshold = beta - razor_margin[depth];
    int eval = Eval.Return(p, 1);

    if (eval < threshold) {
      score = QuiesceChecks(p, ply, alpha, beta, pv);
      if (score < threshold) return score;
    }
  }

  // end of razoring code 

  // Init moves and variables before entering main loop
  
  best = -INF;
  InitMoves(p, m, move, Refutation(last_move), ply);
  
  // Main loop
  
  while ((move = NextMove(m, &mv_type))) {

    // Gather data about the move

    mv_hist_score = history[p->pc[Fsq(move)]][Tsq(move)];
	victim = TpOnSq(p, Tsq(move));
	if (victim != NO_TP) last_capt = Tsq(move);
	else last_capt = -1;

    // Set futility pruning flag before the first applicable move is tried

    if (mv_type == MV_NORMAL && quiet_tried == 0) {
      if (use_futility
      && fl_prunable_node
      && depth <= 6) {
        if (Eval.Return(p, 1) + fut_margin[depth] < beta) fl_futility = 1;
      }
    }

    p->DoMove(move, u);
    if (Illegal(p)) { p->UndoMove(move, u); continue; }

  // Update move statistics 
  // (needed for reduction/pruning decisions and for updating history score)

  mv_played[mv_tried] = move;
  mv_tried++;
  if (mv_type == MV_NORMAL) quiet_tried++;

  // Can we prune this move?

  fl_prunable_move = !InCheck(p)
                  && (mv_type == MV_NORMAL)
                  && (mv_hist_score < hist_limit);

  // Set new search depth

  new_depth = depth - 1;

  // Check extension (pv node or low depth)

  if (is_pv || depth < 9) {
	  new_depth += InCheck(p);
	  if (is_pv && Tsq(move) == last_capt_sq) new_depth += 1;
  }

  // Futility pruning

  if (fl_futility
  &&  fl_prunable_move
  &&  mv_tried > 1) {
    p->UndoMove(move, u); continue;
  }

  // Late move pruning

  if (use_lmp
  && fl_prunable_node
  && fl_prunable_move
  && quiet_tried > lmp_limit[depth]
  && depth <= 3
  && MoveType(move) != CASTLE ) {
    p->UndoMove(move, u); continue;
  }

  // Late move reduction

  reduction = 0;

  if (use_lmr 
  && depth >= 2
  && mv_tried > 3
  && alpha > -MAX_EVAL && beta < MAX_EVAL
  && !fl_check 
  &&  fl_prunable_move
  && lmr_size[is_pv][depth][mv_tried] > 0
  && MoveType(move) != CASTLE ) {
    
    // read reduction size from the table

    reduction = lmr_size[is_pv][depth][mv_tried];

    // increase reduction on bad history score

    if (mv_hist_score < 0
    && new_depth - reduction > 2
    && lmr_hist_adjustement)
       reduction++;

    // reduce search depth

    new_depth -= reduction;
  }

  // a place to come back if reduction looks suspect

  re_search:
   
  // PVS

  if (best == -INF)
    score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv);
  else {
    score = -Search(p, ply + 1, -alpha - 1, -alpha, new_depth, 0, move, last_capt, new_pv);
    if (!abort_search && score > alpha && score < beta)
      score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv);
  }

  // Reduced move scored above alpha - we need to re-search it

  if (reduction
  && score > alpha) {
    new_depth += reduction;
    reduction = 0;
    goto re_search;
  }

  // Undo move

  p->UndoMove(move, u);
  if (abort_search) return 0;

  // Beta cutoff

    if (score >= beta) {
      if (!fl_check) {
        UpdateHistory(p, last_move, move, depth, ply);
        for (int mv = 0; mv < mv_tried; mv++)
          DecreaseHistory(p, mv_played[mv], depth);
      }
      TransStore(p->hash_key, move, score, LOWER, depth, ply);

      return score;
    }

  // Updating score and alpha

    if (score > best) {
      best = score;
      if (score > alpha) {
        alpha = score;
        BuildPv(pv, new_pv, move);
      }
    }

  } // end of the main loop

  // Return correct checkmate/stalemate score

  if (best == -INF)
    return InCheck(p) ? -MATE + ply : DrawScore(p);

  // Save score in the transposition table

  if (*pv) {
    if (!fl_check) {
      UpdateHistory(p, last_move, *pv, depth, ply);
      for (int mv = 0; mv < mv_tried; mv++)
        DecreaseHistory(p, mv_played[mv], depth);
    }
    TransStore(p->hash_key, *pv, best, EXACT, depth, ply);
  } else
    TransStore(p->hash_key, 0, best, UPPER, depth, ply);

  return best;
}
예제 #15
0
void BrowserWindow::OpenURLNotify()
{
#if 0
	UpdateHistory();
#endif
}
예제 #16
0
void BrowserWindow::MessageReceived( BMessage* pcMsg )
{
	switch( pcMsg->what )
	{
	case ID_URL_CHANGED:
	{

		std::string cURL = m_pcURLView->Text();

		for ( uint i = 0 ; i <= cURL.size() ; ++i ) {
			if ( i == cURL.size() || isalnum( cURL[i] ) == false ) {
				if ( i == cURL.size() || cURL[i] != ':' ) {
					std::string cTmp = cURL;
					cURL = "http://";
					for ( uint j = 0 ; j < cTmp.size() ; ++j ) {
						if ( cTmp[j] != '/' ) {
							cURL.insert( cURL.end(), cTmp.begin() + j, cTmp.end() );
							break;
						}
					}
				}
				break;
			}
		}
		m_pcHTMLPart->view()->MakeFocus();
		OpenURL( cURL, KParts::URLArgs() );
//----------------------------------------------
#if 0
		uint32 nEvents = 0;
		pcMsg->FindInt( "events", &nEvents );
		
		if ( nEvents & os::TextView::EI_ESC_PRESSED ) {
			m_pcURLView->Set( m_pcHTMLPart->url().prettyURL().utf8().data() );
			m_pcHTMLPart->view()->MakeFocus();
		break;
		}
		if ( nEvents & os::TextView::EI_ENTER_PRESSED ) {
		std::string cURL = m_pcURLView->GetBuffer()[0];

		for ( uint i = 0 ; i <= cURL.size() ; ++i ) {
			if ( i == cURL.size() || isalnum( cURL[i] ) == false ) {
				if ( i == cURL.size() || cURL[i] != ':' ) {
					std::string cTmp = cURL;
					cURL = "http://";
					for ( uint j = 0 ; j < cTmp.size() ; ++j ) {
						if ( cTmp[j] != '/' ) {
							cURL.insert( cURL.end(), cTmp.begin() + j, cTmp.end() );
							break;
						}
					}
				}
				break;
			}
		}
		UpdateHistory();
		AddHistoryEntry();
		m_pcHTMLPart->view()->MakeFocus();
		OpenURL( cURL, KParts::URLArgs() );
		UpdateHistory();
		}
#endif
		break;
	}
	case ID_ACTIVATE_URLEDIT:
		m_pcURLView->MakeFocus( true );
#if 0
		m_pcURLView->SetCursor( -1, 0 );
#endif
		m_pcURLView->TextView()->SelectAll();
		break;
	case ID_RELOAD:
	{
		KParts::URLArgs cArgs;
		cArgs.reload = true;
		cArgs.xOffset = m_pcHTMLPart->browserExtension()->xOffset();
		cArgs.yOffset = m_pcHTMLPart->browserExtension()->yOffset();
#if 0
		OpenURL( m_pcURLView->GetBuffer()[0], cArgs );
#endif
		OpenURL( m_pcURLView->Text(), cArgs );
		break;
	}
	case ID_NEW_WINDOW:
	{
		BrowserWindow* pcNewWindow = new BrowserWindow( Frame().OffsetByCopy( 30.0f, 30.0f ), false );
		pcNewWindow->Show();
#if 0
		UpdateHistory();
		std::vector<HistoryEntry*> cHistory = m_cHistory;
		cHistory.resize( m_nCurHistoryPos + 1 );
		BrowserWindow* pcNewWindow = new BrowserWindow( GetFrame() + os::Point( 30.0f, 30.0f ), &cHistory, false );
		pcNewWindow->GoHistory(0);
		pcNewWindow->Show( true );
		pcNewWindow->MakeFocus( true );	
#endif
		break;
	}
	case ID_OPEN_LINK:
	{
		BString cURL;
		pcMsg->FindString( "url", &cURL );
		BrowserWindow* pcNewWindow = new BrowserWindow( Frame().OffsetByCopy( 30.0f, 30.0f ), false  );
		pcNewWindow->OpenURL( cURL.String(), KParts::URLArgs() );
		pcNewWindow->Show();
#if 0
		std::string cURL;
		pcMsg->FindString( "url", &cURL );
		std::vector<HistoryEntry*> cHistory = m_cHistory;
		cHistory.resize( m_nCurHistoryPos + 1 );
		BrowserWindow* pcNewWindow = new BrowserWindow( GetFrame() + os::Point( 30.0f, 30.0f ), &cHistory, false );
		pcNewWindow->OpenURL( cURL, KParts::URLArgs() );
		pcNewWindow->AddHistoryEntry();
		pcNewWindow->Show( true );
		pcNewWindow->MakeFocus( true );	
#endif
		break;
	}
	case ID_SAVE_LINK:
	{
		BString cURL;
		pcMsg->FindString( "url", &cURL );

		m_pcHTMLPart->browserExtension()->SaveURL( cURL.String(), "Save link as..." );
		break;
	}
	case ID_COPY_LINK_LOCATION:
	{
#if 0
		std::string cURL;
		pcMsg->FindString( "url", &cURL );

		os::Clipboard cClipboard;
		cClipboard.Lock();
		cClipboard.Clear();
		os::Message* pcData = cClipboard.GetData();
		pcData->AddString( "text/plain", cURL );
		cClipboard.Commit();
		cClipboard.Unlock();
#endif
		break;
	}
	case ID_COPY:
	{
#if 0
		if ( m_cSelectedText.empty() ) {
			break;
		}
		os::Clipboard cClipboard;
		cClipboard.Lock();
		cClipboard.Clear();
		os::Message* pcData = cClipboard.GetData();
		pcData->AddString( "text/plain", m_cSelectedText );
		cClipboard.Commit();
		cClipboard.Unlock();
#endif
		break;
	}
	case ID_FIND:
#if 0
		if ( m_pcSearchDialog == NULL ) {
		m_pcHTMLPart->findTextBegin();
		m_pcSearchDialog = new FindDialog( os::Messenger(this), os::Message(ID_DO_SEARCH), os::Message(ID_SEARCH_CLOSED) );
		m_pcSearchDialog->Show();
		m_pcSearchDialog->MakeFocus();
		}
#endif
		break;
	case ID_DO_SEARCH:
	{
#if 0
		bool bFromTop = false;
		pcMsg->FindBool( "from_top", &bFromTop );
		pcMsg->FindBool( "case_sensitive", &m_bSearchCaseSensitive );
		pcMsg->FindString( "string", &m_cLastSearchStr );

		KHTMLView* pcActiveView = dynamic_cast<KHTMLView*>(GetFocusChild());
		
		KHTMLPart* pcPart = m_pcHTMLPart;
		if ( pcActiveView != NULL ) {
		pcPart = pcActiveView->part();
		}
		if ( bFromTop ) {
		pcPart->findTextBegin();
		}
		pcPart->findTextNext( m_cLastSearchStr.c_str(), true, m_bSearchCaseSensitive );
		break;
#endif
	}
	case ID_REPEAT_FIND:
#if 0
		if ( m_cLastSearchStr.empty() == false ) {
		KHTMLView* pcActiveView = dynamic_cast<KHTMLView*>(GetFocusChild());
		
		KHTMLPart* pcPart = m_pcHTMLPart;
		if ( pcActiveView != NULL ) {
			pcPart = pcActiveView->part();
		}		
		pcPart->findTextNext( m_cLastSearchStr.c_str(), true, m_bSearchCaseSensitive );
		} else if ( m_pcSearchDialog == NULL ) {
		m_pcHTMLPart->findTextBegin();
		m_pcSearchDialog = new FindDialog( os::Messenger(this), os::Message(ID_DO_SEARCH), os::Message(ID_SEARCH_CLOSED) );
		m_pcSearchDialog->Show();
		m_pcSearchDialog->MakeFocus();
		}
		break;
	case ID_SEARCH_CLOSED:
		m_pcSearchDialog = NULL;
		break;
#endif
	case ID_GOHOME:
		OpenURL( "http://www.openbeos.org/", KParts::URLArgs() );
#if 0
		UpdateHistory();
		AddHistoryEntry();
		OpenURL( "http://www.atheos.cx/", KParts::URLArgs() );
		UpdateHistory();
#endif
		break;
#if 0
	case ID_PREV_URL:
		GoHistory( -1 );
		break;
	case ID_NEXT_URL:
		GoHistory( 1 );
		break;
#endif
	case ID_START_DOWNLOAD:
	{
#if 0
		DownloadNode* psNode = NULL;
		std::string   cPath;
		pcMsg->FindPointer( "node", (void**) &psNode );
		pcMsg->FindString( "path", &cPath );

		
		if ( psNode == NULL ) {
		break; // Should never happen
		}
		psNode->m_cPath = cPath;
		const std::string cDstDir = os::Path( cPath.c_str() ).GetDir();

		try {
		os::FSNode cDirNode( cDstDir );
		if ( cDirNode.GetDev() == psNode->m_pcTmpFile->GetDev() ) {
			rename( psNode->m_pcTmpFile->GetPath().c_str(), cPath.c_str() );
			psNode->m_pcTmpFile->Detatch(); // Make sure the destructor don't do anything silly.
		} else {
			psNode->m_pcFile = new os::File( cPath, O_WRONLY | O_CREAT );
			psNode->m_pcTmpFile->Seek( 0, SEEK_SET );
			char anBuffer[32*1024];
			for (;;) {
			int nLen = psNode->m_pcTmpFile->Read( anBuffer, sizeof(anBuffer) );
			if ( nLen < 0 ) {
				throw os::errno_exception( "Failed to copy temporary file" );
			}
			if ( psNode->m_pcFile->Write( anBuffer, nLen ) != nLen ) {
				throw os::errno_exception( "Failed to copy temporary file" );
			}
			if ( nLen < int(sizeof(anBuffer)) ) {
				break;
			}
			}
			delete psNode->m_pcTmpFile;
			psNode->m_pcTmpFile = NULL;
		}
		} catch(...) {
		(new os::Alert( "Error: Failed to create file!",
				os::String().Format( "Failed to create '%s'", cPath.c_str() ), 0,
				"Sorry!", NULL ))->Go(NULL);
		}
		
		psNode->m_pcRequester = NULL;

		if ( psNode->m_bDone == false ) {
		Message cCancelMsg( ID_CANCEL_DOWNLOAD );
		cCancelMsg.AddPointer( "node", psNode );
		
		psNode->m_pcProgressDlg = new DownloadProgress( os::Rect( 100, 100, 449, 349 ), os::String().Format( "Download: %s", cPath.c_str() ),
								psNode->m_cURL,
								cPath,
								psNode->m_nContentSize,
								psNode->m_nStartTime,
								os::Messenger( this ),
								cCancelMsg );

		psNode->m_pcProgressDlg->Show();
		} else {
		delete psNode->m_pcTmpFile;
		delete psNode->m_pcFile;
		delete psNode;
		}
#endif
		break;
	}
	case ID_CANCEL_DOWNLOAD:
	{
#if 0
		DownloadNode* psNode = NULL;
		pcMsg->FindPointer( "node", (void**) &psNode );
		
		if ( psNode == NULL ) {
		break; // Should never happen
		}
		if ( psNode->m_pcProgressDlg != NULL ) {
		psNode->m_pcProgressDlg->Terminate();
		psNode->m_pcProgressDlg = NULL;
		}
		if ( psNode->m_cPath.empty() == false ) {
		unlink( psNode->m_cPath.c_str() );
		}
		if ( psNode->m_bDone == false ) {
		psNode->m_pcRequester = NULL;
		psNode->m_bCanceled = true;
		delete psNode->m_pcTmpFile;
		psNode->m_pcTmpFile = NULL;
		delete psNode->m_pcFile;
		psNode->m_pcFile = NULL;
		} else {
		delete psNode->m_pcTmpFile;
		delete psNode->m_pcFile;
		delete psNode;		
		}
#endif
		break;
	}
	default:
		BWindow::MessageReceived( pcMsg );
		break;
	}
}
예제 #17
0
void BrowserWindow::Completed()
{
#if 0
	UpdateHistory();
#endif
}
예제 #18
0
VOID KeyEventProc(PCONSOLE_INFO pdp, KEY_EVENT_RECORD event)
{
#ifdef USE_OLD_CODE
   // this must here gather keystrokes and pass them forward into the
   // opened sentience...
//   PTEXT temp;
	int bOutput = FALSE;
   lprintf( "Entering handle a key event..." );
	Lock( pdp );
   lprintf( "Got the lock, waiting for collection buffer..." );
   if( event.bKeyDown )
   {
      PTEXT key;
      // here is where we evaluate the curent keystroke....

      for( ; event.wRepeatCount; event.wRepeatCount-- )
      {
         int mod = KEYMOD_NORMAL;
         extern PSIKEYDEFINE KeyDefs[];
         if(event.dwControlKeyState& (RIGHT_CTRL_PRESSED|LEFT_CTRL_PRESSED))
            mod |= KEYMOD_CTRL;
         if(event.dwControlKeyState& (RIGHT_ALT_PRESSED|LEFT_ALT_PRESSED))
            mod |= KEYMOD_ALT;
         if( KeyDefs[event.wVirtualKeyCode].flags & KDF_CAPSKEY )
         {
            if( event.dwControlKeyState & CAPSLOCK_ON )
            {
               if( !(event.dwControlKeyState& SHIFT_PRESSED) )
                  mod |= KEYMOD_SHIFT;
            }
            else
            {
               if( event.dwControlKeyState& SHIFT_PRESSED )
                  mod |= KEYMOD_SHIFT;
            }
         }
         else
            if( event.dwControlKeyState& SHIFT_PRESSED )
               mod |= KEYMOD_SHIFT;
         if( pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bStroke ||
             pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bMacro )
         {
            if( pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bStroke )
            {
               bOutput |= DoStroke(pdp, pdp->Keyboard[event.wVirtualKeyCode][mod].data.stroke);
            }
            else if( pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bMacro )
            {
               if( pdp->common.Owner->pRecord != pdp->Keyboard[event.wVirtualKeyCode][mod].data.macro )
                  InvokeMacro( pdp->common.Owner
                             , pdp->Keyboard[event.wVirtualKeyCode][mod].data.macro
                             , NULL );
               // do macro!!!!!
            }
         }
         else
         {
				if( key = KeyDefs[event.wVirtualKeyCode].op[mod].data.pStroke )
				{
					if( KeyDefs[event.wVirtualKeyCode].op[mod].bFunction )
						bOutput |= ((KeyFunc)key)(pdp);
					else
					{
						bOutput |= DoStroke( pdp, key );
					}
				}
         }
      }
      // call to clear and re-write the current buffer....
      //if( bOutput ) // so we don't output on shift, control, etc...
         //RenderCommandLine( pdp );
   }
   else
   {
      // key up's don't matter like ever...
   }
	Unlock( pdp );
#else
   // this must here gather keystrokes and pass them forward into the
   // opened sentience...
//   PTEXT temp;
   int bOutput = FALSE;
   int mod = KEYMOD_NORMAL;
   if( !pdp ) // not a valid window handle/device path
        return;
   //Log( "Entering keyproc..." );
   EnterCriticalSec( &pdp->Lock );
   //while( LockedExchange( &pdp->common.CommandInfo->CollectionBufferLock, 1 ) )
   //   Sleep(0);
   Log1( "mod = %x", pdp->dwControlKeyState );
   mod = pdp->dwControlKeyState;

   if( KeyDefs[event.wVirtualKeyCode].flags & KDF_CAPSKEY )
   {
      if( event.dwControlKeyState & CAPSLOCK_ON )
      {
         mod ^= KEYMOD_SHIFT;
      }
   }

   if( event.bKeyDown )
   {
      for( ; event.wRepeatCount; event.wRepeatCount-- )
		{
			unsigned char KeyState[256];
			DECLTEXT( key, "                   " );
			GetKeyboardState( KeyState );
			SetTextSize( &key, ToAscii( event.wVirtualKeyCode
											  , event.wVirtualScanCode
											  , KeyState
											  , (unsigned short*)key.data.data
											  , 0 ) );
			KeyPressHandler( pdp, event.wVirtualKeyCode, mod, (PTEXT)&key );
		}
#if 0
      // here is where we evaluate the curent keystroke....
      for( ; event.wRepeatCount; event.wRepeatCount-- )
		{

         // check current keyboard override...
         if( pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bStroke ||
             pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bMacro )
         {
            if( pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bStroke )
            {
               bOutput |= DoStroke(pdp, pdp->Keyboard[event.wVirtualKeyCode][mod].data.stroke);
            }
            else if( pdp->Keyboard[event.wVirtualKeyCode][mod].flags.bMacro )
            {
               if( pdp->common.Owner->pRecord != pdp->Keyboard[event.wVirtualKeyCode][mod].data.macro )
                  InvokeMacro( pdp->common.Owner
                             , pdp->Keyboard[event.wVirtualKeyCode][mod].data.macro
                             , NULL );
            }
         }
         else // key was not overridden
         {
            int result;
            Log1( "Keyfunc = %d", KeyDefs[event.wVirtualKeyCode].op[mod].bFunction );
            switch( KeyDefs[event.wVirtualKeyCode].op[mod].bFunction )
            {
            case KEYDATA_DEFINED:
               Log( "Key data_defined" );
               bOutput |= DoStroke( pdp, (PTEXT)&KeyDefs[event.wVirtualKeyCode].op[mod].data.pStroke );
                    result = UPDATE_NOTHING; // unsure about this - recently added.
                    // well it would appear that the stroke results in whether to update
                    // the command prompt or not.
                break;
            case KEYDATA:
               {
                  char KeyState[256];
                  DECLTEXT( key, "                   " );
                  GetKeyboardState( KeyState );
                  SetTextSize( &key, ToAscii( event.wVirtualKeyCode
                                            , event.wVirtualScanCode
                                            , KeyState
                                            , (void*)key.data.data
                                            , 0 ) );
                  if( GetTextSize( (PTEXT)&key ) )
                     bOutput |= DoStroke( pdp, (PTEXT)&key );
                  result = UPDATE_NOTHING; // already taken care of?!
               }
               break;
            case COMMANDKEY:
               result = KeyDefs[event.wVirtualKeyCode].op[mod].data.CommandKey( pdp->common.CommandInfo );
               break;
            case HISTORYKEY:
               result = KeyDefs[event.wVirtualKeyCode].op[mod].data.HistoryKey( pdp->pHistoryDisplay );
               break;
            case CONTROLKEY:
               KeyDefs[event.wVirtualKeyCode].op[mod].data.ControlKey( &pdp->dwControlKeyState, TRUE );
               result = UPDATE_NOTHING;
               break;
            case SPECIALKEY:
               result = KeyDefs[event.wVirtualKeyCode].op[mod].data.SpecialKey( pdp );
               break;
            }
            switch( result )
            {
            case UPDATE_COMMAND:
               bOutput = TRUE;
               break;
				case UPDATE_HISTORY:
					if( UpdateHistory( pdp ) )
						DoRenderHistory(pdp, TRUE);
						DoRenderHistory(pdp, FALSE);

					break;
				case UPDATE_DISPLAY:
					ChildCalculate( pdp );
					break;
            }
         }
      }
      //if( bOutput )
		//   RenderCommandLine( pdp );
#endif
   }
   else
   {
    // flag is redundant for CONTOLKEY type...
      // key up's only matter if key is upaction flaged...
    switch( KeyDefs[event.wVirtualKeyCode].op[mod].bFunction )
    {
        case CONTROLKEY:
            KeyDefs[event.wVirtualKeyCode].op[mod].data.ControlKey( &pdp->dwControlKeyState, FALSE );
            break;
        }
   }
   LeaveCriticalSec( &pdp->Lock );
   //lprintf( "Left critical section on wincon." );
#endif
}
예제 #19
0
int SearchRoot(POS *p, int ply, int alpha, int beta, int depth, int *pv) {

  int best, score, move, new_depth, new_pv[MAX_PLY];
  int fl_check, fl_prunable_move, mv_type, reduction;
  int mv_tried = 0, quiet_tried = 0;
  int mv_played[MAX_MOVES];
  int mv_hist_score;
  int victim, last_capt;
  int move_change = 0;
  
  fl_has_choice = 0;
  
  MOVES m[1];
  UNDO u[1];

  // Periodically check for timeout, ponderhit or stop command

  nodes++;
  CheckTimeout();

  // Quick exit
  
  if (abort_search) return 0;

  // Retrieving data from transposition table. We hope for a cutoff
  // or at least for a move to improve move ordering.

  move = 0;
  if (TransRetrieve(p->hash_key, &move, &score, alpha, beta, depth, ply)) {
    
    // For move ordering purposes, a cutoff from hash is treated
    // exactly like a cutoff from search

    if (score >= beta) UpdateHistory(p, -1, move, depth, ply);

    // Root node is a pv node, so we return only exact scores

    if (score > alpha && score < beta)
      return score;
  }
  
  // Are we in check? Knowing that is useful when it comes 
  // to pruning/reduction decisions

  fl_check = InCheck(p);

  // Init moves and variables before entering main loop
  
  best = -INF;
  InitMoves(p, m, move, Refutation(-1), ply);
  
  // Main loop
  
  while ((move = NextMove(m, &mv_type))) {

    mv_hist_score = history[p->pc[Fsq(move)]][Tsq(move)];
	victim = TpOnSq(p, Tsq(move));
	if (victim != NO_TP) last_capt = Tsq(move);
	else last_capt = -1;

    p->DoMove(move, u);
    if (Illegal(p)) { p->UndoMove(move, u); continue; }

    // Update move statistics (needed for reduction/pruning decisions)

    mv_played[mv_tried] = move;
    mv_tried++;
    if (mv_tried > 1) fl_has_choice = 1; // we have a choice between at least two root moves
    if (depth > 16 && verbose) DisplayCurrmove(move, mv_tried);
    if (mv_type == MV_NORMAL) quiet_tried++;
    fl_prunable_move = !InCheck(p) && (mv_type == MV_NORMAL);

    // Set new search depth

    new_depth = depth - 1 + InCheck(p);

    // Late move reduction
  
    reduction = 0;
  
    if (use_lmr
    && depth >= 2
    && mv_tried > 3
    && mv_hist_score < hist_limit
    && alpha > -MAX_EVAL && beta < MAX_EVAL
    && !fl_check 
    &&  fl_prunable_move
    && lmr_size[1][depth][mv_tried] > 0
    && MoveType(move) != CASTLE ) {

    reduction = lmr_size[1][depth][mv_tried];

    // increase reduction on bad history score

    if (mv_hist_score < 0 
    && new_depth - reduction > 2 
    && lmr_hist_adjustement) 
       reduction++;

    new_depth -= reduction;
  }

  re_search:
   
  // PVS

  if (best == -INF)
    score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv);
  else {
    score = -Search(p, ply + 1, -alpha - 1, -alpha, new_depth, 0, move, last_capt, new_pv);
    if (!abort_search && score > alpha && score < beta)
      score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv);
  }

  // Reduced move scored above alpha - we need to re-search it

  if (reduction && score > alpha) {
    new_depth += reduction;
    reduction = 0;
    goto re_search;
  }

    p->UndoMove(move, u);
    if (abort_search) return 0;

  // Beta cutoff

    if (score >= beta) {
      if (!fl_check) {
        UpdateHistory(p, -1, move, depth, ply);
        for (int mv = 0; mv < mv_tried; mv++)
          DecreaseHistory(p, mv_played[mv], depth);
      }
      TransStore(p->hash_key, move, score, LOWER, depth, ply);

      // Update search time depending on whether the first move has changed

      if (depth > 4) {
        if (pv[0] != move) Timer.OnNewRootMove();
        else               Timer.OnOldRootMove();
      }

	  // Change the best move and show the new pv

      BuildPv(pv, new_pv, move);
      DisplayPv(score, pv);

      return score;
    }

    // Updating score and alpha

    if (score > best) {
      best = score;

      if (score > alpha) {
        alpha = score;

        // Update search time depending on whether the first move has changed

        if (depth > 4) {
          if (pv[0] != move) Timer.OnNewRootMove();
          else               Timer.OnOldRootMove();
        }

	    // Change the best move and show the new pv

        BuildPv(pv, new_pv, move);
        DisplayPv(score, pv);
      }
    }

  } // end of the main loop

  // Return correct checkmate/stalemate score

  if (best == -INF)
    return InCheck(p) ? -MATE + ply : DrawScore(p);

  // Save score in the transposition table

  if (*pv) {
    if (!fl_check) {
      UpdateHistory(p, -1, *pv, depth, ply);
      for (int mv = 0; mv < mv_tried; mv++)
        DecreaseHistory(p, mv_played[mv], depth);
    }
    TransStore(p->hash_key, *pv, best, EXACT, depth, ply);
    
  } else
    TransStore(p->hash_key, 0, best, UPPER, depth, ply);

  return best;
}