void ExtractAlphaChannelsInterface::__ChannelList_EditCompleted( Edit& sender )
{
   try
   {
      String s = sender.Text();
      s.Trim();

      SortedArray<int> list;
      ExtractAlphaChannelsInstance::ParseChannelList( list, s );

      s.Clear();
      for ( size_type i = 0; ; )
      {
         s.Append( String( list[i] ) );
         if ( ++i == list.Length() )
            break;
         s.Append( ',' );
      }

      instance.channelList = s;
      sender.SetText( s );
   }

   ERROR_CLEANUP(
      sender.SetText( instance.channelList );
      sender.SelectAll();
      sender.Focus()
   )
}
Example #2
0
bool ProcessInstance::CanExecuteOn( const ImageVariant& image, String& whyNot ) const
{
   if ( !image.IsSharedImage() || !image.IsCompletelySelected() )
   {
      ImageVariant tmp;
      tmp.CreateSharedImageAs( image ).AssignImage( image );
      return CanExecuteOn( tmp, whyNot );
   }

   image.PushSelections();
   image.ResetSelections();

   ImageInfo info1( *image );

   image.PopSelections();

   whyNot.Clear();
   whyNot.Reserve( WHYNOT_MAXLENGTH );

   bool ok = (*API->Process->ValidateImageExecution)( handle, image.SharedImageHandle(), whyNot.c_str(), WHYNOT_MAXLENGTH ) != api_false;

   image.PushSelections();
   image.ResetSelections();

   ImageInfo info2( *image );

   image.PopSelections();

   if ( info1 != info2 )
      APIHackingAttempt( "ValidateImageExecution" );

   return ok;
}
Example #3
0
void
Accelerometer::GetLastAcceleration() {
	String res;
	res.Format(256, L"PhoneGap.callbacks['%S'].success({x:%f,y:%f,z:%f,timestamp:%d});", callbackId.GetPointer(), x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);

	res.Clear();
	res.Format(256, L"navigator.accelerometer.lastAcceleration = new Acceleration(%f,%f,%f,%d});", x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);
}
bool GradientsMergeMosaicInstance::CanExecuteGlobal( String& whyNot ) const
{
   if ( targetFrames.IsEmpty() )
   {
      whyNot = "No target frames have been specified.";
      return false;
   }

   whyNot.Clear();
   return true;
}
 bool PhotometricSuperflatInstance::CanExecuteOn( const View& view, String& whyNot ) const
 {
     if ( view.Image().IsComplexSample() )
     {
         whyNot = "PhotometricSuperflat cannot be executed on complex images.";
         return false;
     }
     
     whyNot.Clear();
     return true;
 }
Example #6
0
bool NewImageInterface::ValidateProcess( const ProcessImplementation& p, String& whyNot ) const
{
   const NewImageInstance* r = dynamic_cast<const NewImageInstance*>( &p );
   if ( r == 0 )
   {
      whyNot = "Not a NewImage instance.";
      return false;
   }

   whyNot.Clear();
   return true;
}
Example #7
0
bool DebayerInstance::CanExecuteOn( const View& view, String& whyNot ) const
{
   if ( view.Image().IsComplexSample() )
      whyNot = "Debayer cannot be executed on complex images.";
   else if ( view.Image().Width() < 6 || view.Image().Height() < 6 )
      whyNot = "Debayer needs an image of at least 6 by 6 pixels";
   else
   {
      whyNot.Clear();
      return true;
   }
   return false;
}
Example #8
0
void Ide::IdePaste(String& data)
{
	data.Clear();
	if(AcceptFiles(Clipboard())) {
		Vector<String> s = GetFiles(Clipboard());
		for(int i = 0; i < s.GetCount(); i++)
			if(FileExists(s[i]) && IsTextFile(s[i], 10000)) {
				int64 len = GetFileLength(s[i]);
				if(len > 5000000 || data.GetLength() + len < 5000000)
					data.Cat(LoadFile(s[i]));
			}
	}
}
/**
 * Retrieves the full path of the executable.
 *
 * @param argv0 The first command-line argument.
 * @returns The path.
 */
