Example #1
0
void RegionLoad::DefineActors()
{
	//Creates a list with actors that intercept the region
	regionActors.Clear();

	KrVector2T< GlFixed > screen, axis;
	Axis *pAxis = GameControl::Get()->GetAxis();
	
	//Get region bounds (Solve the bug "Game behavior differ based on editor grid position when uses regions", ALPHA_1_1_4.ged)
	getImage()->CalcTransform();
	KrRect rectRegion = getImage()->Bounds();
	rectRegion.Translate(-rectRegion.xmin, -rectRegion.ymin);
	
	//To axis coordinate (Solve the bug "Game behavior differ based on editor grid position when uses regions", ALPHA_1_1_4.ged)
	getImage()->ObjectToScreen(0, 0, &screen);
	pAxis->getImage()->ScreenToObject( screen.x.ToInt(), screen.y.ToInt(), &axis );
	rectRegion.Translate(axis.x.ToInt(), axis.y.ToInt());


	MapActorIterator it(mapActors);
	for(it.Begin(); !it.Done(); it.Next())
	{
		ListActor *listActor = it.Value();
		for(int il = 0; il < listActor->Count(); il++)
		{
			Actor *actor = (*listActor)[il];			

			if( actor->EditMode() && 
				!actor->isRegion() &&
				!actor->isView() &&
				actor != pAxis
				)
			{
				//Get actor bounds (Solve the bug "Game behavior differ based on editor grid position when uses regions", ALPHA_1_1_4.ged, abuse2.ged)
				actor->getImage()->CalcCompositeTransform();
				KrRect rectActor = actor->Bounds();

				if(actor->getTextActor() && !rectActor.IsValid())
				{
					//Solve the bug "Text actors aren't load after use the LoadGame function without Activation Regions"
					engine->Tree()->Walk(actor->getImage(), true, true);
					rectActor = actor->Bounds();
				}

				if(actor->getTile() && !rectActor.IsValid())
				{
					//Solve the bug "Text actors aren't load after use the LoadGame function without Activation Regions"
					engine->Tree()->Walk(actor->getImage(), true, true);
					rectActor = actor->Bounds();
				}


				rectActor.Translate(-rectActor.xmin, -rectActor.ymin);

				
				//To axis coordinate (Solve the bug "Game behavior differ based on editor grid position when uses regions", ALPHA_1_1_4.ged, abuse2.ged)
				actor->getImage()->ObjectToScreen(0, 0, &screen);
				pAxis->getImage()->ScreenToObject( screen.x.ToInt(), screen.y.ToInt(), &axis );
				rectActor.Translate(axis.x.ToInt(), axis.y.ToInt());

				if(rectActor.IsValid() && rectRegion.Intersect(rectActor))
				{
					regionActors.Add(actor->getCloneName(), 1); 
				}
			}
		}
	}

	viewPosAnt.Set(-123, 456, 0, 0);
	bRegionInView = false;
}
void IntrinsicFeatureCalculator::GetDistanceToSurfaceMeasures(vtkSmartPointer<vtkTable> table, std::vector< ftk::Object::Point > surfacePoints)
{
	typedef itk::Image< IPixelT, 3 > InputImageType;
	typedef itk::Image< LPixelT, 3 > OutputImageType;
	typedef itk::DanielssonDistanceMapImageFilter< OutputImageType, OutputImageType > DanielssonFilterType;
	typedef itk::RescaleIntensityImageFilter< OutputImageType, OutputImageType > RescalerType;
	typedef itk::ImageFileReader< InputImageType  >  ReaderType;
	typedef itk::ImageFileWriter< InputImageType >  InputWriterType;
	typedef itk::ImageFileWriter< OutputImageType >  WriterType;
	typedef itk::LineIterator< OutputImageType > LineIteratorType;

	vtkSmartPointer<vtkDoubleArray> column = vtkSmartPointer<vtkDoubleArray>::New();
	column->SetName( "Dist_To_Surface" );
	column->SetNumberOfValues( table->GetNumberOfRows() );
	table->AddColumn(column);	

	OutputImageType::Pointer im;
	im = OutputImageType::New();
	OutputImageType::PointType origin;
    origin[0] = 0; 
    origin[1] = 0;    
	origin[2] = 0;    
    im->SetOrigin( origin );

    OutputImageType::IndexType start;
    start[0] =   0;  // first index on X
    start[1] =   0;  // first index on Y    
	start[2] =   0;  // first index on Z    
    
	OutputImageType::Pointer temp_image = labelImage->GetItkPtr< LPixelT >(0,0);
	itk::Size<3> im_size = temp_image->GetBufferedRegion().GetSize();
	im_size[2] = 1;
  
    InputImageType::RegionType region;
    region.SetSize( im_size );
    region.SetIndex( start );
    
    im->SetRegions( region );
    im->Allocate();
    im->FillBuffer(0);
	im->Update();
	
	//copy the input image into the ITK image
	for(int p = 1; p < (int)surfacePoints.size(); ++p)
	{
		itk::Index<3> indx,indy;
		indx[0] = surfacePoints[p-1].x;
		indx[1] = surfacePoints[p-1].y;
		indx[2] = 0;
		indy[0] = surfacePoints[p].x;
		indy[1] = surfacePoints[p].y;
		indy[2] = 0;
		LineIteratorType it( im, indx, indy );
		//it.GoToBegin();
		//while(!it.IsAtEnd())
		for(it.GoToBegin(); !it.IsAtEnd(); ++it)
		{
			it.Set(255);			
		}
	}

	DanielssonFilterType::Pointer danielssonFilter = DanielssonFilterType::New();	
	WriterType::Pointer writer = WriterType::New();	
	danielssonFilter->SetInput( im );
	writer->SetFileName( "DistanceMap.tif" );
	danielssonFilter->InputIsBinaryOn();
	danielssonFilter->Update();
	OutputImageType::Pointer distMap = danielssonFilter->GetOutput();
	writer->SetInput( distMap );
	writer->Update();
	
	for(int row=0; row<(int)table->GetNumberOfRows(); ++row)
	{
		OutputImageType::IndexType indx;
		indx[0] = table->GetValue(row, 1).ToInt();
		indx[1] = table->GetValue(row, 2).ToInt();
		indx[2] = 0;
		int dist = distMap->GetPixel(indx);
		table->SetValueByName(row, "Dist_To_Surface", vtkVariant(dist));
	}



}
const char *TScriptCall::Execute()
{
	GString strCommand;
	int bAddedFirstParam = 0;

	if (m_nProjectPort)
	{
		strCommand.Format("%d",(int)m_nProjectPort);
	}
	else
	{
		strCommand = m_strProject;
	}
	strCommand += ":CallScript(";
	
	GStringIterator it( &m_lstParameters );
	while (it())
	{
		if (bAddedFirstParam)
			strCommand += ',';
		GString str(it++);
		strCommand += '"';
		strCommand += str.EscapeWithHex("'\"%");
		strCommand += '"';
		bAddedFirstParam = 1;
	}
	strCommand += ")";

	if (XMLProcedureCall::m_lpfnSend)
	{
		XMLProcedureCall::m_lpfnSend( strCommand );
	}

	int nRetryCount = 0;
RESEND:
	try
	{
		m_strResults = m_DataSource->send(	"TScript",
										strCommand,
										(int)strCommand.Length(),/* -1 = Don't send the Null terminator */
										0,
										&m_pUserData,"TScriptServ=");

		if (XMLProcedureCall::m_lpfnRecv)
			XMLProcedureCall::m_lpfnRecv(m_strResults);

	}
	catch(GException &e)
	{
		// "General error parsing XML stream" means the data was corrupted in transit.
		if (e.GetError() == 7)
		{
			// Resend the request.
			if (nRetryCount++ < 3)
			{
				TRACE_WARNING("Attempting resend" );
				goto RESEND;
			}
		}
		
		// "the handle is invalid".  We need to 'reboot' the datasource. (WININET)
		if ((e.GetError()  == 6) && 
			(e.GetSystem() == 0)) 
		{
			// Resend the request.
			if (nRetryCount++ < 3)
			{
				TRACE_WARNING("Attempting resend" );
				m_DataSource->IPAddressChange();
				goto RESEND;
			}
		}

		// This helps distinguish Client errors from Server errors
		// unless the error was a client side connect error.
		throw GException("XMLProcedureCall", 4, m_DataSource->GetServerAddress(), e.GetDescription());
	}
	return m_strResults;
}
Example #4
0
/* --| main |------------------------------------------------------ */
extern "C" int KDE_EXPORT kdemain(int argc, char* argv[])
{
  setgid(getgid()); setuid(getuid()); // drop privileges

  // deal with shell/command ////////////////////////////
  bool histon = true;
  bool menubaron = true;
  bool tabbaron = true;
  bool frameon = true;
  bool scrollbaron = true;
  bool showtip = true;

  TDEAboutData aboutData( "konsole", I18N_NOOP("Konsole"),
    KONSOLE_VERSION, description, TDEAboutData::License_GPL_V2,
    "Copyright (c) 2011-2014, The Trinity Desktop project\nCopyright (c) 1997-2006, Lars Doelle");
  aboutData.addAuthor( "Timothy Pearson", I18N_NOOP("Maintainer, Trinity bugfixes"), "*****@*****.**" );
  aboutData.addAuthor("Robert Knight",I18N_NOOP("Previous Maintainer"), "*****@*****.**");
  aboutData.addAuthor("Lars Doelle",I18N_NOOP("Author"), "*****@*****.**");
  aboutData.addCredit("Kurt V. Hindenburg",
    I18N_NOOP("bug fixing and improvements"),
    "*****@*****.**");
  aboutData.addCredit("Waldo Bastian",
    I18N_NOOP("bug fixing and improvements"),
    "*****@*****.**");
  aboutData.addCredit("Stephan Binner",
    I18N_NOOP("bug fixing and improvements"),
    "*****@*****.**");
  aboutData.addCredit("Chris Machemer",
    I18N_NOOP("bug fixing"),
    "*****@*****.**");
  aboutData.addCredit("Stephan Kulow",
    I18N_NOOP("Solaris support and work on history"),
    "*****@*****.**");
  aboutData.addCredit("Alexander Neundorf",
    I18N_NOOP("faster startup, bug fixing"),
    "*****@*****.**");
  aboutData.addCredit("Peter Silva",
    I18N_NOOP("decent marking"),
    "*****@*****.**");
  aboutData.addCredit("Lotzi Boloni",
    I18N_NOOP("partification\n"
    "Toolbar and session names"),
    "*****@*****.**");
  aboutData.addCredit("David Faure",
    I18N_NOOP("partification\n"
    "overall improvements"),
    "*****@*****.**");
  aboutData.addCredit("Antonio Larrosa",
    I18N_NOOP("transparency"),
    "*****@*****.**");
  aboutData.addCredit("Matthias Ettrich",
    I18N_NOOP("most of main.C donated via kvt\n"
    "overall improvements"),
    "*****@*****.**");
  aboutData.addCredit("Warwick Allison",
    I18N_NOOP("schema and selection improvements"),
    "*****@*****.**");
  aboutData.addCredit("Dan Pilone",
    I18N_NOOP("SGI Port"),
    "*****@*****.**");
  aboutData.addCredit("Kevin Street",
    I18N_NOOP("FreeBSD port"),
    "*****@*****.**");
  aboutData.addCredit("Sven Fischer",
    I18N_NOOP("bug fixing"),
    "*****@*****.**");
  aboutData.addCredit("Dale M. Flaven",
    I18N_NOOP("bug fixing"),
    "*****@*****.**");
  aboutData.addCredit("Martin Jones",
    I18N_NOOP("bug fixing"),
    "*****@*****.**");
  aboutData.addCredit("Lars Knoll",
    I18N_NOOP("bug fixing"),
    "*****@*****.**");
  aboutData.addCredit("",I18N_NOOP("Thanks to many others.\n"
    "The above list only reflects the contributors\n"
    "I managed to keep track of."));

  TDECmdLineArgs::init( argc, argv, &aboutData );
  TDECmdLineArgs::addCmdLineOptions( options ); // Add our own options.
  //1.53 sec
  TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
  TDECmdLineArgs *qtargs = TDECmdLineArgs::parsedArgs("qt");
  has_noxft = !args->isSet("xft");
  TEWidget::setAntialias( !has_noxft );
  TEWidget::setStandalone( true );

  // The following Qt options have no effect; warn users.
  if( qtargs->isSet("background") )
      kdWarning() << "The Qt option -bg, --background has no effect." << endl;
  if( qtargs->isSet("foreground") )
      kdWarning() << "The Qt option -fg, --foreground has no effect." << endl;
  if( qtargs->isSet("button") )
      kdWarning() << "The Qt option -btn, --button has no effect." << endl;
  if( qtargs->isSet("font") )
      kdWarning() << "The Qt option -fn, --font has no effect." << endl;

  TDEApplication* a = NULL;
#ifdef COMPOSITE
  a = new TDEApplication(TDEApplication::openX11RGBADisplay());
  argb_visual = a->isX11CompositionAvailable();
#else
  a = new TDEApplication;
#endif

  TQString dataPathBase = TDEStandardDirs::kde_default("data").append("konsole/");
  TDEGlobal::dirs()->addResourceType("wallpaper", dataPathBase + "wallpapers");

  KImageIO::registerFormats(); // add io for additional image formats
  //2.1 secs

  TQString title;
  if(args->isSet("T")) {
    title = TQFile::decodeName(args->getOption("T"));
  }
  if(qtargs->isSet("title")) {
    title = TQFile::decodeName(qtargs->getOption("title"));
  }

  TQString term = "";
  if(args->isSet("tn")) {
    term=TQString::fromLatin1(args->getOption("tn"));
  }
  login_shell = args->isSet("ls");

  TQStrList eargs;

  const char* shell = 0;
  if (!args->getOption("e").isEmpty())
  {
     if (args->isSet("ls"))
        TDECmdLineArgs::usage(i18n("You can't use BOTH -ls and -e.\n"));
     shell = strdup(args->getOption("e"));
     eargs.append(shell);
     for(int i=0; i < args->count(); i++)
       eargs.append( args->arg(i) );

     if (title.isEmpty() &&
         (kapp->caption() == kapp->aboutData()->programName()))
     {
        title = TQFile::decodeName(shell);  // program executed in the title bar
     }
     showtip = false;
  }

  TQCString sz = "";
  sz = args->getOption("vt_sz");
  histon = args->isSet("hist");
  menubaron = args->isSet("menubar");
  tabbaron = args->isSet("tabbar") && args->isSet("toolbar");
  frameon = args->isSet("frame");
  scrollbaron = args->isSet("scrollbar");
  TQCString wname = qtargs->getOption("name");
  full_script = args->isSet("script");
  auto_close = args->isSet("close");
  fixed_size = !args->isSet("resize");

  if (!full_script)
	a->dcopClient()->setQtBridgeEnabled(false);

  TQCString type = "";

  if(args->isSet("type")) {
    type = args->getOption("type");
  }
  if(args->isSet("types")) {
    TQStringList types = TDEGlobal::dirs()->findAllResources("appdata", "*.desktop", false, true);
    types.sort();
    for(TQStringList::ConstIterator it = types.begin();
        it != types.end(); ++it)
    {
       TQString file = *it;
       file = file.mid(file.findRev('/')+1);
       if (file.endsWith(".desktop"))
          file = file.left(file.length()-8);
       printf("%s\n", TQFile::encodeName(file).data());
    }
    return 0;
  }
  if(args->isSet("schemas") || args->isSet("schemata")) {
    ColorSchemaList colors;
    colors.checkSchemas();
    for(int i = 0; i < (int) colors.count(); i++)
    {
       ColorSchema *schema = colors.find(i);
       TQString relPath = schema->relPath();
       if (!relPath.isEmpty())
          printf("%s\n", TQFile::encodeName(relPath).data());
    }
    return 0;
  }

  if(args->isSet("keytabs")) {
    TQStringList lst = TDEGlobal::dirs()->findAllResources("data", "konsole/*.keytab");

    printf("default\n");   // 'buildin' keytab
    lst.sort();
    for(TQStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
    {
      TQFileInfo fi(*it);
      TQString file = fi.baseName();
      printf("%s\n", TQFile::encodeName(file).data());
    }
    return 0;
  }

  TQString workDir = TQFile::decodeName( args->getOption("workdir") );

  TQString keytab = "";
  if (args->isSet("keytab"))
    keytab = TQFile::decodeName(args->getOption("keytab"));

  TQString schema = "";
  if (args->isSet("schema"))
    schema = args->getOption("schema");

  TDEConfig * sessionconfig = 0;
  TQString profile = "";
  if (args->isSet("profile")) {
    profile = args->getOption("profile");
    TQString path = locate( "data", "konsole/profiles/" + profile );
    if ( TQFile::exists( path ) )
      sessionconfig=new TDEConfig( path, true );
    else
      profile = "";
  }
  if (args->isSet("profiles"))
  {
     TQStringList profiles = TDEGlobal::dirs()->findAllResources("data", "konsole/profiles/*", false, true);
     profiles.sort();
     for(TQStringList::ConstIterator it = profiles.begin();
         it != profiles.end(); ++it)
     {
        TQString file = *it;
        file = file.mid(file.findRev('/')+1);
        printf("%s\n", TQFile::encodeName(file).data());
     }
     return 0;
  }


  //FIXME: more: font

  args->clear();

  int c = 0, l = 0;
  if ( !sz.isEmpty() )
  {
    char *ls = strchr( sz.data(), 'x' );
    if ( ls != NULL )
    {
       *ls='\0';
       ls++;
       c=atoi(sz.data());
       l=atoi(ls);
    }
    else
    {
       TDECmdLineArgs::usage(i18n("expected --vt_sz <#columns>x<#lines> e.g. 80x40\n"));
    }
  }

  if (!kapp->authorizeTDEAction("size"))
    fixed_size = true;

  // ///////////////////////////////////////////////

  // Ignore SIGHUP so that we don't get killed when
  // our parent-shell gets closed.
  signal(SIGHUP, SIG_IGN);

  putenv((char*)"COLORTERM="); // to trigger mc's color detection
  KonsoleSessionManaged ksm;

  if (a->isRestored() || !profile.isEmpty())
  {
    if (!shell)
       shell = konsole_shell(eargs);

    if (profile.isEmpty())
      sessionconfig = a->sessionConfig();
    sessionconfig->setDesktopGroup();
    int n = 1;

    TQString key;
    TQString sTitle;
    TQString sPgm;
    TQString sTerm;
    TQString sIcon;
    TQString sCwd;
    int     n_tabbar;

    // TODO: Session management stores everything in same group,
    // should use one group / mainwindow
    while (TDEMainWindow::canBeRestored(n) || !profile.isEmpty())
    {
        sessionconfig->setGroup(TQString("%1").arg(n));
        if (!sessionconfig->hasKey("Pgm0"))
            sessionconfig->setDesktopGroup(); // Backwards compatible

        int session_count = sessionconfig->readNumEntry("numSes");
        int counter = 0;

        wname = sessionconfig->readEntry("class",wname).latin1();

        sPgm = sessionconfig->readEntry("Pgm0", shell);
        sessionconfig->readListEntry("Args0", eargs);
        sTitle = sessionconfig->readEntry("Title0", title);
        sTerm = sessionconfig->readEntry("Term0");
        sIcon = sessionconfig->readEntry("Icon0","konsole");
        sCwd = sessionconfig->readPathEntry("Cwd0");
        workDir = sessionconfig->readPathEntry("workdir");
	n_tabbar = TQMIN(sessionconfig->readUnsignedNumEntry("tabbar",Konsole::TabBottom),2);
        Konsole *m = new Konsole(wname,histon,menubaron,tabbaron,frameon,scrollbaron,0/*type*/,true,n_tabbar, workDir);

        m->newSession(sPgm, eargs, sTerm, sIcon, sTitle, sCwd);

        m->enableFullScripting(full_script);
        m->enableFixedSize(fixed_size);
	m->restore(n);
        sessionconfig->setGroup(TQString("%1").arg(n));
        if (!sessionconfig->hasKey("Pgm0"))
            sessionconfig->setDesktopGroup(); // Backwards compatible
        m->makeGUI();
        m->setEncoding(sessionconfig->readNumEntry("Encoding0"));
        m->setSchema(sessionconfig->readEntry("Schema0"));
        // Use konsolerc default as tmpFont instead?
        TQFont tmpFont = TDEGlobalSettings::fixedFont();
        m->initSessionFont(sessionconfig->readFontEntry("SessionFont0", &tmpFont));
        m->initSessionKeyTab(sessionconfig->readEntry("KeyTab0"));
        m->initMonitorActivity(sessionconfig->readBoolEntry("MonitorActivity0",false));
        m->initMonitorSilence(sessionconfig->readBoolEntry("MonitorSilence0",false));
        m->initMasterMode(sessionconfig->readBoolEntry("MasterMode0",false));
        m->initTabColor(sessionconfig->readColorEntry("TabColor0"));
        // -1 will be changed to the default history in konsolerc
        m->initHistory(sessionconfig->readNumEntry("History0", -1), 
                       sessionconfig->readBoolEntry("HistoryEnabled0", true));
        counter++;

        // show() before 2nd+ sessions are created allows --profile to
        //  initialize the TE size correctly.
        m->show();

        while (counter < session_count)
        {
          key = TQString("Title%1").arg(counter);
          sTitle = sessionconfig->readEntry(key, title);
          key = TQString("Args%1").arg(counter);
          sessionconfig->readListEntry(key, eargs);

          key = TQString("Pgm%1").arg(counter);
          
          // if the -e option is passed on the command line, this overrides the program specified 
          // in the profile file
          if ( args->isSet("e") )
            sPgm = (shell ? TQFile::decodeName(shell) : TQString());
          else
            sPgm = sessionconfig->readEntry(key, shell);

          key = TQString("Term%1").arg(counter);
          sTerm = sessionconfig->readEntry(key);
          key = TQString("Icon%1").arg(counter);
          sIcon = sessionconfig->readEntry(key,"konsole");
          key = TQString("Cwd%1").arg(counter);
          sCwd = sessionconfig->readPathEntry(key);
          m->newSession(sPgm, eargs, sTerm, sIcon, sTitle, sCwd);
          m->setSessionTitle(sTitle);  // Use title as is
          key = TQString("Schema%1").arg(counter);
          m->setSchema(sessionconfig->readEntry(key));
          key = TQString("Encoding%1").arg(counter);
          m->setEncoding(sessionconfig->readNumEntry(key));
          key = TQString("SessionFont%1").arg(counter);
          TQFont tmpFont = TDEGlobalSettings::fixedFont();
          m->initSessionFont(sessionconfig->readFontEntry(key, &tmpFont));
          key = TQString("KeyTab%1").arg(counter);
          m->initSessionKeyTab(sessionconfig->readEntry(key));
          key = TQString("MonitorActivity%1").arg(counter);
          m->initMonitorActivity(sessionconfig->readBoolEntry(key,false));
          key = TQString("MonitorSilence%1").arg(counter);
          m->initMonitorSilence(sessionconfig->readBoolEntry(key,false));
          key = TQString("MasterMode%1").arg(counter);
          m->initMasterMode(sessionconfig->readBoolEntry(key,false));
          key = TQString("TabColor%1").arg(counter);
          m->initTabColor(sessionconfig->readColorEntry(key));
          // -1 will be changed to the default history in konsolerc
          key = TQString("History%1").arg(counter);
          TQString key2 = TQString("HistoryEnabled%1").arg(counter);
          m->initHistory(sessionconfig->readNumEntry(key, -1), 
                         sessionconfig->readBoolEntry(key2, true));
          counter++;
        }
        m->setDefaultSession( sessionconfig->readEntry("DefaultSession","shell.desktop") );

        m->initFullScreen();
        if ( !profile.isEmpty() ) {
          m->callReadPropertiesInternal(sessionconfig,1);
          profile = "";
          // Hack to work-around sessions initialized with minimum size
          for (int i=0;i<counter;i++)
            m->activateSession( i );
          m->setColLin(c,l); // will use default height and width if called with (0,0)
        }
	// works only for the first one, but there won't be more.
        n++;
        m->activateSession( sessionconfig->readNumEntry("ActiveSession",0) );
	m->setAutoClose(auto_close);
    }
  }
  else
  {
    Konsole*  m = new Konsole(wname,histon,menubaron,tabbaron,frameon,scrollbaron,type, false, 0, workDir);
    m->newSession((shell ? TQFile::decodeName(shell) : TQString()), eargs, term, TQString(), title, workDir);
    m->enableFullScripting(full_script);
    m->enableFixedSize(fixed_size);
    //3.8 :-(
    //exit(0);

    if (!keytab.isEmpty())
      m->initSessionKeyTab(keytab);

    if (!schema.isEmpty()) {
      if (schema.right(7)!=".schema")
        schema+=".schema";
      m->setSchema(schema);
      m->activateSession(0); // Fixes BR83162, transp. schema + notabbar
    }

    m->setColLin(c,l); // will use default height and width if called with (0,0)

    m->initFullScreen();
    m->show();
    if (showtip)
      m->showTipOnStart();
    m->setAutoClose(auto_close);
  }

  int ret = a->exec();

 //// Temporary code, waiting for Qt to do this properly

  // Delete all toplevel widgets that have WDestructiveClose
  TQWidgetList *list = TQApplication::topLevelWidgets();
  // remove all toplevel widgets that have a parent (i.e. they
  // got WTopLevel explicitly), they'll be deleted by the parent
  list->first();
  while( list->current())
  {
    if( list->current()->parentWidget() != NULL || !list->current()->testWFlags( TQt::WDestructiveClose ) )
    {
        list->remove();
        continue;
    }
    list->next();
  }
  TQWidgetListIt it(*list);
  TQWidget * w;
  while( (w=it.current()) != 0 ) {
     ++it;
     delete w;
  }
  delete list;
  
  delete a;

  return ret;
}
Example #5
0
void BaseTrackPlayerImpl::slotFinishLoading(TrackPointer pTrackInfoObject)
{
    m_replaygainPending = false;
    // Read the tags if required
    if (!m_pLoadedTrack->getHeaderParsed()) {
        m_pLoadedTrack->parse(false);
    }

    // m_pLoadedTrack->setPlayedAndUpdatePlaycount(true); // Actually the song is loaded but not played

    // Update the BPM and duration values that are stored in ControlObjects
    m_pDuration->set(m_pLoadedTrack->getDuration());
    m_pBPM->slotSet(m_pLoadedTrack->getBpm());
    m_pKey->slotSet(m_pLoadedTrack->getKey());
    m_pReplayGain->slotSet(m_pLoadedTrack->getReplayGain());

    // Update the PlayerInfo class that is used in EngineShoutcast to replace
    // the metadata of a stream
    PlayerInfo::instance().setTrackInfo(getGroup(), m_pLoadedTrack);

    // Reset the loop points.
    m_pLoopInPoint->slotSet(-1);
    m_pLoopOutPoint->slotSet(-1);

    const QList<Cue*> trackCues = pTrackInfoObject->getCuePoints();
    QListIterator<Cue*> it(trackCues);
    while (it.hasNext()) {
        Cue* pCue = it.next();
        if (pCue->getType() == Cue::LOOP) {
            int loopStart = pCue->getPosition();
            int loopEnd = loopStart + pCue->getLength();
            if (loopStart != -1 && loopEnd != -1 && even(loopStart) && even(loopEnd)) {
                m_pLoopInPoint->slotSet(loopStart);
                m_pLoopOutPoint->slotSet(loopEnd);
                break;
            }
        }
    }
    if(m_pConfig->getValueString(ConfigKey("[Mixer Profile]", "EqAutoReset"), 0).toInt()) {
        if (m_pLowFilter != NULL) {
            m_pLowFilter->set(1.0);
        }
        if (m_pMidFilter != NULL) {
            m_pMidFilter->set(1.0);
        }
        if (m_pHighFilter != NULL) {
            m_pHighFilter->set(1.0);
        }
        if (m_pLowFilterKill != NULL) {
            m_pLowFilterKill->set(0.0);
        }
        if (m_pMidFilterKill != NULL) {
            m_pMidFilterKill->set(0.0);
        }
        if (m_pHighFilterKill != NULL) {
            m_pHighFilterKill->set(0.0);
        }
        m_pPreGain->set(1.0);
    }
    int reset = m_pConfig->getValueString(ConfigKey(
            "[Controls]", "SpeedAutoReset"),
            QString("%1").arg(RESET_PITCH)).toInt();
    switch (reset) {
      case RESET_PITCH_AND_SPEED:
        // Note: speed may affect pitch
        if (m_pSpeed != NULL) {
            m_pSpeed->set(0.0);
        }
        // Fallthrough intended
      case RESET_PITCH:
        if (m_pPitchAdjust != NULL) {
            m_pPitchAdjust->set(0.0);
        }
    }
    emit(newTrackLoaded(m_pLoadedTrack));
}
Example #6
0
 void static fill(T_Iterator start, T_Iterator end, unsigned int ref_start, unsigned int query_start, MultiSeed & seeds){
     SeedIterator it(start, end, ref_start, query_start);
     it.get_blocks(seeds);
 }
Expression::Ptr ExpressionFactory::createExpression(const QString &expr,
                                                    const StaticContext::Ptr &context,
                                                    const LanguageAccent lang,
                                                    const SequenceType::Ptr &requiredType,
                                                    const QUrl &queryURI)
{
    pDebug() << Q_FUNC_INFO << queryURI;
    Q_ASSERT(context);
    Q_ASSERT(requiredType);
    Q_ASSERT(queryURI.isValid());

    OptimizationPasses::Coordinator::init();

    ParserContext::Ptr info(new ParserContext(context, lang,
                                              Tokenizer::Ptr(new XQueryTokenizer(expr, queryURI))));

    const int bisonRetval = XPathparse(info.data());

    Q_ASSERT_X(bisonRetval == 0, Q_FUNC_INFO,
               "We shouldn't be able to get an error, because we throw exceptions.");
    Q_UNUSED(bisonRetval); /* Needed when not compiled in debug mode, since bisonRetval won't
                            * be used in the Q_ASSERT_X above. */

    Expression::Ptr result(info->queryBody);

    if(!result)
    {
        context->error(QtXmlPatterns::tr("A library module cannot be evaluated "
                                         "directly. It must be imported from a "
                                         "main module."),
                       ReportContext::XPST0003,
                       QSourceLocation(queryURI, 1, 1));
    }

    /* Here, we type check user declared functions and global variables. This means
     * that variables and functions that are not used are type checked(which they otherwise
     * wouldn't have been), and those which are used, are type-checked twice, unfortunately. */

    const UserFunction::List::const_iterator end(info->userFunctions.constEnd());
    UserFunction::List::const_iterator it(info->userFunctions.constBegin());
    for(; it != end; ++it)
    {
        pDebug() << "-----      User Function Typecheck      -----";
        registerLastPath((*it)->body());

        /* We will most likely call body()->typeCheck() again, once for each callsite. That is, it will
         * be called from UserFunctionCallsite::typeCheck(), which will be called indirectly when
         * we check the query body. */
        const Expression::Ptr typeCheck((*it)->body()->typeCheck(context, (*it)->signature()->returnType()));
        /* We don't have to call (*it)->setBody(typeCheck) here since it's only used directly below. */
        processTreePass(typeCheck, UserFunctionTypeCheck);
        pDebug() << "------------------------------";

        pDebug() << "-----      User Function Compress      -----";
        const Expression::Ptr comp(typeCheck->compress(context));
        (*it)->setBody(comp);
        processTreePass(comp, UserFunctionCompression);
        pDebug() << "------------------------------";
    }

    const VariableDeclaration::Stack::const_iterator vend(info->variables.constEnd());
    VariableDeclaration::Stack::const_iterator vit(info->variables.constBegin());
    for(; vit != vend; ++vit)
    {
        Q_ASSERT(*vit);
        /* If it's already used, it will be typeChecked later on. */
        if((*vit)->isUsed() || (*vit)->type == VariableDeclaration::ExternalVariable)
            continue;

        pDebug() << "-----      Global Variable Typecheck      -----";
        Q_ASSERT((*vit)->expression());
        /* We supply ZeroOrMoreItems, meaning the variable can evaluate to anything. */
        // FIXME which is a source to bugs
        // TODO What about compressing variables?
        const Expression::Ptr
        nev((*vit)->expression()->typeCheck(context, CommonSequenceTypes::ZeroOrMoreItems));
        processTreePass(nev, GlobalVariableTypeCheck);
        pDebug() << "------------------------------";
    }

    pDebug() << "----- Initial AST build. -----";
    processTreePass(result, QueryBodyInitial);
    pDebug() << "------------------------------";

    pDebug() << "-----     Type Check     -----";
    registerLastPath(result);
    result->rewrite(result, result->typeCheck(context, requiredType), context);
    processTreePass(result, QueryBodyTypeCheck);
    pDebug() << "------------------------------";

    pDebug() << "-----      Compress      -----";
    result->rewrite(result, result->compress(context), context);
    processTreePass(result, QueryBodyCompression);
    pDebug() << "------------------------------";

    return result;
}
Example #8
0
/**
 * \brief Add a new mark of the given type. Before the new mark is added, any
 *        existing redundant mark of that type is removed. This simplifies
 *        the cleanup code.
 */
void DeleteMap::AddMark(uint64_t frame, MarkTypes type)
{
    EDIT_CHECK;
    if ((MARK_CUT_START != type) && (MARK_CUT_END != type) &&
        (MARK_PLACEHOLDER != type))
        return;

    frm_dir_map_t::Iterator find_temporary = m_deleteMap.find(frame);
    if (find_temporary != m_deleteMap.end())
    {
        if (MARK_PLACEHOLDER == find_temporary.value())
        {
            // Delete the temporary mark before putting a real mark at its
            // location
            Delete(frame, "");
        }
        else // Don't add a mark on top of a mark
            return;
    }

    int       lasttype  = MARK_UNSET;
    long long lastframe = -1;
    long long remove    = -1;
    QMutableMapIterator<uint64_t, MarkTypes> it(m_deleteMap);

    if (type == MARK_CUT_END)
    {
        // remove curent end marker if it exists
        while (it.hasNext())
        {
            it.next();
            if (it.key() > frame)
            {
                if ((lasttype == MARK_CUT_END) && (lastframe > -1))
                    remove = lastframe;
                break;
            }
            lasttype  = it.value();
            lastframe = it.key();
        }
        if ((remove < 0) && (lasttype == MARK_CUT_END) &&
            (lastframe > -1) && (lastframe < (int64_t)frame))
            remove = lastframe;
    }
    else if (type == MARK_CUT_START)
    {
        // remove curent start marker if it exists
        it.toBack();
        while (it.hasPrevious())
        {
            it.previous();
            if (it.key() <= frame)
            {
                if (lasttype == MARK_CUT_START && (lastframe > -1))
                    remove = lastframe;
                break;
            }
            lasttype  = it.value();
            lastframe = it.key();
        }
        if ((remove < 0) && (lasttype == MARK_CUT_START) &&
            (lastframe > -1) && (lastframe > (int64_t)frame))
            remove = lastframe;
    }

    if (remove > -1)
        Delete((uint64_t)remove);
    Add(frame, type);
    CleanMap();
}
Example #9
0
void CDirectoryListing::RecurseFolder(const char *pzDir, GStringList *strDirs, GStringList *strFiles)
{
	char chSlash = '\\';

	static GString strDot("[dir] .");
	static GString strDotDot("[dir] ..");
	try
	{
		// Sample listing 2 files + 1 directory = "file1.txt*[dir] Temp*file2.txt"
		GString strResults;
		CDirectoryListing dir(pzDir, 2); // directories only
		GStringIterator it(&dir);
		while (it())
		{
			// pzResult will look something like "[dir] SubDir"
			const char *pzResult = it++; 
			if (strDot.Compare(pzResult) != 0 && strDotDot.Compare(pzResult) != 0)
			{
				// pzDir may be "/myPath" to begin with
				GString strFullPath(pzDir);
				if ( strFullPath.GetAt(strFullPath.GetLength() - 1) != '\\' && 
					 strFullPath.GetAt(strFullPath.GetLength() - 1) != '/')
				{
					// pzDir will now end with a slash if it did not already.
					// like "/myPath/" or "c:\myPath\"
					strFullPath += chSlash;
				}

				// add the file name to the complete path we're building
				strFullPath += &pzResult[6]; // skip the "[dir] ", add a string like "SubDir"

				if(strDirs)
				{
					strDirs->AddLast(strFullPath);
				}

				// now add the final slash for a string like this "/myPath/SubDir/"
				strFullPath += chSlash;

				// go down into that directory now.
				RecurseFolder(strFullPath, strDirs, strFiles);
			}
		}

		if(strFiles)
		{
			CDirectoryListing files(pzDir, 1); // files only
			GStringIterator it2(&files);
			while (it2())
			{
				// pzDir may be "/myPath" to begin with
				GString strFullPath(pzDir);
				if ( strFullPath.GetAt(strFullPath.GetLength() - 1) != '\\' && 
					 strFullPath.GetAt(strFullPath.GetLength() - 1) != '/')
				{
					// strFullPath will now end with a slash like "/myPath/" 
					strFullPath += chSlash;
				}


				const char *pzFile = it2++;
				strFullPath += pzFile;
				strFiles->AddLast((const char *)strFullPath);
			}
		}
	}
	catch( GenericException & )
	{
		// ignore the directory we can't access 
		// rErr.GetDescription();
	}
}
Example #10
0
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
    /* WARNING! If you're reading this because you're learning about crypto
       and/or designing a new system that will use merkle trees, keep in mind
       that the following merkle tree algorithm has a serious flaw related to
       duplicate txids, resulting in a vulnerability (CVE-2012-2459).

       The reason is that if the number of hashes in the list at a given time
       is odd, the last one is duplicated before computing the next level (which
       is unusual in Merkle trees). This results in certain sequences of
       transactions leading to the same merkle root. For example, these two
       trees:

                    A               A
                  /  \            /   \
                B     C         B       C
               / \    |        / \     / \
              D   E   F       D   E   F   F
             / \ / \ / \     / \ / \ / \ / \
             1 2 3 4 5 6     1 2 3 4 5 6 5 6

       for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
       6 are repeated) result in the same root hash A (because the hash of both
       of (F) and (F,F) is C).

       The vulnerability results from being able to send a block with such a
       transaction list, with the same merkle root, and the same block hash as
       the original without duplication, resulting in failed validation. If the
       receiving node proceeds to mark that block as permanently invalid
       however, it will fail to accept further unmodified (and thus potentially
       valid) versions of the same block. We defend against this by detecting
       the case where we would hash two identical hashes at the end of the list
       together, and treating that identically to the block having an invalid
       merkle root. Assuming no double-SHA256 collisions, this will detect all
       known ways of changing the transactions without affecting the merkle
       root.
    */
    vMerkleTree.clear();
    vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
    for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
        vMerkleTree.push_back(it->GetHash());
    int j = 0;
    bool mutated = false;
    for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
    {
        for (int i = 0; i < nSize; i += 2)
        {
            int i2 = std::min(i+1, nSize-1);
            if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
                // Two identical hashes at the end of the list at a particular level.
                mutated = true;
            }
            vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
                                       BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
        }
        j += nSize;
    }
    if (fMutated) {
        *fMutated = mutated;
    }
    return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