String Application::GetExePath(const String& argv0)
{
	String executablePath;

#ifndef _WIN32
	char buffer[MAXPATHLEN];
	if (getcwd(buffer, sizeof(buffer)) == NULL) {
		BOOST_THROW_EXCEPTION(posix_error()
		    << boost::errinfo_api_function("getcwd")
		    << boost::errinfo_errno(errno));
	}

	String workingDirectory = buffer;

	if (argv0[0] != '/')
		executablePath = workingDirectory + "/" + argv0;
	else
		executablePath = argv0;

	bool foundSlash = false;
	for (size_t i = 0; i < argv0.GetLength(); i++) {
		if (argv0[i] == '/') {
			foundSlash = true;
			break;
		}
	}

	if (!foundSlash) {
		const char *pathEnv = getenv("PATH");
		if (pathEnv != NULL) {
			std::vector<String> paths;
			boost::algorithm::split(paths, pathEnv, boost::is_any_of(":"));

			bool foundPath = false;
			BOOST_FOREACH(String& path, paths) {
				String pathTest = path + "/" + argv0;

				if (access(pathTest.CStr(), X_OK) == 0) {
					executablePath = pathTest;
					foundPath = true;
					break;
				}
			}

			if (!foundPath) {
				executablePath.Clear();
				BOOST_THROW_EXCEPTION(std::runtime_error("Could not determine executable path."));
			}
		}
Example #10
0
void B3EInterface::__EditCompleted_bkg( Edit& sender )
{
   try
   {
      String id = sender.Text().Trimmed();
      if ( id == TARGET_IMAGE )
         id.Clear();
      if ( !id.IsEmpty() )
      {
         bool valid;
         size_type p = id.Find( "->" );
         if ( p == String::notFound )
            valid = id.IsValidIdentifier();
         else
            valid = id.Left( p ).IsValidIdentifier() && id.Substring( p+2 ).IsValidIdentifier();
         if ( !valid )
            throw Error( "Invalid view identifier: " + id );
      }

      if ( sender == GUI->BackgroundReferenceView1_Edit )
      {
         instance.p_inputView[0].backgroundReferenceViewId = id;
         sender.SetText( BACKGROUND_REFERENCE_ID1 );
      }
      else if ( sender == GUI->BackgroundReferenceView2_Edit )
      {
         instance.p_inputView[1].backgroundReferenceViewId = id;
         sender.SetText( BACKGROUND_REFERENCE_ID2 );
      }
      return;
   }

   catch ( ... )
   {
      if ( sender == GUI->BackgroundReferenceView1_Edit )
         sender.SetText( BACKGROUND_REFERENCE_ID1 );
      else if ( sender == GUI->BackgroundReferenceView2_Edit )
         sender.SetText( BACKGROUND_REFERENCE_ID2 );

      try
      {
         throw;
      }
      ERROR_HANDLER

      sender.SelectAll();
      sender.Focus();
   }
}
bool ChannelCombinationInstance::CanExecuteOn( const View& v, String& whyNot ) const
{
   if ( v.Image().IsComplexSample() )
   {
      whyNot = "ChannelCombination cannot be executed on complex images.";
      return false;
   }

   if ( v.Image()->ColorSpace() != ColorSpace::RGB )
   {
      whyNot = "ChannelCombination can only be executed on RGB color images.";
      return false;
   }

   whyNot.Clear();
   return true;
}
Example #12
0
void
Accelerometer::OnDataReceived(SensorType sensorType, SensorData& sensorData, result r) {

	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_TIMESTAMP, timestamp);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_X, x);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Y, y);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Z, z);

	AppLogDebug("x: %f, y: %f, z: %f timestamp: %d", x, y, z, timestamp);

	String res;
	res.Format(256, L"PhoneGap.callbacks['%S'].success({x:%f,y:%f,z:%f,timestamp:%d});", callbackId.GetPointer(), x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);

	res.Clear();
	res.Format(256, L"navigator.accelerometer.lastAcceleration = new Acceleration(%f,%f,%f,%d});", x, y, z, timestamp);
	pWeb->EvaluateJavascriptN(res);
}
Example #13
0
bool ProcessInstance::CanExecuteGlobal( String& whyNot ) const
{
   whyNot.Clear();
   whyNot.Reserve( WHYNOT_MAXLENGTH );
   return (*API->Process->ValidateGlobalExecution)( handle, whyNot.c_str(), WHYNOT_MAXLENGTH ) != api_false;
}
Example #14
0
bool ProcessInstance::Validate( String& whyNot )
{
   whyNot.Clear();
   whyNot.Reserve( WHYNOT_MAXLENGTH );
   return (*API->Process->ValidateProcessInstance)( handle, whyNot.c_str(), WHYNOT_MAXLENGTH ) != api_false;
}
Example #15
0
void  XConfig::WriteFileItem(XFile &file, int indent, XBaseItem *baseItem)
{
    int j;

    if(baseItem->IsData())
    {
        XDataItem *item = static_cast<XDataItem*>(baseItem);

        String strItem;

        for(j=0; j<indent; j++)
            strItem << TEXT("  ");

        if( item->strName.IsValid()                         && (
            item->strName[0] == ' '                         ||
            item->strName[0] == '\t'                        ||
            item->strName[0] == '{'                         ||
            item->strName[item->strName.Length()-1] == ' '  ||
            item->strName[item->strName.Length()-1] == '\t' ||
            schr(item->strName, '\n')                       ||
            schr(item->strName, '"')                        ||
            schr(item->strName, ':')                        ))
        {
            strItem << ConvertToTextString(item->strName);
        }
        else
            strItem << item->strName;

        strItem << TEXT(" : ");

        if( item->strData.IsValid()                         && (
            item->strData[0] == ' '                         ||
            item->strData[0] == '\t'                        ||
            item->strData[0] == '{'                         ||
            item->strData[item->strData.Length()-1] == ' '  ||
            item->strData[item->strData.Length()-1] == '\t' ||
            schr(item->strData, '\n')                       ||
            schr(item->strData, '"')                        ||
            schr(item->strData, ':')                        ))
        {
            strItem << ConvertToTextString(item->strData);
        }
        else
            strItem << item->strData;

        strItem << TEXT("\r\n");

        file.WriteAsUTF8(strItem);
    }
    else if(baseItem->IsElement())
    {
        XElement *element = static_cast<XElement*>(baseItem);

        String strElement;

        for(j=0; j<indent; j++)
            strElement << TEXT("  ");

        if( element->strName.IsValid()                            && (
            element->strName[0] == ' '                            ||
            element->strName[0] == '\t'                           ||
            element->strName[0] == '{'                            ||
            element->strName[element->strName.Length()-1] == ' '  ||
            element->strName[element->strName.Length()-1] == '\t' ||
            schr(element->strName, '\n')                          ||
            schr(element->strName, '"')                           ||
            schr(element->strName, ':')                           ))
        {
            strElement << ConvertToTextString(element->strName);
        }
        else
            strElement << element->strName;

        strElement << TEXT(" : {\r\n");

        file.WriteAsUTF8(strElement);

        strElement.Clear();

        WriteFileData(file, indent+1, element);

        for(j=0; j<indent; j++)
            strElement << TEXT("  ");
        strElement << TEXT("}\r\n");

        file.WriteAsUTF8(strElement);
    }
}
bool ChannelCombinationInstance::CanExecuteGlobal( String& whyNot ) const
{
   whyNot.Clear();
   return true;
}
Example #17
0
void ClipReference(HaplotypeSet  & reference,
                   StringArray   & refMarkerList,
                   StringIntHash & referenceHash,
                   StringArray   & markerList,
                   String & start, String & stop)
   {
   if (start == "start") start.Clear();
   if (stop == "stop") stop.Clear();

   // If no clipping was requested, then nothing to do
   if (start.IsEmpty() && stop.IsEmpty())
       return;

   // Find the stretch of target that overlaps with reference
   int    firstMatch = reference.markerCount, lastMatch = -1;
   bool   matchStart = false, matchStop = false;
   String newStart, newStop;

   // First we find overlapping markers in target and, at the same time,
   // keep track of the marker nearest suggested start and stop positions
   // that overlaps with reference.
   for (int i = 0; i < markerList.Length(); i++)
      {
      String trimmed = markerList[i].Trim();

      if (start == trimmed) matchStart = true;
      if (stop == trimmed) matchStop = true;

      int index = referenceHash.Integer(trimmed);

      if (index < 0) continue;

      if (index < firstMatch) firstMatch = index;
      if (index > lastMatch) lastMatch = index;

      if (matchStart)
         {
         newStart = trimmed;
         matchStart = false;
         }

      if (matchStop)
         {
         newStop = trimmed;
         matchStop = false;
         }
      }

   // If start and stop are not in the reference, adjust them
   // according to information in the target list
   int startIndex = referenceHash.Integer(start);
   int stopIndex = referenceHash.Integer(stop);

   if (startIndex < 0 && !start.IsEmpty())
      {
      if (newStart.IsEmpty()) return;

      start = newStart;
      startIndex = referenceHash.Integer(start);
      }
   firstMatch = firstMatch < startIndex ? firstMatch : startIndex;

   if (stopIndex < 0 && !stop.IsEmpty())
      {
      if (newStop.IsEmpty()) return;

      stop = newStop;
      stopIndex = referenceHash.Integer(stop);
      }
   lastMatch = lastMatch > stopIndex ? lastMatch : stopIndex;

   int clipFrom = !start.IsEmpty() ? firstMatch : 0;
   int clipTo = !stop.IsEmpty() ? lastMatch : reference.markerCount - 1;

   if (clipFrom > 0 || clipTo < reference.markerCount - 1)
      {
      printf("  Clipping reference haplotypes to match target ...\n");

      reference.ClipHaplotypes(clipFrom, clipTo);

      StringArray newMarkerList;
      newMarkerList.Dimension(reference.markerCount);
      for (int i = clipFrom; i <= clipTo; i++)
         newMarkerList[i - clipFrom].Swap(refMarkerList[i]);
      newMarkerList.Swap(refMarkerList);

      referenceHash.Clear();
      for (int i = 0; i < refMarkerList.Length(); i++)
         referenceHash.Add(refMarkerList[i].Trim(), i);

      printf("    %d Markers Remain After Clipping ...\n", reference.markerCount);
      }
   }