Example #11
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QXmlStreamReader reader(inputDevice);
    QStack<RCCXmlTag> tokens;

    QString prefix;
    QLocale::Language language = QLocale::c().language();
    QLocale::Country country = QLocale::c().country();
    QString alias;
    int compressLevel = m_compressLevel;
    int compressThreshold = m_compressThreshold;

    while (!reader.atEnd()) {
        QXmlStreamReader::TokenType t = reader.readNext();
        switch (t) {
        case QXmlStreamReader::StartElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty())
                    reader.raiseError(QLatin1String("expected <RCC> tag"));
                else
                    tokens.push(RccTag);
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (tokens.isEmpty() || tokens.top() != RccTag) {
                    reader.raiseError(QLatin1String("unexpected <RESOURCE> tag"));
                } else {
                    tokens.push(ResourceTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    language = QLocale::c().language();
                    country = QLocale::c().country();

                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                        QString attribute = attributes.value(m_strings.ATTRIBUTE_LANG).toString();
                        QLocale lang = QLocale(attribute);
                        language = lang.language();
                        if (2 == attribute.length()) {
                            // Language only
                            country = QLocale::AnyCountry;
                        } else {
                            country = lang.country();
                        }
                    }

                    prefix.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                        prefix = attributes.value(m_strings.ATTRIBUTE_PREFIX).toString();
                    if (!prefix.startsWith(slash))
                        prefix.prepend(slash);
                    if (!prefix.endsWith(slash))
                        prefix += slash;
                }
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (tokens.isEmpty() || tokens.top() != ResourceTag) {
                    reader.raiseError(QLatin1String("unexpected <FILE> tag"));
                } else {
                    tokens.push(FileTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    alias.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                        alias = attributes.value(m_strings.ATTRIBUTE_ALIAS).toString();

                    compressLevel = m_compressLevel;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                        compressLevel = attributes.value(m_strings.ATTRIBUTE_COMPRESS).toString().toInt();

                    compressThreshold = m_compressThreshold;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                        compressThreshold = attributes.value(m_strings.ATTRIBUTE_THRESHOLD).toString().toInt();

                    // Special case for -no-compress. Overrides all other settings.
                    if (m_compressLevel == -2)
                        compressLevel = 0;
                }
            } else {
                reader.raiseError(QString(QLatin1String("unexpected tag: %1")).arg(reader.name().toString()));
            }
            break;

        case QXmlStreamReader::EndElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty() && tokens.top() == RccTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (!tokens.isEmpty() && tokens.top() == ResourceTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (!tokens.isEmpty() && tokens.top() == FileTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            }
            break;

        case QXmlStreamReader::Characters:
            if (reader.isWhitespace())
                break;
            if (tokens.isEmpty() || tokens.top() != FileTag) {
                reader.raiseError(QLatin1String("unexpected text"));
            } else {
                QString fileName = reader.text().toString();
                if (fileName.isEmpty()) {
                    const QString msg = QString::fromLatin1("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                    m_errorDevice->write(msg.toUtf8());
                }

                if (alias.isNull())
                    alias = fileName;

                alias = QDir::cleanPath(alias);
                while (alias.startsWith(QLatin1String("../")))
                    alias.remove(0, 3);
                alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                QString absFileName = fileName;
                if (QDir::isRelativePath(absFileName))
                    absFileName.prepend(currentPath);
                QFileInfo file(absFileName);
                if (!file.exists()) {
                    m_failedResources.push_back(absFileName);
                    const QString msg = QString::fromLatin1("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                    m_errorDevice->write(msg.toUtf8());
                    if (ignoreErrors)
                        continue;
                    else
                        return false;
                } else if (file.isFile()) {
                    const bool arc =
                        addFile(alias,
                                RCCFileInfo(alias.section(slash, -1),
                                            file,
                                            language,
                                            country,
                                            RCCFileInfo::NoFlags,
                                            compressLevel,
                                            compressThreshold)
                                );
                    if (!arc)
                        m_failedResources.push_back(absFileName);
                } else {
                    QDir dir;
                    if (file.isDir()) {
                        dir.setPath(file.filePath());
                    } else {
                        dir.setPath(file.path());
                        dir.setNameFilters(QStringList(file.fileName()));
                        if (alias.endsWith(file.fileName()))
                            alias = alias.left(alias.length()-file.fileName().length());
                    }
                    if (!alias.endsWith(slash))
                        alias += slash;
                    QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                    while (it.hasNext()) {
                        it.next();
                        QFileInfo child(it.fileInfo());
                        if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                            const bool arc =
                                addFile(alias + child.fileName(),
                                        RCCFileInfo(child.fileName(),
                                                    child,
                                                    language,
                                                    country,
                                                    RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(child.fileName());
                        }
                    }
                }
            }
            break;

        default:
            break;
        }
    }

    if (reader.hasError()) {
        if (ignoreErrors)
            return true;
        int errorLine = reader.lineNumber();
        int errorColumn = reader.columnNumber();
        QString errorMessage = reader.errorString();
        QString msg = QString::fromLatin1("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMessage);
        m_errorDevice->write(msg.toUtf8());
        return false;
    }

    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading with QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
Example #12
0
void CustomPriority::loadExampleRules()
{
    QMap<QString, QString> examples;
    examples.insert(tr("Modify priority for an input (Input priority)"),
                    "capturecard.cardid = 1");
    examples.insert(tr("Modify priority for every card on a host"),
                    "capturecard.hostname = 'mythbox'");
    examples.insert(tr("Only one specific channel ID (Channel priority)"),
                    "channel.chanid = '1003' ");
    examples.insert(tr("Only a certain channel number"),
                    "channel.channum = '3' ");
    examples.insert(tr("Only channels that carry a specific station"),
                    "channel.callsign = 'ESPN' ");
    examples.insert(tr("Match related callsigns"),
                    "channel.callsign LIKE 'HBO%' ");
    examples.insert(tr("Only channels marked as commercial free"),
                    QString("channel.commmethod = %1 ")
                        .arg(COMM_DETECT_COMMFREE));
    examples.insert(tr("Modify priority for a station on an input"),
                    "channel.callsign = 'ESPN' AND capturecard.cardid = 2");
    examples.insert(tr("Priority for all matching titles"),
                    "program.title LIKE 'CSI: %' ");
    examples.insert(tr("Only shows marked as HDTV"),
                    "program.hdtv > 0 ");
    examples.insert(tr("Close Captioned priority"),
                    "program.closecaptioned > 0 ");
    examples.insert(tr("New episodes only"),
                    "program.previouslyshown = 0 ");
    examples.insert(tr("Modify unidentified episodes"),
                    "program.generic = 0 ");
    examples.insert(tr("First showing of each episode"),
                    "program.first > 0 ");
    examples.insert(tr("Last showing of each episode"),
                    "program.last > 0 ");
    examples.insert(tr("Priority for any show with End Late time"),
                    "RECTABLE.endoffset > 0 ");
    examples.insert(tr("Priority for a category"),
                    "program.category = 'Reality' ");
    examples.insert(QString("%1 ('movie', 'series', 'sports', 'tvshow')")
                    .arg(tr("Priority for a category type")),
                    "program.category_type = 'sports' ");
    examples.insert(tr("Modify priority by star rating (0.0 to 1.0 for "
                       "movies only)"),
                    "program.stars >= 0.75 ");
    examples.insert(tr("Priority when shown once (complete example)"),
                    "program.first > 0 AND program.last > 0");
    examples.insert(tr("Prefer a host for a storage group (complete example)"),
                    QString("RECTABLE.storagegroup = 'Archive' "
                            "AND capturecard.hostname = 'mythbox' "));
    examples.insert(tr("Priority for HD shows under two hours (complete "
                       "example)"),
                    "program.hdtv > 0 AND program.starttime > "
                    "DATE_SUB(program.endtime, INTERVAL 2 HOUR) ");
    examples.insert(tr("Priority for movies by the year of release (complete "
                       "example)"),
                    "program.category_type = 'movie' "
                    "AND program.airdate >= 2006 ");
    examples.insert(tr("Prefer movies when shown at night (complete example)"),
                    "program.category_type = 'movie' "
                    "AND HOUR(program.starttime) < 6 ");
    examples.insert(tr("Prefer a host for live sports with overtime (complete "
                    "example)"),
                    "RECTABLE.endoffset > 0 "
                    "AND program.category = 'Sports event' "
                    "AND capturecard.hostname = 'mythbox' ");
    examples.insert(tr("Avoid poor signal quality (complete example)"),
                    "capturecard.cardid = 1 AND "
                    "channel.channum IN (3, 5, 39, 66) ");

    QMapIterator<QString, QString> it(examples);
    while (it.hasNext())
    {
        it.next();
        new MythUIButtonListItem(m_clauseList, it.key(),
                                 qVariantFromValue(it.value()));
    }
}
Example #13
0
void hrAdventureScreen::collect()
{
    clearItems();

    const QVector<hrTile> &tiles = isUnderground ? tilesUnderground : tilesGround;
    QList<hrSceneObject> &objects = isUnderground ? objectsUnderground : objectsGround;

    if (tiles.isEmpty())
        return;

    for (int i = viewport.width() - 1; i >= 0; i--)
        for (int j = viewport.height() - 1; j >= 0; j--)
        {
            QPoint pos = coord::toPix(QPoint(i, j));
            QPoint index = viewport.topLeft() + QPoint(i, j);

            const hrTile &tile = tiles.at(index.y() * size.width() + index.x());

            hrGraphicsItem item = itemsTerrain[tile.terrainId];
            item.setCurFrame(tile.terrainFrame);
            item.setMirror(tile.isTerrainHorizontal(), tile.isTerrainVertical());
            item.setPoint(pos);
            addItem(item);

            if (tile.hasRiver())
            {
                hrGraphicsItem item = itemsRiver[tile.riverId];
                item.setCurFrame(tile.riverFrame);
                item.setMirror(tile.isRiverHorizontal(), tile.isRiverVertical());
                item.setPoint(pos);
                addItem(item);
            }
            if (tile.hasRoad())
            {
                drawRoad(tile, pos);
            }
        }

    if (viewport.y() > 0)
    {
        for (int i = 0; i < viewport.width(); i++)
        {
            QPoint pos = coord::toPix(QPoint(i, -1));
            QPoint index = viewport.topLeft() + QPoint(i, -1);

            const hrTile &tile = tiles.at(index.y() * size.width() + index.x());

            if (tile.hasRoad())
            {
                drawRoad(tile, pos);
            }
        }
    }

    QMutableListIterator<hrSceneObject> it(objects);

    while (it.hasNext())
    {
        hrSceneObject &obj = it.next();

        if (viewport.intersects(obj.getRect()))
        {
            QPoint pos = coord::toPix(obj.getPoint() - viewport.topLeft());
            hrGraphicsItem item = itemsObject[obj.getId()];
            item.setCurFrame(isAnimate ? obj.getNextFrame() : obj.getCurFrame());
            item.setPoint(pos);
            addItem(item);
        }
    }

    isAnimate = false;
}
Example #14
0
void RegionLoad::UpdateView()
{
	/*
	Tests the intersection of all regions with the view (if moved) 
	Call CreateActors of the areas that began to intercept and    
	DestroyActors of the areas that are not more intercepting.
	*/
	
	//The coordinates changes solve the bug in activation-problem_view_parent.ged
	//(don't load left region)

	//Make sure view don't will shake
	KrImage *pImageView = GameControl::Get()->GetViewActor()->getImage();
	Axis *pAxis = GameControl::Get()->GetAxis();

	if(pImageView->IsInvalid(true)) 
	{
		//Solve the alpha14.ged bug
		pImageView->CalcCompositeTransform();
		engine->Tree()->Walk(pImageView, true, true);
	}
	else
	{
		pImageView->CalcTransform();
	}

	//Get view bounds
	KrRect rectView = pImageView->Bounds(), viewPos;

	//Get view in screen and axis coordinates
	KrVector2T< GlFixed > screen, axis;
	pImageView->ObjectToScreen(0, 0, &screen);
	pAxis->getImage()->ScreenToObject( screen.x.ToInt(), screen.y.ToInt(), &axis );

	//Make sure rect is (0, 0, ...)
	rectView.Translate(-rectView.xmin, -rectView.ymin);

	//Translate to correct position
	rectView.Translate(axis.x.ToInt(), axis.y.ToInt());


	//Solve the bug: "PocketPC don't load checkers.ged"
	viewPos.Set(rectView.xmin, rectView.ymin, 
				//zeroViewPos.x.ToInt(), zeroViewPos.y.ToInt(),
				0, 0);

	

	if(viewPos != viewPosAnt)
	{		
		MapRegions createdRegions, destroyedRegions;

/*#ifdef DEBUG
		GLOUTPUT( " View pos: (%ld, %ld)\n",  rectView.xmin, rectView.ymin);
#endif*/

		MapRegionsIterator it(regions);
		RegionLoad *pRegion;
		for( it.Begin(); !it.Done(); it.Next() )
		{
			pRegion = *it.Key();

			pRegion->getImage()->CalcTransform();
			KrRect rectRegion = pRegion->getImage()->Bounds();
			rectRegion.Translate(-rectRegion.xmin, -rectRegion.ymin);

			//To axis coordinate
			pRegion->getImage()->ObjectToScreen(0, 0, &screen);
			pAxis->getImage()->ScreenToObject( screen.x.ToInt(), screen.y.ToInt(), &axis );
			rectRegion.Translate(axis.x.ToInt()*pAxis->getScale(), axis.y.ToInt()*pAxis->getScale());

			//View and region in axis coordinates

			if(rectView.Intersect(rectRegion))
			{
				if(!pRegion->bRegionInView)
				{
					createdRegions.Add(pRegion, 1);
				}				
			}
			else
			{
				if(pRegion->bRegionInView)
				{
					destroyedRegions.Add(pRegion, 1);				
				}
			}
		}

		//Destroy actors from regions outside the view
		//Solve the Move to Region.ged when add the 'sad' actor to two default regions 
		//(some times)

		MapRegionsIterator it1(destroyedRegions);
		
		for(it1.Begin(); !it1.Done(); it1.Next())
		{
			pRegion = *it1.Key();
			
			pRegion->DestroyActors();
			if(defaultRegion == pRegion)
				InvalidateDefaultRegion();
		}

		//Call OnCreate after destroy old actors
		//Solve the Move to Region 2.ged actor move to a wrong position
		MapRegionsIterator it2(createdRegions);
		
		for(it2.Begin(); !it2.Done(); it2.Next())
		{
			pRegion = *it2.Key();			
			RegionLoad *pOldDefaultRegion = defaultRegion;
			SetDefaultRegion(pRegion);
			
			pRegion->CreateActors();
					
			RemoveCommonActorsFromOldDefaultRegion(pOldDefaultRegion);
		}
		
		viewPosAnt = viewPos;
	}






}
Example #15
0
void staticArrayStreamer(const ArrayData* ad, std::ostream& out) {
  if (ad->isVecArray()) out << "vec(";
  else if (ad->isDict()) out << "dict(";
  else if (ad->isKeyset()) out << "keyset(";
  else {
    assert(ad->isPHPArray());
    out << "array(";
  }

  if (!ad->empty()) {
    bool comma = false;
    for (ArrayIter it(ad); !it.end(); it.next()) {
      if (comma) {
        out << ",";
      } else {
        comma = true;
      }
      Variant key = it.first();

      if (!ad->isVecArray() && !ad->isKeyset()) {
        // Key.
        if (isIntType(key.getType())) {
          out << *key.getInt64Data();
        } else if (isStringType(key.getType())) {
          out << "\""
              << escapeStringForCPP(key.getStringData()->data(),
                                    key.getStringData()->size())
              << "\"";
        } else {
          assert(false);
        }

        out << "=>";
      }

      Variant val = it.second();

      // Value.
      [&] {
        switch (val.getType()) {
          case KindOfUninit:
          case KindOfNull:
            out << "null";
            return;
          case KindOfBoolean:
            out << (val.toBoolean() ? "true" : "false");
            return;
          case KindOfInt64:
            out << *val.getInt64Data();
            return;
          case KindOfDouble:
            out << *val.getDoubleData();
            return;
          case KindOfPersistentString:
          case KindOfString:
            out << "\""
                << escapeStringForCPP(val.getStringData()->data(),
                                      val.getStringData()->size())
                << "\"";
            return;
          case KindOfPersistentVec:
          case KindOfVec:
          case KindOfPersistentDict:
          case KindOfDict:
          case KindOfPersistentKeyset:
          case KindOfKeyset:
          case KindOfPersistentArray:
          case KindOfArray:
            staticArrayStreamer(val.getArrayData(), out);
            return;
          case KindOfObject:
          case KindOfResource:
          case KindOfRef:
          case KindOfClass:
            not_reached();
        }
      }();
    }
  }
  out << ")";
}
Example #16
0
Container::Container(unsigned id, const char *cfg)
{
    m_bInit   = false;
    m_bInSize = false;
    m_bStatusSize = false;
    m_bBarChanged = false;
    m_bReceived = false;
    m_bNoSwitch = false;
    m_bNoRead   = false;
    m_wnds		= NULL;
    m_tabBar	= NULL;

    SET_WNDPROC("container")
    setWFlags(WDestructiveClose);

    if (cfg && *cfg){
        Buffer config;
        config << "[Title]\n" << cfg;
        config.setWritePos(0);
        config.getSection();
        load_data(containerData, &data, &config);
    }else{
        load_data(containerData, &data, NULL);
    }

    bool bPos = true;
    if (cfg == NULL){
        setId(id);
        memcpy(data.barState, CorePlugin::m_plugin->data.containerBar, sizeof(data.barState));
        memcpy(data.geometry, CorePlugin::m_plugin->data.containerGeo, sizeof(data.geometry));
        if ((data.geometry[WIDTH].value == (unsigned long)-1) || (data.geometry[HEIGHT].value == (unsigned long)-1)){
            QWidget *desktop = QApplication::desktop();
            data.geometry[WIDTH].value = desktop->width() / 3;
            data.geometry[HEIGHT].value = desktop->height() / 3;
        }
        bPos = false;
        if ((data.geometry[TOP].value != (unsigned long)-1) || (data.geometry[LEFT].value != (unsigned long)-1)){
            bPos = true;
            QWidgetList  *list = QApplication::topLevelWidgets();
            for (int i = 0; i < 2; i++){
                bool bOK = true;
                QWidgetListIt it(*list);
                QWidget * w;
                while ((w = it.current()) != NULL){
                    if (w == this){
                        ++it;
                        continue;
                    }
                    if (w->inherits("Container")){
                        int dw = w->pos().x() - data.geometry[LEFT].value;
                        int dh = w->pos().y() - data.geometry[TOP].value;
                        if (dw < 0) dw = -dw;
                        if (dh < 0) dh = -dh;
                        if ((dw < 3) && (dh < 3)){
                            int nl = data.geometry[LEFT].value;
                            int nt = data.geometry[TOP].value;
                            nl += 21;
                            nt += 20;
                            QWidget *desktop = QApplication::desktop();
                            if (nl + (int)data.geometry[WIDTH].value > desktop->width())
                                nl = 0;
                            if (nt + (int)data.geometry[WIDTH].value > desktop->width())
                                nt = 0;
                            if ((nl != (int)data.geometry[LEFT].value) && (nt != (int)data.geometry[TOP].value)){
                                data.geometry[LEFT].value = nl;
                                data.geometry[TOP].value  = nt;
                                bOK = false;
                            }
                        }
                    }
                    ++it;
                }
                if (bOK)
                    break;
            }
            delete list;
        }
        setStatusSize(CorePlugin::m_plugin->getContainerStatusSize());
    }
    m_bInSize = true;
    restoreGeometry(this, data.geometry, bPos, true);
    m_bInSize = false;
}
bool NativeInputWindowHandle::updateInfo()
{
    AutoPtr<IInputWindowHandle> obj;
    mObjWeak->Resolve(EIID_IInputWindowHandle, (IInterface**)&obj);
    if (!obj) {
        releaseInfo();
        return false;
    }

    if (!mInfo) {
        mInfo = new android::InputWindowInfo();
    }
    else {
        mInfo->touchableRegion.clear();
    }

    Elastos::Droid::Server::Input::InputWindowHandle* handle =
            (Elastos::Droid::Server::Input::InputWindowHandle*)obj.Get();
    AutoPtr<IInputChannel> inputChannelObj = handle->mInputChannel;
    if (inputChannelObj) {
        Handle64 ptr;
        inputChannelObj->GetNativeInputChannel(&ptr);
        NativeInputChannel* nativeInputChannel = reinterpret_cast<NativeInputChannel*>(ptr);
        mInfo->inputChannel = nativeInputChannel != NULL ? nativeInputChannel->getInputChannel() : NULL;
    }
    else {
        mInfo->inputChannel.clear();
    }

    if (!handle->mName.IsNull()) {
        mInfo->name.setTo(handle->mName.string());
    }
    else {
        mInfo->name.setTo("<null>");
    }

    mInfo->layoutParamsFlags = handle->mLayoutParamsFlags;
    mInfo->layoutParamsType = handle->mLayoutParamsType;
    mInfo->dispatchingTimeout = handle->mDispatchingTimeoutNanos;
    mInfo->frameLeft = handle->mFrameLeft;
    mInfo->frameTop = handle->mFrameTop;
    mInfo->frameRight = handle->mFrameRight;
    mInfo->frameBottom = handle->mFrameBottom;
    mInfo->scaleFactor = handle->mScaleFactor;

    AutoPtr<IRegion> regionObj = handle->mTouchableRegion;
    if (regionObj) {
        Int64 regionHandle;
        regionObj->GetNativeRegion((Handle64*)&regionHandle);
        SkRegion* region = reinterpret_cast<SkRegion*>(regionHandle);
        SkASSERT(region != NULL);

        for (SkRegion::Iterator it(*region); !it.done(); it.next()) {
            const SkIRect& rect = it.rect();
            mInfo->addTouchableRegion(android::Rect(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom));
        }
    }

    mInfo->visible = handle->mVisible;
    mInfo->canReceiveKeys = handle->mCanReceiveKeys;
    mInfo->hasFocus = handle->mHasFocus;
    mInfo->hasWallpaper = handle->mHasWallpaper;
    mInfo->paused = handle->mPaused;
    mInfo->layer = handle->mLayer;
    mInfo->ownerPid = handle->mOwnerPid;
    mInfo->ownerUid = handle->mOwnerUid;
    mInfo->inputFeatures = handle->mInputFeatures;
    mInfo->displayId = handle->mDisplayId;

    return true;
}
Example #18
0
//Do the interpolation calculations
bool SIM_SnowSolver::solveGasSubclass(SIM_Engine &engine, SIM_Object *obj, SIM_Time time, SIM_Time framerate){

	/// STEP #0: Retrieve all data objects from Houdini

	//Scalar params
	freal particle_mass = getPMass();
	freal YOUNGS_MODULUS = getYoungsModulus();
	freal POISSONS_RATIO = getPoissonsRatio();
	freal CRIT_COMPRESS = getCritComp();
	freal CRIT_STRETCH = getCritStretch();
	freal FLIP_PERCENT = getFlipPercent();
	freal HARDENING = getHardening();
	freal CFL = getCfl();
	freal COF = getCof();
	freal division_size = getDivSize();
	freal max_vel = getMaxVel();
	//Vector params
	vector3 GRAVITY = getGravity();
	vector3 bbox_min_limit = getBboxMin();
	vector3 bbox_max_limit = getBboxMax();

	//Particle params
	UT_String s_p, s_vol, s_den, s_vel, s_fe, s_fp;
	getParticles(s_p);
	getPVol(s_vol);
	getPD(s_den);
	getPVel(s_vel);
	getPFe(s_fe);
	getPFp(s_fp);

	SIM_Geometry* geometry = (SIM_Geometry*) obj->getNamedSubData(s_p);
	if (!geometry) return true;
	
	//Get particle data
	//Do we use the attribute name???
	// GU_DetailHandle gdh = geometry->getGeometry().getWriteableCopy();
	GU_DetailHandle gdh = geometry->getOwnGeometry();
	const GU_Detail* gdp_in = gdh.readLock(); // Must unlock later
	GU_Detail* gdp_out = gdh.writeLock();

	GA_RWAttributeRef p_ref_position = gdp_out->findPointAttribute("P");
	GA_RWHandleT<vector3> p_position(p_ref_position.getAttribute());

	GA_RWAttributeRef p_ref_volume = gdp_out->findPointAttribute(s_vol);
	GA_RWHandleT<freal> p_volume(p_ref_volume.getAttribute());

	GA_RWAttributeRef p_ref_density = gdp_out->findPointAttribute(s_den);
	GA_RWHandleT<freal> p_density(p_ref_density.getAttribute());

	GA_RWAttributeRef p_ref_vel = gdp_out->findPointAttribute(s_vel);
	GA_RWHandleT<vector3> p_vel(p_ref_vel.getAttribute());

	GA_RWAttributeRef p_ref_Fe = gdp_out->findPointAttribute(s_fe);
	GA_RWHandleT<matrix3> p_Fe(p_ref_Fe.getAttribute());

	GA_RWAttributeRef p_ref_Fp = gdp_out->findPointAttribute(s_fp);
	GA_RWHandleT<matrix3> p_Fp(p_ref_Fp.getAttribute());

	//EVALUATE PARAMETERS
	freal mu = YOUNGS_MODULUS/(2+2*POISSONS_RATIO);
	freal lambda = YOUNGS_MODULUS*POISSONS_RATIO/((1+POISSONS_RATIO)*(1-2*POISSONS_RATIO));

	//Get grid data
	SIM_ScalarField *g_mass_field;
	SIM_DataArray g_mass_data;
	getMatchingData(g_mass_data, obj, MPM_G_MASS);	
	g_mass_field = SIM_DATA_CAST(g_mass_data(0), SIM_ScalarField);

	SIM_VectorField *g_nvel_field;
	SIM_DataArray g_nvel_data;
	getMatchingData(g_nvel_data, obj, MPM_G_NVEL);
	g_nvel_field = SIM_DATA_CAST(g_nvel_data(0), SIM_VectorField);

	SIM_VectorField *g_ovel_field;
	SIM_DataArray g_ovel_data;
	getMatchingData(g_ovel_data, obj, MPM_G_OVEL);
	g_ovel_field = SIM_DATA_CAST(g_ovel_data(0), SIM_VectorField);

	SIM_ScalarField *g_active_field;
	SIM_DataArray g_active_data;
	getMatchingData(g_active_data, obj, MPM_G_ACTIVE);	
	g_active_field = SIM_DATA_CAST(g_active_data(0), SIM_ScalarField);

	SIM_ScalarField *g_density_field;
	SIM_DataArray g_density_data;
	getMatchingData(g_density_data, obj, MPM_G_DENSITY);	
	g_density_field = SIM_DATA_CAST(g_density_data(0), SIM_ScalarField);

	SIM_ScalarField *g_col_field;
	SIM_DataArray g_col_data;
	getMatchingData(g_col_data, obj, MPM_G_COL);	
	g_col_field = SIM_DATA_CAST(g_col_data(0), SIM_ScalarField);

	SIM_VectorField *g_colVel_field;
	SIM_DataArray g_colVel_data;
	getMatchingData(g_colVel_data, obj, MPM_G_COLVEL);	
	g_colVel_field = SIM_DATA_CAST(g_colVel_data(0), SIM_VectorField);

	SIM_VectorField *g_extForce_field;
	SIM_DataArray g_extForce_data;
	getMatchingData(g_extForce_data, obj, MPM_G_EXTFORCE);	
	g_extForce_field = SIM_DATA_CAST(g_extForce_data(0), SIM_VectorField);
	
	UT_VoxelArrayF
		*g_mass = g_mass_field->getField()->fieldNC(),
		*g_nvelX = g_nvel_field->getField(0)->fieldNC(),
		*g_nvelY = g_nvel_field->getField(1)->fieldNC(),
		*g_nvelZ = g_nvel_field->getField(2)->fieldNC(),
		*g_ovelX = g_ovel_field->getField(0)->fieldNC(),
		*g_ovelY = g_ovel_field->getField(1)->fieldNC(),
		*g_ovelZ = g_ovel_field->getField(2)->fieldNC(),
		*g_colVelX = g_colVel_field->getField(0)->fieldNC(),
		*g_colVelY = g_colVel_field->getField(1)->fieldNC(),
		*g_colVelZ = g_colVel_field->getField(2)->fieldNC(),
		*g_extForceX = g_extForce_field->getField(0)->fieldNC(),
		*g_extForceY = g_extForce_field->getField(1)->fieldNC(),
		*g_extForceZ = g_extForce_field->getField(2)->fieldNC(),
		*g_col = g_col_field->getField()->fieldNC(),
		*g_active = g_active_field->getField()->fieldNC();

	int point_count = gdp_out->getPointRange().getEntries();
	std::vector<boost::array<freal,64> > p_w(point_count);
	std::vector<boost::array<vector3,64> > p_wgh(point_count);

	//Get world-to-grid conversion ratios
	//Particle's grid position can be found via (pos - grid_origin)/voxel_dims
	vector3
		voxel_dims = g_mass_field->getVoxelSize(),
		grid_origin = g_mass_field->getOrig(),
		grid_divs = g_mass_field->getDivisions();
	//Houdini uses voxel centers for grid nodes, rather than grid corners
	grid_origin += voxel_dims/2.0;
	freal voxelArea = voxel_dims[0]*voxel_dims[1]*voxel_dims[2];
	
	/*
	//Reset grid
	for(int iX=0; iX < grid_divs[0]; iX++){
		for(int iY=0; iY < grid_divs[1]; iY++){
			for(int iZ=0; iZ < grid_divs[2]; iZ++){
				g_mass->setValue(iX,iY,iZ,0);
				g_active->setValue(iX,iY,iZ,0);
				g_ovelX->setValue(iX,iY,iZ,0);
				g_ovelY->setValue(iX,iY,iZ,0);
				g_ovelZ->setValue(iX,iY,iZ,0);
				g_nvelX->setValue(iX,iY,iZ,0);
				g_nvelY->setValue(iX,iY,iZ,0);
				g_nvelZ->setValue(iX,iY,iZ,0);
			}
		}
	}
	*/

	/// STEP #1: Transfer mass to grid

	if (p_position.isValid()){

		//Iterate through particles
		for (GA_Iterator it(gdp_out->getPointRange()); !it.atEnd(); it.advance()){
			int pid = it.getOffset();
							
			//Get grid position
			vector3 gpos = (p_position.get(pid) - grid_origin)/voxel_dims;
			int p_gridx = (int) gpos[0], p_gridy = (int) gpos[1], p_gridz = (int) gpos[2];
			//g_mass_field->posToIndex(p_position.get(pid),p_gridx,p_gridy,p_gridz);
			freal particle_density = p_density.get(pid);
			//Compute weights and transfer mass
			for (int idx=0, z=p_gridz-1, z_end=z+3; z<=z_end; z++){
				//Z-dimension interpolation
				freal z_pos = gpos[2]-z,
					wz = SIM_SnowSolver::bspline(z_pos),
					dz = SIM_SnowSolver::bsplineSlope(z_pos);
				for (int y=p_gridy-1, y_end=y+3; y<=y_end; y++){
					//Y-dimension interpolation
					freal y_pos = gpos[1]-y,
						wy = SIM_SnowSolver::bspline(y_pos),
						dy = SIM_SnowSolver::bsplineSlope(y_pos);
					for (int x=p_gridx-1, x_end=x+3; x<=x_end; x++, idx++){
						//X-dimension interpolation
						freal x_pos = gpos[0]-x,
							wx = SIM_SnowSolver::bspline(x_pos),
							dx = SIM_SnowSolver::bsplineSlope(x_pos);
						
						//Final weight is dyadic product of weights in each dimension
						freal weight = wx*wy*wz;
						p_w[pid-1][idx] = weight;

						//Weight gradient is a vector of partial derivatives
						p_wgh[pid-1][idx] = vector3(dx*wy*wz, wx*dy*wz, wx*wy*dz)/voxel_dims;

						//Interpolate mass
						freal node_mass = g_mass->getValue(x,y,z);
						node_mass += weight*particle_mass;
						g_mass->setValue(x,y,z,node_mass);
					}
				}
			}
		}
	}
	
	/// STEP #2: First timestep only - Estimate particle volumes using grid mass

	/*
	if (time == 0.0){
		//Iterate through particles
		for (GA_Iterator it(gdp_out->getPointRange()); !it.atEnd(); it.advance()){
			int pid = it.getOffset();
			freal density = 0;

			//Get grid position
			int p_gridx = 0, p_gridy = 0, p_gridz = 0;
			vector3 gpos = (p_position.get(pid) - grid_origin)/voxel_dims;
			int p_gridx = (int) gpos[0], p_gridy = (int) gpos[1], p_gridz = (int) gpos[2];
			//g_nvel_field->posToIndex(0,p_position.get(pid),p_gridx,p_gridy,p_gridz);
			//Transfer grid density (within radius) to particles
			for (int idx=0, z=p_gridz-1, z_end=z+3; z<=z_end; z++){
				for (int y=p_gridy-1, y_end=y+3; y<=y_end; y++){
					for (int x=p_gridx-1, x_end=x+3; x<=x_end; x++, idx++){
						freal w = p_w[pid-1][idx];
						if (w > EPSILON){
							//Transfer density
							density += w * g_mass->getValue(x,y,z);
						}
					}
				}
			}
			
			density /= voxelArea;
			p_density.set(pid,density);
			p_volume.set(pid, particle_mass/density);
		}
	}
	//*/
	
	/// STEP #3: Transfer velocity to grid

	//This must happen after transferring mass, to conserve momentum
	//Iterate through particles and transfer
	for (GA_Iterator it(gdp_in->getPointRange()); !it.atEnd(); it.advance()){
		int pid = it.getOffset();
		vector3 vel_fac = p_vel.get(pid)*particle_mass;

		//Get grid position
		vector3 gpos = (p_position.get(pid) - grid_origin)/voxel_dims;
		int p_gridx = (int) gpos[0], p_gridy = (int) gpos[1], p_gridz = (int) gpos[2];
		//g_nvel_field->posToIndex(0,p_position.get(pid),p_gridx,p_gridy,p_gridz);

		//Transfer to grid nodes within radius
		for (int idx=0, z=p_gridz-1, z_end=z+3; z<=z_end; z++){
			for (int y=p_gridy-1, y_end=y+3; y<=y_end; y++){
				for (int x=p_gridx-1, x_end=x+3; x<=x_end; x++, idx++){
					freal w = p_w[pid-1][idx];
					if (w > EPSILON){
						freal nodex_vel = g_ovelX->getValue(x,y,z) + vel_fac[0]*w;
						freal nodey_vel = g_ovelY->getValue(x,y,z) + vel_fac[1]*w;
						freal nodez_vel = g_ovelZ->getValue(x,y,z) + vel_fac[2]*w;
						g_ovelX->setValue(x,y,z,nodex_vel);
						g_ovelY->setValue(x,y,z,nodey_vel);
						g_ovelZ->setValue(x,y,z,nodez_vel);			
						g_active->setValue(x,y,z,1.0);			
					}
				}
			}
		}
	}
	//Division is slow (maybe?); we only want to do divide by mass once, for each active node
	for(int iX=0; iX < grid_divs[0]; iX++){
		for(int iY=0; iY < grid_divs[1]; iY++){
			for(int iZ=0; iZ < grid_divs[2]; iZ++){
				//Only check nodes that have mass
				if (g_active->getValue(iX,iY,iZ)){
					freal node_mass = 1/(g_mass->getValue(iX,iY,iZ));
					g_ovelX->setValue(iX,iY,iZ,(g_ovelX->getValue(iX,iY,iZ)*node_mass));
					g_ovelY->setValue(iX,iY,iZ,(g_ovelY->getValue(iX,iY,iZ)*node_mass));
					g_ovelZ->setValue(iX,iY,iZ,(g_ovelZ->getValue(iX,iY,iZ)*node_mass));
				}
			}
		}
	}
	
	/// STEP #4: Compute new grid velocities

	//Temporary variables for plasticity and force calculation
	//We need one set of variables for each thread that will be running
	eigen_matrix3 def_elastic, def_plastic, energy, svd_u, svd_v;
	Eigen::JacobiSVD<eigen_matrix3, Eigen::NoQRPreconditioner> svd;
	eigen_vector3 svd_e;
	matrix3  HDK_def_plastic, HDK_def_elastic, HDK_energy;
	freal* data_dp = HDK_def_plastic.data();
	freal* data_de = HDK_def_elastic.data();
	freal* data_energy = HDK_energy.data();
	//Map Eigen matrices to HDK matrices
	Eigen::Map<eigen_matrix3> data_dp_map(data_dp);
	Eigen::Map<eigen_matrix3> data_de_map(data_de);
	Eigen::Map<eigen_matrix3> data_energy_map(data_energy);	

	//Compute force at each particle and transfer to Eulerian grid
	//We use "nvel" to hold the grid force, since that variable is not in use
	for (GA_Iterator it(gdp_in->getPointRange()); !it.atEnd(); it.advance()){
		int pid = it.getOffset();
		
		//Apply plasticity to deformation gradient, before computing forces
		//We need to use the Eigen lib to do the SVD; transfer houdini matrices to Eigen matrices
		HDK_def_plastic = p_Fp.get(pid);
		HDK_def_elastic = p_Fe.get(pid);
		def_plastic = Eigen::Map<eigen_matrix3>(data_dp);
		def_elastic = Eigen::Map<eigen_matrix3>(data_de);
		
		//Compute singular value decomposition (uev*)
		svd.compute(def_elastic, Eigen::ComputeFullV | Eigen::ComputeFullU);
		svd_e = svd.singularValues();
		svd_u = svd.matrixU();
		svd_v = svd.matrixV();
		//Clamp singular values
		for (int i=0; i<3; i++){
			if (svd_e[i] < CRIT_COMPRESS) 
				svd_e[i] = CRIT_COMPRESS;
			else if (svd_e[i] > CRIT_STRETCH)
				svd_e[i] = CRIT_STRETCH;
		}
		//Put SVD back together for new elastic and plastic gradients
		def_plastic = svd_v * svd_e.asDiagonal().inverse() * svd_u.transpose() * def_elastic * def_plastic;
		svd_v.transposeInPlace();
		def_elastic = svd_u * svd_e.asDiagonal() * svd_v;
		
		//Now compute the energy partial derivative (which we use to get force at each grid node)
		energy = 2*mu*(def_elastic - svd_u*svd_v)*def_elastic.transpose();
		//Je is the determinant of def_elastic (equivalent to svd_e.prod())
		freal Je = svd_e.prod(),
			contour = lambda*Je*(Je-1),
			jp = def_plastic.determinant(),
			particle_vol = p_volume.get(pid);
		for (int i=0; i<3; i++)
			energy(i,i) += contour;
		energy *=  particle_vol * exp(HARDENING*(1-jp));
		
		//Transfer Eigen matrices back to HDK
		data_dp_map = def_plastic;
		data_de_map = def_elastic;
		data_energy_map = energy;
		
		p_Fp.set(pid,HDK_def_plastic);
		p_Fe.set(pid,HDK_def_elastic);
		
		//Transfer energy to surrounding grid nodes
		vector3 gpos = (p_position.get(pid) - grid_origin)/voxel_dims;
		int p_gridx = (int) gpos[0], p_gridy = (int) gpos[1], p_gridz = (int) gpos[2];
		for (int idx=0, z=p_gridz-1, z_end=z+3; z<=z_end; z++){
			for (int y=p_gridy-1, y_end=y+3; y<=y_end; y++){
				for (int x=p_gridx-1, x_end=x+3; x<=x_end; x++, idx++){
					freal w = p_w[pid-1][idx];
					if (w > EPSILON){
						vector3 ngrad = p_wgh[pid-1][idx];
						g_nvelX->setValue(x,y,z,g_nvelX->getValue(x,y,z) + ngrad.dot(HDK_energy[0]));
						g_nvelY->setValue(x,y,z,g_nvelY->getValue(x,y,z) + ngrad.dot(HDK_energy[1]));
						g_nvelZ->setValue(x,y,z,g_nvelZ->getValue(x,y,z) + ngrad.dot(HDK_energy[2]));						
					}
				}
			}
		}
	}

	//Use new forces to solve for new velocities
	for(int iX=0; iX < grid_divs[0]; iX++){
		for(int iY=0; iY < grid_divs[1]; iY++){
			for(int iZ=0; iZ < grid_divs[2]; iZ++){
				//Only compute for active nodes
				if (g_active->getValue(iX,iY,iZ)){
					freal nodex_ovel = g_ovelX->getValue(iX,iY,iZ);
					freal nodey_ovel = g_ovelY->getValue(iX,iY,iZ);
					freal nodez_ovel = g_ovelZ->getValue(iX,iY,iZ);
					freal forcex = g_nvelX->getValue(iX,iY,iZ);
					freal forcey = g_nvelY->getValue(iX,iY,iZ);
					freal forcez = g_nvelZ->getValue(iX,iY,iZ);
					freal node_mass = 1/(g_mass->getValue(iX,iY,iZ));
					freal ext_forceX = GRAVITY[0] + g_extForceX->getValue(iX,iY,iZ);
					freal ext_forceY = GRAVITY[1] + g_extForceY->getValue(iX,iY,iZ);
					freal ext_forceZ = GRAVITY[2] + g_extForceZ->getValue(iX,iY,iZ);
					nodex_ovel += framerate*(ext_forceX - forcex*node_mass);
					nodey_ovel += framerate*(ext_forceY - forcey*node_mass);
					nodez_ovel += framerate*(ext_forceZ - forcez*node_mass);
					
					//Limit velocity to max_vel
					vector3 g_nvel(nodex_ovel, nodey_ovel, nodez_ovel);
					freal nvelNorm = g_nvel.length();
					if(nvelNorm > max_vel){
						freal velRatio = max_vel/nvelNorm;
						g_nvel*= velRatio;
					}

					g_nvelX->setValue(iX,iY,iZ,g_nvel[0]);
					g_nvelY->setValue(iX,iY,iZ,g_nvel[1]);
					g_nvelZ->setValue(iX,iY,iZ,g_nvel[2]);

				}
			}
		}
	}

	/// STEP #5: Grid collision resolution

	vector3 sdf_normal;
	//*
	for(int iX=1; iX < grid_divs[0]-1; iX++){
		for(int iY=1; iY < grid_divs[1]-1; iY++){
			for(int iZ=1; iZ < grid_divs[2]-1; iZ++){
				if (g_active->getValue(iX,iY,iZ)){
					if (!computeSDFNormal(g_col, iX, iY, iZ, sdf_normal))
						continue;

					//Collider velocity
					vector3 vco(
						g_colVelX->getValue(iX,iY,iZ),
						g_colVelY->getValue(iX,iY,iZ),
						g_colVelZ->getValue(iX,iY,iZ)
					);
					//Grid velocity
					vector3 v(
						g_nvelX->getValue(iX,iY,iZ),
						g_nvelY->getValue(iX,iY,iZ),
						g_nvelZ->getValue(iX,iY,iZ)
					);
					//Skip if bodies are separating
					vector3 vrel = v - vco;
					
					freal vn = vrel.dot(sdf_normal);
					if (vn >= 0) continue;
					//Resolve collisions; also add velocity of collision object to snow velocity
					//Sticks to surface (too slow to overcome static friction)
					vector3 vt = vrel - (sdf_normal*vn);

					freal stick = vn*COF, vt_norm = vt.length();
					if (vt_norm <= -stick)
						vt = vco;
					//Dynamic friction
					else vt += stick*vt/vt_norm + vco;
					
					g_nvelX->setValue(iX,iY,iZ,vt[0]);	
					g_nvelY->setValue(iX,iY,iZ,vt[1]);
					g_nvelZ->setValue(iX,iY,iZ,vt[2]);
				}
			}
		}
	}
	//*/

	/// STEP #6: Transfer grid velocities to particles and integrate
	/// STEP #7: Particle collision resolution

	vector3 pic, flip, col_vel;
	matrix3 vel_grad;
	//Iterate through particles
	for (GA_Iterator it(gdp_in->getPointRange()); !it.atEnd(); it.advance()){
		int pid = it.getOffset();
		//Particle position
		vector3 pos(p_position.get(pid));
		
		//Reset velocity
		pic[0] = 0.0;
		pic[1] = 0.0;
		pic[2] = 0.0;
		flip = p_vel.get(pid);
		vel_grad.zero();
		freal density = 0;

		 //Get grid position
		vector3 gpos = (pos - grid_origin)/voxel_dims;
		int p_gridx = (int) gpos[0], p_gridy = (int) gpos[1], p_gridz = (int) gpos[2];
		for (int idx=0, z=p_gridz-1, z_end=z+3; z<=z_end; z++){
			for (int y=p_gridy-1, y_end=y+3; y<=y_end; y++){
				for (int x=p_gridx-1, x_end=x+3; x<=x_end; x++, idx++){
					freal w = p_w[pid-1][idx];
					if (w > EPSILON){
						const vector3 node_wg = p_wgh[pid-1][idx];
						const vector3 node_nvel(
							g_nvelX->getValue(x,y,z),
							g_nvelY->getValue(x,y,z),
							g_nvelZ->getValue(x,y,z)
						);

						//Transfer velocities
						pic += node_nvel*w;	
						flip[0] += (node_nvel[0] - g_ovelX->getValue(x,y,z))*w;	
						flip[1] += (node_nvel[1]- g_ovelY->getValue(x,y,z))*w;	
						flip[2] += (node_nvel[2] - g_ovelZ->getValue(x,y,z))*w;
						//Transfer density
						density += w * g_mass->getValue(x,y,z);
						//Transfer veloctiy gradient
						vel_grad.outerproductUpdate(1.0, node_nvel, node_wg);
					}
				}
			}
		}

		//Finalize velocity update
		vector3 vel = flip*FLIP_PERCENT + pic*(1-FLIP_PERCENT);
		
		//Reset collision data
		freal col_sdf = 0;
		sdf_normal[0] = 0;
		sdf_normal[1] = 0;
		sdf_normal[2] = 0;
		col_vel[0] = 0;
		col_vel[1] = 0;
		col_vel[2] = 0;
		
		//Interpolate surrounding nodes' SDF info to the particle (trilinear interpolation)

		for (int idx=0, z=p_gridz, z_end=z+1; z<=z_end; z++){
			freal w_z = gpos[2]-z;
			for (int y=p_gridy, y_end=y+1; y<=y_end; y++){
				freal w_zy = w_z*(gpos[1]-y);
				for (int x=p_gridx, x_end=x+1; x<=x_end; x++, idx++){
					freal weight = fabs(w_zy*(gpos[0]-x));
					//cout << w_zy << "," << (gpos[0]-x) << "," << weight << endl;
					vector3 temp_normal;
					computeSDFNormal(g_col, x, y, z, temp_normal);
						//goto SKIP_PCOLLIDE;
					//cout << g_col->getValue(x, y, z) << endl;
					//Interpolate
					sdf_normal += temp_normal*weight;
					col_sdf += g_col->getValue(x, y, z)*weight;
					col_vel[0] += g_colVelX->getValue(x, y, z)*weight;
					col_vel[1] += g_colVelY->getValue(x, y, z)*weight;
					col_vel[2] += g_colVelZ->getValue(x, y, z)*weight;
				}
			}
		}

		//Resolve particle collisions	
		//cout << col_sdf << endl;
		if (col_sdf > 0){
			vector3 vrel = vel - col_vel;
			freal vn = vrel.dot(sdf_normal);
			
			//Skip if bodies are separating
			if (vn < 0){
				
				//Resolve and add velocity of collision object to snow velocity
				//Sticks to surface (too slow to overcome static friction)
				vel = vrel - (sdf_normal*vn);
				freal stick = vn*COF, vel_norm = vel.length();
				if (vel_norm <= -stick)
					vel = col_vel;
				//Dynamic friction
				else vel += stick*vel/vel_norm + col_vel;
			}
		}
		
		SKIP_PCOLLIDE:

		//Finalize density update
		density /= voxelArea;
		p_density.set(pid,density);

		//Update particle position
		pos += framerate*vel;
		//Limit particle position
		int mask = 0;
		/*		
		for (int i=0; i<3; i++){
			if (pos[i] > bbox_max_limit[i]){
				pos[i] = bbox_max_limit[i];
				vel[i] = 0.0;
				mask |= 1 << i;
			}
			else if (pos[i] < bbox_min_limit[i]){
				pos[i] = bbox_min_limit[i];
				vel[i] = 0.0;
				mask |= 1 << i;
			}
		}
		//Slow particle down at bounds (not really necessary...)
		if (mask){
			for (int i=0; i<3; i++){
				if (mask & 0x1)
					vel[i] *= .05;
				mask >>= 1;
			}
		}//*/
		p_vel.set(pid,vel);
		p_position.set(pid,pos);

		//Update particle deformation gradient
		//Note: plasticity is computed on the next timestep...
		vel_grad *= framerate;
		vel_grad(0,0) += 1;
		vel_grad(1,1) += 1;
		vel_grad(2,2) += 1;
		
		p_Fe.set(pid, vel_grad*p_Fe.get(pid));
	}

	gdh.unlock(gdp_out);
    gdh.unlock(gdp_in);
	
	return true;
}
Example #19
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QDomDocument document;
    {
        QString errorMsg;
        int errorLine = 0;
        int errorColumn = 0;
        if (!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) {
            if (ignoreErrors)
                return true;
            const QString msg = QString::fromUtf8("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMsg);
            m_errorDevice->write(msg.toUtf8());
            return false;
        }
    }

    QDomElement domRoot = document.firstChildElement(m_strings.TAG_RCC).toElement();
    if (!domRoot.isNull() && domRoot.tagName() == m_strings.TAG_RCC) {
        for (QDomNode node = domRoot.firstChild(); !node.isNull(); node = node.nextSibling()) {
            if (!node.isElement())
                continue;

            QDomElement child = node.toElement();
            if (!child.isNull() && child.tagName() == m_strings.TAG_RESOURCE) {
                QLocale::Language language = QLocale::c().language();
                QLocale::Country country = QLocale::c().country();

                if (child.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                    QString attribute = child.attribute(m_strings.ATTRIBUTE_LANG);
                    QLocale lang = QLocale(attribute);
                    language = lang.language();
                    if (2 == attribute.length()) {
                        // Language only
                        country = QLocale::AnyCountry;
                    } else {
                        country = lang.country();
                    }
                }

                QString prefix;
                if (child.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                    prefix = child.attribute(m_strings.ATTRIBUTE_PREFIX);
                if (!prefix.startsWith(slash))
                    prefix.prepend(slash);
                if (!prefix.endsWith(slash))
                    prefix += slash;

                for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) {
                    if (res.isElement() && res.toElement().tagName() == m_strings.TAG_FILE) {

                        QString fileName(res.firstChild().toText().data());
                        if (fileName.isEmpty()) {
                            const QString msg = QString::fromUtf8("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                            m_errorDevice->write(msg.toUtf8());
                        }
                        QString alias;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                            alias = res.toElement().attribute(m_strings.ATTRIBUTE_ALIAS);
                        else
                            alias = fileName;

                        int compressLevel = m_compressLevel;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                            compressLevel = res.toElement().attribute(m_strings.ATTRIBUTE_COMPRESS).toInt();
                        int compressThreshold = m_compressThreshold;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                            compressThreshold = res.toElement().attribute(m_strings.ATTRIBUTE_THRESHOLD).toInt();

                        // Special case for -no-compress. Overrides all other settings.
                        if (m_compressLevel == -2)
                            compressLevel = 0;

                        alias = QDir::cleanPath(alias);
                        while (alias.startsWith(QLatin1String("../")))
                            alias.remove(0, 3);
                        alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                        QString absFileName = fileName;
                        if (QDir::isRelativePath(absFileName))
                            absFileName.prepend(currentPath);
                        QFileInfo file(absFileName);
                        if (!file.exists()) {
                            m_failedResources.push_back(absFileName);
                            const QString msg = QString::fromUtf8("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                            m_errorDevice->write(msg.toUtf8());
                            if (ignoreErrors)
                                continue;
                            else
                                return false;
                        } else if (file.isFile()) {
                            const bool arc =
                                addFile(alias,
                                        RCCFileInfo(alias.section(slash, -1),
                                                    file,
                                                    language,
                                                    country,
                                                    RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(absFileName);
                        } else {
                            QDir dir;
                            if (file.isDir()) {
                                dir.setPath(file.filePath());
                            } else {
                                dir.setPath(file.path());
                                dir.setNameFilters(QStringList(file.fileName()));
                                if (alias.endsWith(file.fileName()))
                                    alias = alias.left(alias.length()-file.fileName().length());
                            }
                            if (!alias.endsWith(slash))
                                alias += slash;
                            QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                            while (it.hasNext()) {
                                it.next();
                                QFileInfo child(it.fileInfo());
                                if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                                    const bool arc =
                                        addFile(alias + child.fileName(),
                                                RCCFileInfo(child.fileName(),
                                                            child,
                                                            language,
                                                            country,
                                                            RCCFileInfo::NoFlags,
                                                            compressLevel,
                                                            compressThreshold)
                                                );
                                    if (!arc)
                                        m_failedResources.push_back(child.fileName());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading qith QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
Example #20
0
// This is called from the AnalyserQueue thread
bool AnalyserQueue::doAnalysis(TrackPointer tio, const Mixxx::SoundSourcePointer& pSoundSource) {
    int totalSamples = pSoundSource->length();
    //qDebug() << tio->getFilename() << " has " << totalSamples << " samples.";
    int processedSamples = 0;

    QTime progressUpdateInhibitTimer;
    progressUpdateInhibitTimer.start(); // Inhibit Updates for 60 milliseconds

    int read = 0;
    bool dieflag = false;
    bool cancelled = false;
    int progress; // progress in 0 ... 100

    do {
        ScopedTimer t("AnalyserQueue::doAnalysis block");
        read = pSoundSource->read(kAnalysisBlockSize, m_pSamplesPCM);

        // To compare apples to apples, let's only look at blocks that are the
        // full block size.
        if (read != kAnalysisBlockSize) {
            t.cancel();
        }

        // Safety net in case something later barfs on 0 sample input
        if (read == 0) {
            t.cancel();
            break;
        }

        // If we get more samples than length, ask the analysers to process
        // up to the number we promised, then stop reading - AD
        if (read + processedSamples > totalSamples) {
            qDebug() << "While processing track of length " << totalSamples << " actually got "
                     << read + processedSamples << " samples, truncating analysis at expected length";
            read = totalSamples - processedSamples;
            dieflag = true;
        }

        SampleUtil::convertS16ToFloat32(m_pSamples, m_pSamplesPCM, read);

        QListIterator<Analyser*> it(m_aq);

        while (it.hasNext()) {
            Analyser* an =  it.next();
            //qDebug() << typeid(*an).name() << ".process()";
            an->process(m_pSamples, read);
            //qDebug() << "Done " << typeid(*an).name() << ".process()";
        }

        // emit progress updates
        // During the doAnalysis function it goes only to 100% - FINALIZE_PERCENT
        // because the finalise functions will take also some time
        processedSamples += read;
        //fp div here prevents insane signed overflow
        progress = (int)(((float)processedSamples)/totalSamples *
                         (1000 - FINALIZE_PERCENT));

        if (m_progressInfo.track_progress != progress) {
            if (progressUpdateInhibitTimer.elapsed() > 60) {
                // Inhibit Updates for 60 milliseconds
                emitUpdateProgress(tio, progress);
                progressUpdateInhibitTimer.start();
            }
        }

        // Since this is a background analysis queue, we should co-operatively
        // yield every now and then to try and reduce CPU contention. The
        // analyser queue is CPU intensive so we want to get out of the way of
        // the audio callback thread.
        //QThread::yieldCurrentThread();
        //QThread::usleep(10);

        //has something new entered the queue?
        if (load_atomic(m_aiCheckPriorities)) {
            m_aiCheckPriorities = false;
            if (isLoadedTrackWaiting(tio)) {
                qDebug() << "Interrupting analysis to give preference to a loaded track.";
                dieflag = true;
                cancelled = true;
            }
        }

        if (m_exit) {
            dieflag = true;
            cancelled = true;
        }

        // Ignore blocks in which we decided to bail for stats purposes.
        if (dieflag || cancelled) {
            t.cancel();
        }
    } while(read == kAnalysisBlockSize && !dieflag);

    return !cancelled; //don't return !dieflag or we might reanalyze over and over
}
Example #21
0
int HBFHTTPCorrelator<RequestReaderType, ResponseReaderType, WriterType>::run() {
	HTTPRequest http_request;
	HTTPResponse http_response;
	IPv4Network network;
	NewIPv4FlowMatcher matcher, reverseMatcher;
	bool foundRequest(false), foundResponse(false);
	HTTPResult httpResult;
	HBFHTTPResult hbfhttpResult;
	bool moreRequests(true);
	bool moreResponses(true);

	// prefetch the first HTTP
	ErrorStatus errorStatus;
	if ((errorStatus = _request_reader->read(http_request)) != E_SUCCESS) {
		if (errorStatus != E_EOF) {
			_error = true;
			_errorMsg.assign("Reader: error reading ");
			return 1;
		}
		// no more http data to read. we're done.
		moreRequests = false;
	}

	if ((errorStatus = _response_reader->read(http_response)) != E_SUCCESS) {
		if (errorStatus != E_EOF) {
			_error = true;
			_errorMsg.assign("Reader: error reading ");
			return 1;
		}
		// no more http data to read. we're done.
		moreResponses = false;
	}

	std::deque <HTTPRequest> request_q;
	std::deque <HTTPResponse> response_q;
	TimeStamp windowSize(300, 0); // 5 minutes
	// for each HBFResult
	for (std::set<HBFResult>::const_iterator i(_set->begin());
		 i != _set->end();
		 ++i)
	{
		// fill up the 5 minute window for requests
		while (!request_q.empty() && request_q.front().time() < i->startTime() - windowSize) {
			request_q.pop_front();
		}
		while (moreRequests && http_request.time() <= i -> startTime()) {
			if (http_request.time() >= i->startTime() - windowSize) {
				// in range. push it into the deque
				request_q.push_back(http_request);
			}

			if ((errorStatus = _request_reader->read(http_request)) != E_SUCCESS) {
				if (errorStatus != E_EOF) {
					_error = true;
					_errorMsg.assign("Reader: error reading");
					return 1;
				}

				// no more http_request data to read. we're done.
				moreRequests = false;
			}
		}

		// fill up the 5 minute window for responses
		while (!response_q.empty() && response_q.front().time() < i->startTime() - windowSize) {
			response_q.pop_front();
		}
		while (moreResponses && http_response.time() <= i -> startTime()) {
			if (http_response.time() >= i->startTime() - windowSize) {
				// in range. push it into the deque
				response_q.push_back(http_response);
			}

			if ((errorStatus = _response_reader->read(http_response)) != E_SUCCESS) {
				if (errorStatus != E_EOF) {
					_error = true;
					_errorMsg.assign("Reader: error reading");
					return 1;
				}

				// no more http_response data to read. we're done.
				moreResponses = false;;
			}
		}

		// if there are HTTPs to look at, make flow matcher based on i
		if (!request_q.empty() && !response_q.empty()) {
			matcher.addProtocolRange(std::make_pair(i->protocol(),
													i->protocol()));
			network.rawSet(i->rawSourceIP(), 0xffffffff);
			matcher.addSourceNetwork(network);
			network.rawSet(i->rawDestinationIP(), 0xffffffff);
			matcher.addDestinationNetwork(network);
			matcher.addSourcePortRange(std::make_pair(i->sourcePort(),
													  i->sourcePort()));
			matcher.addDestinationPortRange(std::make_pair(
													i->destinationPort(),
													i->destinationPort()));

			reverseMatcher.addProtocolRange(std::make_pair(i->protocol(),
														   i->protocol()));
			network.rawSet(i->rawDestinationIP(), 0xffffffff);
			reverseMatcher.addSourceNetwork(network);
			network.rawSet(i->rawSourceIP(), 0xffffffff);
			reverseMatcher.addDestinationNetwork(network);
			reverseMatcher.addSourcePortRange(std::make_pair(
													i->destinationPort(),
													i->destinationPort()));
			reverseMatcher.addDestinationPortRange(std::make_pair(
													i->sourcePort(),
													i->sourcePort()));
		}

		// look for the correlated HTTP request.
		foundRequest = foundResponse = false;
		for (std::deque <HTTPRequest>::reverse_iterator it(request_q.rbegin());
			 it != request_q.rend();
			 ++it)
		{
			if (matcher.isMatch(*it) || reverseMatcher.isMatch(*it)) {
				http_request = *it;
				foundRequest = true;
				break;
			}
		}

		for (std::deque <HTTPResponse>::reverse_iterator it(response_q.rbegin());
			 it != response_q.rend();
			 ++it)
		{
			if (matcher.isMatch(*it) || reverseMatcher.isMatch(*it)) {
				http_response = *it;
				foundResponse = true;
				break;
			}
		}

		// prepare the result
		httpResult.clear();
		if (foundRequest) {
			// we found a matching Request.
			httpResult.request(http_request);
		}
		if (foundResponse) {
			// we found a matching Response.
			httpResult.response(http_response);
		}
		hbfhttpResult.assign(*i, httpResult);
		if (!(_writer->write(hbfhttpResult))) {
			_error = true;
			_errorMsg.assign("Writer: ");
			_errorMsg.append(_writer->error());
			return 1;
		}
	}

	return 0;
}
Example #22
0
void AnalyserQueue::run() {
    unsigned static id = 0; //the id of this thread, for debugging purposes
    QThread::currentThread()->setObjectName(QString("AnalyserQueue %1").arg(++id));

    // If there are no analyzers, don't waste time running.
    if (m_aq.size() == 0)
        return;

    m_progressInfo.current_track = TrackPointer();
    m_progressInfo.track_progress = 0;
    m_progressInfo.queue_size = 0;
    m_progressInfo.sema.release(); // Initalise with one

    while (!m_exit) {
        TrackPointer nextTrack = dequeueNextBlocking();

        // It's important to check for m_exit here in case we decided to exit
        // while blocking for a new track.
        if (m_exit)
            return;

        // If the track is NULL, try to get the next one.
        // Could happen if the track was queued but then deleted.
        // Or if dequeueNextBlocking is unblocked by exit == true
        if (!nextTrack) {
            m_qm.lock();
            m_queue_size = m_tioq.size();
            m_qm.unlock();
            if (m_queue_size == 0) {
                emit(queueEmpty()); // emit asynchrony for no deadlock
            }
            continue;
        }

        Trace trace("AnalyserQueue analyzing track");

        // Get the audio
        SoundSourceProxy soundSourceProxy(nextTrack);
        Mixxx::SoundSourcePointer pSoundSource(soundSourceProxy.open());
        if (pSoundSource.isNull()) {
            qWarning() << "Failed to open file for analyzing:" << nextTrack->getLocation();
            continue;
        }

        int iNumSamples = pSoundSource->length();
        int iSampleRate = pSoundSource->getSampleRate();

        if (iNumSamples == 0 || iSampleRate == 0) {
            qWarning() << "Skipping invalid file:" << nextTrack->getLocation();
            continue;
        }

        QListIterator<Analyser*> it(m_aq);
        bool processTrack = false;
        while (it.hasNext()) {
            // Make sure not to short-circuit initialise(...)
            if (it.next()->initialise(nextTrack, iSampleRate, iNumSamples)) {
                processTrack = true;
            }
        }

        m_qm.lock();
        m_queue_size = m_tioq.size();
        m_qm.unlock();

        if (processTrack) {
            emitUpdateProgress(nextTrack, 0);
            bool completed = doAnalysis(nextTrack, pSoundSource);
            if (!completed) {
                //This track was cancelled
                QListIterator<Analyser*> itf(m_aq);
                while (itf.hasNext()) {
                    itf.next()->cleanup(nextTrack);
                }
                queueAnalyseTrack(nextTrack);
                emitUpdateProgress(nextTrack, 0);
            } else {
                // 100% - FINALIZE_PERCENT finished
                emitUpdateProgress(nextTrack, 1000 - FINALIZE_PERCENT);
                // This takes around 3 sec on a Atom Netbook
                QListIterator<Analyser*> itf(m_aq);
                while (itf.hasNext()) {
                    itf.next()->finalise(nextTrack);
                }
                emit(trackDone(nextTrack));
                emitUpdateProgress(nextTrack, 1000); // 100%
            }
        } else {
            emitUpdateProgress(nextTrack, 1000); // 100%
            qDebug() << "Skipping track analysis because no analyzer initialized.";
        }

        m_qm.lock();
        m_queue_size = m_tioq.size();
        m_qm.unlock();
        if (m_queue_size == 0) {
            emit(queueEmpty()); // emit asynchrony for no deadlock
        }
    }
    emit(queueEmpty()); // emit in case of exit;
}
Example #23
0
void BaseTrackPlayerImpl::slotLoadTrack(TrackPointer track, bool bPlay) {
    // Before loading the track, ensure we have access. This uses lazy
    // evaluation to make sure track isn't NULL before we dereference it.
    if (!track.isNull() && !Sandbox::askForAccess(track->getCanonicalLocation())) {
        // We don't have access.
        return;
    }

    //Disconnect the old track's signals.
    if (m_pLoadedTrack) {
        // Save the loops that are currently set in a loop cue. If no loop cue is
        // currently on the track, then create a new one.
        int loopStart = m_pLoopInPoint->get();
        int loopEnd = m_pLoopOutPoint->get();
        if (loopStart != -1 && loopEnd != -1 &&
            even(loopStart) && even(loopEnd) && loopStart <= loopEnd) {
            Cue* pLoopCue = NULL;
            QList<Cue*> cuePoints = m_pLoadedTrack->getCuePoints();
            QListIterator<Cue*> it(cuePoints);
            while (it.hasNext()) {
                Cue* pCue = it.next();
                if (pCue->getType() == Cue::LOOP) {
                    pLoopCue = pCue;
                }
            }
            if (!pLoopCue) {
                pLoopCue = m_pLoadedTrack->addCue();
                pLoopCue->setType(Cue::LOOP);
            }
            pLoopCue->setPosition(loopStart);
            pLoopCue->setLength(loopEnd - loopStart);
        }

        // WARNING: Never. Ever. call bare disconnect() on an object. Mixxx
        // relies on signals and slots to get tons of things done. Don't
        // randomly disconnect things.
        // m_pLoadedTrack->disconnect();
        disconnect(m_pLoadedTrack.data(), 0, m_pBPM, 0);
        disconnect(m_pLoadedTrack.data(), 0, this, 0);
        disconnect(m_pLoadedTrack.data(), 0, m_pKey, 0);

        m_pReplayGain->slotSet(0);

        // Causes the track's data to be saved back to the library database.
        emit(unloadingTrack(m_pLoadedTrack));
    }

    m_pLoadedTrack = track;
    if (m_pLoadedTrack) {
        // Listen for updates to the file's BPM
        connect(m_pLoadedTrack.data(), SIGNAL(bpmUpdated(double)),
                m_pBPM, SLOT(slotSet(double)));

        connect(m_pLoadedTrack.data(), SIGNAL(keyUpdated(double)),
                m_pKey, SLOT(slotSet(double)));

        // Listen for updates to the file's Replay Gain
        connect(m_pLoadedTrack.data(), SIGNAL(ReplayGainUpdated(double)),
                this, SLOT(slotSetReplayGain(double)));
    }

    // Request a new track from the reader
    emit(loadTrack(track, bPlay));
}
Example #24
0
void eDVBCIInterfaces::recheckPMTHandlers()
{
	eDebugCI("recheckPMTHAndlers()");
	for (PMTHandlerList::iterator it(m_pmt_handlers.begin());
		it != m_pmt_handlers.end(); ++it)
	{
		CAID_LIST caids;
		ePtr<eDVBService> service;
		eServiceReferenceDVB ref;
		eDVBCISlot *tmp = it->cislot;
		eDVBServicePMTHandler *pmthandler = it->pmthandler;
		eDVBServicePMTHandler::program p;
		bool plugged_cis_exist = false;

		pmthandler->getServiceReference(ref);
		pmthandler->getService(service);

		eDebugCI("recheck %p %s", pmthandler, ref.toString().c_str());
		for (eSmartPtrList<eDVBCISlot>::iterator ci_it(m_slots.begin()); ci_it != m_slots.end(); ++ci_it)
			if (ci_it->plugged && ci_it->getCAManager())
			{
				eDebug("Slot %d plugged", ci_it->getSlotID());
				ci_it->plugged = false;
				plugged_cis_exist = true;
			}

		// check if this pmt handler has already assigned CI(s) .. and this CI(s) are already running
		if (!plugged_cis_exist)
		{
			while(tmp)
			{
				if (!tmp->running_services.empty())
					break;
				tmp=tmp->linked_next;
			}
			if (tmp) // we dont like to change tsmux for running services
			{
				eDebugCI("already assigned and running CI!\n");
				continue;
			}
		}

		if (!pmthandler->getProgramInfo(p))
		{
			int cnt=0;
			std::set<eDVBServicePMTHandler::program::capid_pair> set(p.caids.begin(), p.caids.end());
			for (std::set<eDVBServicePMTHandler::program::capid_pair>::reverse_iterator x(set.rbegin()); x != set.rend(); ++x, ++cnt)
				caids.push_front(x->caid);
			if (service && cnt)
				service->m_ca = caids;
		}

		if (service)
			caids = service->m_ca;

		if (caids.empty())
			continue; // unscrambled service

		for (eSmartPtrList<eDVBCISlot>::iterator ci_it(m_slots.begin()); ci_it != m_slots.end(); ++ci_it)
		{
			eDebugCI("check Slot %d", ci_it->getSlotID());
			bool useThis=false;
			bool user_mapped=true;
			eDVBCICAManagerSession *ca_manager = ci_it->getCAManager();

			if (ca_manager)
			{
				int mask=0;
				if (!ci_it->possible_services.empty())
				{
					mask |= 1;
					serviceSet::iterator it = ci_it->possible_services.find(ref);
					if (it != ci_it->possible_services.end())
					{
						eDebug("'%s' is in service list of slot %d... so use it", ref.toString().c_str(), ci_it->getSlotID());
						useThis = true;
					}
					else // check parent
					{
						eServiceReferenceDVB parent_ref = ref.getParentServiceReference();
						if (parent_ref)
						{
							it = ci_it->possible_services.find(ref);
							if (it != ci_it->possible_services.end())
							{
								eDebug("parent '%s' of '%s' is in service list of slot %d... so use it",
									parent_ref.toString().c_str(), ref.toString().c_str(), ci_it->getSlotID());
								useThis = true;
							}
						}
					}
				}
				if (!useThis && !ci_it->possible_providers.empty())
				{
					eDVBNamespace ns = ref.getDVBNamespace();
					mask |= 2;
					if (!service) // subservice?
					{
						eServiceReferenceDVB parent_ref = ref.getParentServiceReference();
						eDVBDB::getInstance()->getService(parent_ref, service);
					}
					if (service)
					{
						providerSet::iterator it = ci_it->possible_providers.find(providerPair(service->m_provider_name, ns.get()));
						if (it != ci_it->possible_providers.end())
						{
							eDebug("'%s/%08x' is in provider list of slot %d... so use it", service->m_provider_name.c_str(), ns.get(), ci_it->getSlotID());
							useThis = true;
						}
					}
				}
				if (!useThis && !ci_it->possible_caids.empty())
				{
					mask |= 4;
					for (CAID_LIST::iterator ca(caids.begin()); ca != caids.end(); ++ca)
					{
						caidSet::iterator it = ci_it->possible_caids.find(*ca);
						if (it != ci_it->possible_caids.end())
						{
							eDebug("caid '%04x' is in caid list of slot %d... so use it", *ca, ci_it->getSlotID());
							useThis = true;
							break;
						}
					}
				}
				if (!useThis && !mask)
				{
					const std::vector<uint16_t> &ci_caids = ca_manager->getCAIDs();
					for (CAID_LIST::iterator ca(caids.begin()); ca != caids.end(); ++ca)
					{
						std::vector<uint16_t>::const_iterator z =
							std::lower_bound(ci_caids.begin(), ci_caids.end(), *ca);
						if ( z != ci_caids.end() && *z == *ca )
						{
							eDebug("The CI in Slot %d has said it can handle caid %04x... so use it", ci_it->getSlotID(), *z);
							useThis = true;
							user_mapped = false;
							break;
						}
					}
				}
			}

			if (useThis)
			{
				// check if this CI is already assigned to this pmthandler
				eDVBCISlot *tmp = it->cislot;
				while(tmp)
				{
					if (tmp == ci_it)
						break;
					tmp=tmp->linked_next;
				}
				if (tmp) // ignore already assigned cislots...
				{
					eDebugCI("already assigned!");
					continue;
				}
				eDebugCI("current slot %d usecount %d", ci_it->getSlotID(), ci_it->use_count);
				if (ci_it->use_count)  // check if this CI can descramble more than one service
				{
					bool found = false;
					useThis = false;
					PMTHandlerList::iterator tmp = m_pmt_handlers.begin();
					while (!found && tmp != m_pmt_handlers.end())
					{
						eDebugCI(".");
						eDVBCISlot *tmp_cislot = tmp->cislot;
						while (!found && tmp_cislot)
						{
							eDebugCI("..");
							eServiceReferenceDVB ref2;
							tmp->pmthandler->getServiceReference(ref2);
							if ( tmp_cislot == ci_it && it->pmthandler != tmp->pmthandler )
							{
								eDebugCI("check pmthandler %s for same service/tp", ref2.toString().c_str());
								eDVBChannelID s1, s2;
								if (ref != ref2)
								{
									eDebugCI("different services!");
									ref.getChannelID(s1);
									ref2.getChannelID(s2);
								}
								if (ref == ref2 || (s1 == s2 && canDescrambleMultipleServices(tmp_cislot->getSlotID())))
								{
									found = true;
									eDebugCI("found!");
									eDVBCISlot *tmpci = it->cislot = tmp->cislot;
									while(tmpci)
									{
										++tmpci->use_count;
										eDebug("(2)CISlot %d, usecount now %d", tmpci->getSlotID(), tmpci->use_count);
										tmpci=tmpci->linked_next;
									}
								}
							}
							tmp_cislot=tmp_cislot->linked_next;
						}
						eDebugCI("...");
						++tmp;
					}
				}

				if (useThis)
				{
					if (ci_it->user_mapped)  // we dont like to link user mapped CIs
					{
						eDebugCI("user mapped CI already in use... dont link!");
						continue;
					}

					++ci_it->use_count;
					eDebug("(1)CISlot %d, usecount now %d", ci_it->getSlotID(), ci_it->use_count);

					data_source ci_source=CI_A;
					switch(ci_it->getSlotID())
					{
						case 0: ci_source = CI_A; break;
						case 1: ci_source = CI_B; break;
						case 2: ci_source = CI_C; break;
						case 3: ci_source = CI_D; break;
						default:
							eDebug("try to get source for CI %d!!\n", ci_it->getSlotID());
							break;
					}

					if (!it->cislot)
					{
						int tunernum = -1;
						eUsePtr<iDVBChannel> channel;
						if (!pmthandler->getChannel(channel))
						{
							ePtr<iDVBFrontend> frontend;
							if (!channel->getFrontend(frontend))
							{
								eDVBFrontend *fe = (eDVBFrontend*) &(*frontend);
								tunernum = fe->getSlotID();
							}
						}
						ASSERT(tunernum != -1);
						data_source tuner_source = TUNER_A;
						switch (tunernum)
						{
							case 0: tuner_source = TUNER_A; break;
							case 1: tuner_source = TUNER_B; break;
							case 2: tuner_source = TUNER_C; break;
							case 3: tuner_source = TUNER_D; break;
							default:
								eDebug("try to get source for tuner %d!!\n", tunernum);
								break;
						}
						ci_it->current_tuner = tunernum;
						setInputSource(tunernum, ci_source);
						ci_it->setSource(tuner_source);
					}
					else
					{
						ci_it->current_tuner = it->cislot->current_tuner;
						ci_it->linked_next = it->cislot;
						ci_it->setSource(ci_it->linked_next->current_source);
						ci_it->linked_next->setSource(ci_source);
					}
					it->cislot = ci_it;
					eDebugCI("assigned!");
					gotPMT(pmthandler);
				}

				if (it->cislot && user_mapped) // CI assigned to this pmthandler in this run.. and user mapped? then we break here.. we dont like to link other CIs to user mapped CIs
				{
					eDebugCI("user mapped CI assigned... dont link CIs!");
					break;
				}
			}
		}
	}
}
Example #25
0
/** Loads the settings for this page */
void ServerPage::load()
{

	/* load up configuration from rsPeers */
	RsPeerDetails detail;
	if (!rsPeers->getPeerDetails(rsPeers->getOwnId(), detail))
	{
		return;
	}

	/* set net mode */
	int netIndex = 0;
	switch(detail.netMode)
	{
		case RS_NETMODE_EXT:
			netIndex = 2;
			break;
		case RS_NETMODE_UDP:
			netIndex = 1;
			break;
		default:
		case RS_NETMODE_UPNP:
			netIndex = 0;
			break;
	}
	ui.netModeComboBox->setCurrentIndex(netIndex);

	/* DHT + Discovery: (public)
	 * Discovery only:  (private)
	 * DHT only: (inverted)
	 * None: (dark net)
	 */

	netIndex = 3; // NONE.
	if (detail.visState & RS_VS_DHT_ON)
	{
		if (detail.visState & RS_VS_DISC_ON)
		{
			netIndex = 0; // PUBLIC
		}
		else
		{
			netIndex = 2; // INVERTED
		}
	}
	else
	{
		if (detail.visState & RS_VS_DISC_ON)
		{
			netIndex = 1; // PRIVATE
		}
		else
		{
			netIndex = 3; // NONE
		}
	}

	ui.discComboBox->setCurrentIndex(netIndex);

	int dlrate = 0;
	int ulrate = 0;
	rsConfig->GetMaxDataRates(dlrate, ulrate);
	ui.totalDownloadRate->setValue(dlrate);
	ui.totalUploadRate->setValue(ulrate);

	toggleUPnP();


	/* Addresses must be set here - otherwise can't edit it */
		/* set local address */
	ui.localAddress->setText(QString::fromStdString(detail.localAddr));
	ui.localPort -> setValue(detail.localPort);
		/* set the server address */
	ui.extAddress->setText(QString::fromStdString(detail.extAddr));
	ui.extPort -> setValue(detail.extPort);
	/* set DynDNS */
	ui.dynDNS -> setText(QString::fromStdString(detail.dyndns));

	ui.showDiscStatusBar->setChecked(Settings->getStatusBarFlags() & STATUSBAR_DISC);

	ui._max_tr_up_per_sec_SB->setValue(rsTurtle->getMaxTRForwardRate()) ;
	ui._turtle_enabled_CB->setChecked(rsTurtle->enabled()) ;

		ui.ipAddressList->clear();
		for(std::list<std::string>::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it)
			ui.ipAddressList->addItem(QString::fromStdString(*it));
}
Example #26
0
LoremManager::LoremManager(ScribusDoc* doc, QWidget* parent) : QDialog( parent )
{
	m_Doc=doc;
	setModal(true);
	setWindowTitle( tr( "Lorem Ipsum" ) );
	setWindowIcon(QIcon(loadIcon ( "AppIcon.png" )));
	LoremManagerLayout = new QGridLayout(this) ;
	LoremManagerLayout->setMargin(10);
	LoremManagerLayout->setSpacing(5);

	layout3 = new QVBoxLayout;
	layout3->setMargin(0);
	layout3->setSpacing(5);

	loremList = new QTreeWidget( this );
	loremList->setRootIsDecorated(true);
	loremList->setColumnCount(1);
	loremList->setHeaderLabel( tr("Select Lorem Ipsum"));
	loremList->header()->setClickable( false );
	loremList->header()->setResizeMode( QHeaderView::ResizeToContents );
	loremList->setSelectionMode(QAbstractItemView::SingleSelection);
	layout3->addWidget( loremList );

	layout2 = new QHBoxLayout;
	layout2->setMargin(0);
	layout2->setSpacing(5);

	paraLabel = new QLabel( this );
	layout2->addWidget( paraLabel );

	paraBox = new QSpinBox( this );
	paraBox->setMinimum( 1 );
	paraBox->setValue(PrefsManager::instance()->appPrefs.miscPrefs.paragraphsLI);
	layout2->addWidget( paraBox );
	randomCheckBox = new QCheckBox(this);
	randomCheckBox->setChecked(true);
	layout2->addWidget( randomCheckBox );
	paraSpacer = new QSpacerItem( 2, 2, QSizePolicy::Expanding, QSizePolicy::Minimum );
	layout2->addItem( paraSpacer );
	layout3->addLayout( layout2 );

	layout1 = new QHBoxLayout;
	layout1->setMargin(0);
	layout1->setSpacing(5);
	buttonSpacer = new QSpacerItem( 2, 2, QSizePolicy::Expanding, QSizePolicy::Minimum );
	layout1->addItem( buttonSpacer );

	okButton = new QPushButton( this );
	layout1->addWidget( okButton );

	cancelButton = new QPushButton( this );
	layout1->addWidget( cancelButton );
	layout3->addLayout( layout1 );

	LoremManagerLayout->addLayout( layout3, 0, 0 );
	languageChange();

	// reading lorems
	QDir d(getLoremLocation(QString::null), "*.xml");

	QFileInfoList list = d.entryInfoList();
	QListIterator<QFileInfo> it(list);
	QFileInfo fi;
	LanguageManager * langmgr( LanguageManager::instance() );
// 	langmgr->init(false);

	while (it.hasNext())
	{
		fi = it.next();
		if (langmgr->getLangFromAbbrev(fi.baseName(), false).isEmpty())
			continue;
		LoremParser *parser = new LoremParser(fi.fileName());
		if (!parser->correct)
		{
			delete parser;
			continue;
		}
		availableLorems[parser->name] = fi.fileName();
		QTreeWidgetItem *item = new QTreeWidgetItem(loremList);
		if (parser->name=="la")
			item->setText(0, standardloremtext);
		else
			item->setText(0, langmgr->getLangFromAbbrev(parser->name, true));
		QTreeWidgetItem *subItem;
		subItem = new QTreeWidgetItem(item);
		subItem->setText(0, tr("Author:") + " " + parser->author);
		subItem = new QTreeWidgetItem(item);
		subItem->setText(0, tr("Get More:") + " " + parser->url);
		subItem = new QTreeWidgetItem(item);
		subItem->setText(0, tr("XML File:") + " " + fi.fileName());
		delete parser;
	}
	loremList->sortItems(0, Qt::AscendingOrder);
	loremList->setSortingEnabled(false);
	resize( QSize(320, 340).expandedTo(minimumSizeHint()) );
	QList<QTreeWidgetItem *> defItem;
	defItem.clear();
	defItem = loremList->findItems(langmgr->getTransLangFromLang(m_Doc->Language), Qt::MatchExactly);
	if (defItem.count() == 0)
		defItem = loremList->findItems(standardloremtext, Qt::MatchExactly);
	if (defItem.count() != 0)
	{
		loremList->setCurrentItem(defItem[0]);
		defItem[0]->setSelected(true);
	}
	// signals and slots connections
	connect( okButton, SIGNAL( clicked() ), this, SLOT( accept() ) );
	connect( cancelButton, SIGNAL( clicked() ), this, SLOT( reject() ) );
	connect( loremList, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(accept()));
	
}
Example #27
0
Container::Container(unsigned id, const char *cfg)
{
    m_bInit   = false;
    m_bInSize = false;
    m_bStatusSize = false;
    m_bBarChanged = false;
    m_bReceived = false;
    m_bNoSwitch = false;

    SET_WNDPROC("container")
    setWFlags(WDestructiveClose);
    QFrame *frm = new QFrame(this);
    setCentralWidget(frm);

    connect(CorePlugin::m_plugin, SIGNAL(modeChanged()), this, SLOT(modeChanged()));

    QVBoxLayout *lay = new QVBoxLayout(frm);
    m_wnds = new QWidgetStack(frm);
    m_wnds->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
    lay->addWidget(m_wnds);

    m_tabSplitter = new Splitter(frm);
    m_tabSplitter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
    m_tabBar = new UserTabBar(m_tabSplitter);
    m_tabBar->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding));
    m_tabBar->hide();

    m_status = new ContainerStatus(m_tabSplitter);
    lay->addWidget(m_tabSplitter);

    load_data(containerData, &data, cfg);

    bool bPos = true;
    if (cfg == NULL){
        setId(id);
        memcpy(data.barState, CorePlugin::m_plugin->data.containerBar, sizeof(data.barState));
        memcpy(data.geometry, CorePlugin::m_plugin->data.containerGeo, sizeof(data.geometry));
        if ((data.geometry[WIDTH].value == (unsigned long)-1) || (data.geometry[HEIGHT].value == (unsigned long)-1)){
            QWidget *desktop = QApplication::desktop();
            data.geometry[WIDTH].value = desktop->width() / 3;
            data.geometry[HEIGHT].value = desktop->height() / 3;
        }
        bPos = false;
        if ((data.geometry[TOP].value != (unsigned long)-1) || (data.geometry[LEFT].value != (unsigned long)-1)){
            bPos = true;
            QWidgetList  *list = QApplication::topLevelWidgets();
            for (int i = 0; i < 2; i++){
                bool bOK = true;
                QWidgetListIt it(*list);
                QWidget * w;
                while ((w = it.current()) != NULL){
                    if (w == this){
                        ++it;
                        continue;
                    }
                    if (w->inherits("Container")){
                        int dw = w->pos().x() - data.geometry[LEFT].value;
                        int dh = w->pos().y() - data.geometry[TOP].value;
                        if (dw < 0) dw = -dw;
                        if (dh < 0) dh = -dh;
                        if ((dw < 3) && (dh < 3)){
                            int nl = data.geometry[LEFT].value;
                            int nt = data.geometry[TOP].value;
                            nl += 21;
                            nt += 20;
                            QWidget *desktop = QApplication::desktop();
                            if (nl + (int)data.geometry[WIDTH].value > desktop->width())
                                nl = 0;
                            if (nt + (int)data.geometry[WIDTH].value > desktop->width())
                                nt = 0;
                            if ((nl != (int)data.geometry[LEFT].value) && (nt != (int)data.geometry[TOP].value)){
                                data.geometry[LEFT].value = nl;
                                data.geometry[TOP].value  = nt;
                                bOK = false;
                            }
                        }
                    }
                    ++it;
                }
                if (bOK)
                    break;
            }
            delete list;
        }
        setStatusSize(CorePlugin::m_plugin->getContainerStatusSize());
        showBar();
        m_bInit = true;
    }
    m_bInSize = true;
    restoreGeometry(this, data.geometry, bPos, true);
    m_bInSize = false;
    connect(m_tabBar, SIGNAL(selected(int)), this, SLOT(contactSelected(int)));
    connect(this, SIGNAL(toolBarPositionChanged(QToolBar*)), this, SLOT(toolbarChanged(QToolBar*)));
    connect(m_status, SIGNAL(sizeChanged(int)), this, SLOT(statusChanged(int)));

    m_accel = new QAccel(this);
    connect(m_accel, SIGNAL(activated(int)), this, SLOT(accelActivated(int)));
    setupAccel();
}
Example #28
0
/**
* Processes filters by looping across the pool of FilterMgrs.
* As each FilterMgr finishes, emits appropriate signals and flags it as no longer busy.
*/
void SpeechData::doFiltering()
{
    // kdDebug() << "SpeechData::doFiltering: Running. " << m_pooledFilterMgrs.count() << " filters in pool." <<  endl;
    bool again = true;
    while (again)
    {
        again = false;
        QPtrListIterator<PooledFilterMgr> it( m_pooledFilterMgrs );
        for( ; it.current(); ++it )
        {
            PooledFilterMgr* pooledFilterMgr = it.current();
            // If FilterMgr is busy, see if it is now finished.
            if (pooledFilterMgr->busy)
            {
                FilterMgr* filterMgr = pooledFilterMgr->filterMgr;
                if (filterMgr->getState() == FilterMgr::fsFinished)
                {
                    mlJob* job = pooledFilterMgr->job;
                    // kdDebug() << "SpeechData::doFiltering: filter finished, jobNum = " << job->jobNum << " partNum = " << pooledFilterMgr->partNum << endl;
                    // We have to retrieve parts in order, but parts may not be completed in order.
                    // See if this is the next part we need.
                    if ((int)job->partSeqNums.count() == (pooledFilterMgr->partNum - 1))
                    {
                        pooledFilterMgr->busy = false;
                        // Retrieve text from FilterMgr.
                        QString text = filterMgr->getOutput();
                        // kdDebug() << "SpeechData::doFiltering: text.left(500) = " << text.left(500) << endl;
                        filterMgr->ackFinished();
                        // Convert the TalkerCode back into string.
                        job->talker = pooledFilterMgr->talkerCode->getTalkerCode();
                        // TalkerCode object no longer needed.
                        delete pooledFilterMgr->talkerCode;
                        pooledFilterMgr->talkerCode = 0;
                        if (filterMgr->noSBD())
                            job->sentences = text;
                        else
                        {
                            // Split the text into sentences and store in the job.
                            // The SBD plugin does all the real sentence parsing, inserting tabs at each
                            // sentence boundary.
                            QStringList sentences = QStringList::split("\t", text, false);
                            int sentenceCount = job->sentences.count();
                            job->sentences += sentences;
                            job->partSeqNums.append(sentenceCount + sentences.count());
                        }
                        int partNum = job->partSeqNums.count();
                        // Clean up.
                        pooledFilterMgr->job = 0;
                        pooledFilterMgr->partNum = 0;
                        // Emit signal.
                        if (!filterMgr->noSBD())
                        {
                            if (partNum == 1)
                                emit textSet(job->appId, job->jobNum);
                            else
                                emit textAppended(job->appId, job->jobNum, partNum);
                        }
                    } else {
                        // A part is ready, but need to first process a finished preceeding part
                        // that follows this one in the pool of filter managers.
                        again = true;
                        // kdDebug() << "SpeechData::doFiltering: filter is finished, but must wait for earlier part to finish filter, job = " << pooledFilterMgr->job->jobNum << endl;
                    }
                }
                // else kdDebug() << "SpeechData::doFiltering: filter for job " << pooledFilterMgr->job->jobNum << " is busy." << endl;
            }
            // else kdDebug() << "SpeechData::doFiltering: filter is idle" << endl;
        }
    }
}
Example #29
0
bool CDBWrapper::IsEmpty()
{
    boost::scoped_ptr<CDBIterator> it(NewIterator());
    it->SeekToFirst();
    return !(it->Valid());
}
bool KviKvsTreeNodeSpecialCommandForeach::execute(KviKvsRunTimeContext * c)
{
	KviKvsVariantList l;
	l.setAutoDelete(true);
	if(!m_pIterationData->evaluate(c,&l))
		return false;

	KviKvsSwitchList swl;
	if(m_pSwitches)
	{
		if(!(m_pSwitches->evaluate(c,&swl)))
			return false;
	}

	bool bIncludeEmptyScalars = swl.find('a',"all") != 0;

	for(KviKvsVariant * pArg = l.first();pArg;pArg = l.next())
	{
		switch(pArg->type())
		{
			case KviKvsVariantData::Array:
			{
				unsigned int uCnt = pArg->array()->size();
				unsigned int idx = 0;
				while(idx < uCnt)
				{
					// we evaluate this each time (as it may actually be killed at each iteration)
					// FIXME: maybe some kind of reference counting or a observer pattern might be a bit more efficient here
					//        (but might be far less efficient everywhere else...)
					KviKvsRWEvaluationResult * v = m_pIterationVariable->evaluateReadWrite(c);
					if(!v)
						return false;
					KviKvsVariant * pOne = pArg->array()->at(idx);
					if(pOne)
					{
						if(bIncludeEmptyScalars || (!pOne->isEmpty()))
						{
							v->result()->copyFrom(*pOne);
						} else {
							delete v; // we're done with it for this iteration
							idx++;
							continue;
						}
					} else {
						if(bIncludeEmptyScalars)
						{
							v->result()->setNothing();
						} else {
							delete v; // we're done with it for this iteration
							idx++;
							continue;
						}

					}
					delete v; // we're done with it for this iteration

					if(!m_pLoop->execute(c))
					{
						if(c->error())
							return false;

						// break allowed!
						if(c->breakPending())
						{
							c->handleBreak();
							return true;
						}

						if(c->continuePending())
						{
							c->handleContinue();
							idx++;
							continue;
						}

						return false; // propagate the false return value
					}

					idx++;
				}
			}
			break;
			case KviKvsVariantData::Hash:
			{
				KviKvsHashIterator it(*(pArg->hash()->dict()));
				while(KviKvsVariant * pOne = it.current())
				{
					// we evaluate this each time (as it may actually be killed at each iteration)
					// FIXME: maybe some kind of reference counting or a observer pattern might be a bit more efficient here
					//        (but might be far less efficient everywhere else...)
					KviKvsRWEvaluationResult * v = m_pIterationVariable->evaluateReadWrite(c);
					if(!v)
						return false;

					if(bIncludeEmptyScalars || (!pOne->isEmpty()))
					{
						v->result()->copyFrom(*pOne);
					} else {
						delete v; // we're done with it for this iteration
						++it;
						continue;
					}
					delete v; // we're done with it for this iteration

					if(!m_pLoop->execute(c))
					{
						if(c->error())
							return false;

						// break allowed!
						if(c->breakPending())
						{
							c->handleBreak();
							return true;
						}

						if(c->continuePending())
						{
							c->handleContinue();
							++it;
							continue;
						}

						return false; // propagate the false return value
					}

					++it;
				}
			}
			break;
			default:
				if(bIncludeEmptyScalars || (!pArg->isEqualToNothing()))
				{
					// we evaluate this each time (as it may actually be killed at each iteration)
					// FIXME: maybe some kind of reference counting or a observer pattern might be a bit more efficient here
					//        (but might be far less efficient everywhere else...)
					KviKvsRWEvaluationResult * v = m_pIterationVariable->evaluateReadWrite(c);
					if(!v)
						return false;
					v->result()->copyFrom(*pArg);
					delete v; // we're done with it for this iteration

					if(!m_pLoop->execute(c))
					{
						if(c->error())
							return false;

						// break allowed!
						if(c->breakPending())
						{
							c->handleBreak();
							return true;
						}

						if(c->continuePending())
						{
							c->handleContinue();
							continue;
						}

						return false; // propagate the false return value
					}
				}
			break;
		}
	}

	return true;
}