void CompileShader(const String& fileName)
{
    String file = GetFileName(fileName);
    
    XMLFile doc(context_);
    File source(context_);
    source.Open(fileName);
    if (!doc.Load(source))
        ErrorExit("Could not open input file " + fileName);
    
    XMLElement shaders = doc.GetRoot("shaders");
    if (!shaders)
        ErrorExit("No shaders element in " + source.GetName());
    
    if (compileVS_)
    {
        ShaderParser vsParser;
        if (!vsParser.Parse(VS, shaders, defines_, defineValues_))
            ErrorExit("VS: " + vsParser.GetErrorMessage());
        
        const HashMap<String, unsigned>& combinations = vsParser.GetAllCombinations();
        for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
        {
            if (!compileVariation_ || i->first_ == variationName_)
            {
                ShaderCombination src = vsParser.GetCombination(i->first_);
                CompiledVariation compile;
                
                compile.type_ = VS;
                compile.name_ = file;
                compile.outFileName_ = outDir_ + file;
                if (!src.name_.Empty())
                {
                    compile.name_ += "_" + src.name_;
                    compile.outFileName_ += "_" + src.name_;
                }
                compile.outFileName_ += useSM3_ ? ".vs3" : ".vs2";
                compile.defines_ = src.defines_;
                compile.defineValues_ = src.defineValues_;
                
                variations_.Push(compile);
                workList_.Push(&variations_.Back());
            }
        }
    }
    
    if (compilePS_)
    {
        ShaderParser psParser;
        if (!psParser.Parse(PS, shaders, defines_, defineValues_))
            ErrorExit("PS: " + psParser.GetErrorMessage());
        
        const HashMap<String, unsigned>& combinations = psParser.GetAllCombinations();
        for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
        {
            if (!compileVariation_ || i->first_ == variationName_)
            {
                ShaderCombination src = psParser.GetCombination(i->first_);
                CompiledVariation compile;
                
                compile.type_ = PS;
                compile.name_ = file;
                compile.outFileName_ = outDir_ + file;
                if (!src.name_.Empty())
                {
                    compile.name_ += "_" + src.name_;
                    compile.outFileName_ += "_" + src.name_;
                }
                compile.outFileName_ += useSM3_ ? ".ps3" : ".ps2";
                compile.defines_ = src.defines_;
                compile.defineValues_ = src.defineValues_;
                
                variations_.Push(compile);
                workList_.Push(&variations_.Back());
            }
        }
    }
    
    if (variations_.Empty())
    {
        PrintLine("No variations to compile");
        return;
    }
    
    // Load the shader source code
    {
        String inputFileName = inDir_ + file + ".hlsl";
        File hlslFile(context_, inputFileName);
        if (!hlslFile.IsOpen())
            ErrorExit("Could not open input file " + inputFileName);
        
        hlslCode_.Clear();
        while (!hlslFile.IsEof())
            hlslCode_ += hlslFile.ReadLine() + "\n";
    }
    
    if (!compileVariation_)
    {
        // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely
        unsigned numWorkerThreads = GetNumLogicalCPUs() - 1;
        if (!numWorkerThreads)
            numWorkerThreads = 1;
        
        Vector<SharedPtr<WorkerThread> > workerThreads;
        workerThreads.Resize(numWorkerThreads);
        for (unsigned i = 0; i < workerThreads.Size(); ++i)
        {
            workerThreads[i] = new WorkerThread();
            workerThreads[i]->Run();
        }
        // This will wait until the thread functions have stopped
        for (unsigned i = 0; i < workerThreads.Size(); ++i)
            workerThreads[i]->Stop();
    }
    else
    {
        WorkerThread dummyThread;
        dummyThread.ThreadFunction();
    }
    
    // Check that all shaders compiled
    for (List<CompiledVariation>::Iterator i = variations_.Begin(); i != variations_.End(); ++i)
    {
        if (!i->errorMsg_.Empty())
        {
            if (i->type_ == VS)
                ErrorExit("Failed to compile vertex shader " + i->name_ + ": " + i->errorMsg_);
            else
                ErrorExit("Failed to compile pixel shader " + i->name_ + ": " + i->errorMsg_);
        }
    }
}
Example #19
0
int MIValue::ParsePair(String &name, MIValue &val, String const &s, int i)
{
	name.Clear();
	val.Clear();
	while(s[i] && isspace(s[i]))
		i++;
	if(!s[i])
	{
		SetError("ParsePair:Unexpected end of string");
		return i;
	}
	
	// is starting wirh '[' or '{' take it as a value with empty name
	if(s[i] == '{' || s[i] == '[')
	{
		name = "<UNNAMED>";
		return val.ParseTuple(s, i);
	}
	else
	{
		int aCount = 0;
		while(s[i] && ((s[i] != '=' && s[i] != '}' && s[i] != ']' && s[i] != ',') || aCount))
		{
			if(s[i] == '<')
				aCount++;
			else if(s[i] == '>')
				aCount--;
			if(s[i] == '\\')
				name.Cat(backslash(s, i));
			else
				name.Cat(s[i]);
			i++;
			
			// skip blanks if not inside <>
/*
			if(!aCount)
				while(s[i] && isspace(s[i]))
					i++;
*/
		}
		while(s[i] && isspace(s[i]))
			i++;

		if(s[i] != '=')
		{
			// we take the data without = as the value part
			// of keyless tuple...
			val.Set(name);
			name = "<UNNAMED>";
			return i;
		}
		i++;

		while(s[i] && isspace(s[i]))
			i++;
	}

	// skip address part before a tuple start, if any... it's useless and confuses the parser
	if(s[i] == '@')
	{
		int j = i;
		while(s[j] && s[j] != ':')
			j++;
		if(s[j] == ':')
			j++;
		while(s[j] && IsSpace(s[j]))
			j++;
		if(s[j] == '{')
			i = j;
	}

	switch(s[i])
	{
		case '"':
			i = val.ParseString(s, i);
			break;
		break;
		
		case '[':
			i = val.ParseArray(s, i);
			break;
			
		case '{':
			i = val.ParseTuple(s, i);
			break;
			
		default:
			i = val.ParseUnquotedString(s, i);
			break;
	}

	return i;
}
Example #20
0
bool JSONValue::ReadJSONString(String& dest, const char*& pos, const char*& end, bool inQuote)
{
    char c;
    
    if (!inQuote)
    {
        if (!NextChar(c, pos, end, true) || c != '\"')
            return false;
    }
    
    dest.Clear();
    for (;;)
    {
        if (!NextChar(c, pos, end, false))
            return false;
        if (c == '\"')
            break;
        else if (c != '\\')
            dest += c;
        else
        {
            if (!NextChar(c, pos, end, false))
                return false;
            switch (c)
            {
            case '\\':
                dest += '\\';
                break;
                
            case '\"':
                dest += '\"';
                break;
                
            case 'b':
                dest += '\b';
                break;
                
            case 'f':
                dest += '\f';
                break;
                
            case 'n':
                dest += '\n';
                break;
            
            case 'r':
                dest += '\r';
                break;
                
            case 't':
                dest += '\t';
                break;
                
            case 'u':
                {
                    /// \todo Doesn't handle unicode surrogate pairs
                    unsigned code;
                    /// @todo check return value
                    code = strtol(pos, 0, 16);
                    pos += 4;
                    dest.AppendUTF8(code);
                }
                break;
            }
        }
    }
    
    return true;
}