Example #1
0
bool CodeLocation::isValid() const
{
    return !filePath().isEmpty();
}
Example #2
0
int main(int argc, char *argv[])
{
  try {
    if(argc < 2) {
      std::cerr << "Input file not specified!!!" << std::endl;
      return EXIT_FAILURE;
    }
  
    // check if input file exist
    std::ifstream inFile(argv[1]);
    if(!inFile.is_open()) {
      std::cerr << "Input file '" << argv[1] << "' not found!!!" << std::endl;
      return EXIT_FAILURE;
    }
  
    // create file name
    std::string filePath(argv[1]);
    size_t nameStart = filePath.find_last_of("/\\");
    size_t extStart = filePath.find_last_of(".");
    std::string fileName(filePath, nameStart + 1, extStart - nameStart);
    fileName += "cpp";

    // prepare output stream
    std::ofstream outFile(fileName.c_str());
    if(!outFile.is_open()) {
      std::cerr << "Cannot create output file '" << fileName << "'!!!" << std::endl;
      return EXIT_FAILURE;
    }
  
    // create logger & translator
    freettcn::translator::CLogger logger;
    freettcn::translator::CDumper dumper(outFile);
    freettcn::translator::CTranslator translator(argv[1], logger);
    
    // create input stream
    pANTLR3_UINT8 fName((pANTLR3_UINT8)argv[1]);
    pANTLR3_INPUT_STREAM input = antlr3AsciiFileStreamNew(fName);
    if(!input)
      std::cerr << "Unable to open file " << (char *)fName << " due to malloc() failure1" << std::endl;
  
    // create lexer
    pttcn3Lexer lexer = ttcn3LexerNew(input);
    if(!lexer) {
      std::cerr << "Unable to create the lexer due to malloc() failure1" << std::endl;
      return EXIT_FAILURE;
    }
    // override warning messages for lexer
    lexer->pLexer->rec->displayRecognitionError = freettcn::translator::DisplayRecognitionError;
  
    // create tokens stream from input file
    pANTLR3_COMMON_TOKEN_STREAM tokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
    if(!tokens) {
      std::cerr << "Out of memory trying to allocate token stream" << std::endl;
      return EXIT_FAILURE;
    }

    // create parser
    pttcn3Parser parser = ttcn3ParserNew(tokens);
    if(!parser) {
      std::cerr << "Out of memory trying to allocate parser" << std::endl;
      return EXIT_FAILURE;
    }
    // override warning messages for parser
    parser->pParser->rec->displayRecognitionError = freettcn::translator::DisplayRecognitionError;
  
    if(argc >= 3 && std::string(argv[2]) == "-t") {
      // print tokens stream
      pANTLR3_UINT8 *tokenNames = parser->pParser->rec->state->tokenNames;
      if(!tokenNames) {
        std::cerr << "Token names not initiated!!!" << std::endl;
        return EXIT_FAILURE;
      }

      // estimate the longest token name
      size_t maxTokenLength = 0;
      pANTLR3_VECTOR vector = tokens->getTokens(tokens);
      for(unsigned i=0; i<vector->size(vector); i++) {
        pANTLR3_COMMON_TOKEN token = (pANTLR3_COMMON_TOKEN)vector->get(vector, i);
        maxTokenLength = std::max(maxTokenLength, std::string((char *)tokenNames[token->getType(token)]).size());
      }
   
      // print tokens
      for(unsigned i=0; i<vector->size(vector); i++) {
        pANTLR3_COMMON_TOKEN token = (pANTLR3_COMMON_TOKEN)vector->get(vector, i);
        std::cout << "Token[" << std::setw(3) << std::right << token->getType(token) << "] - " <<
          std::setw(maxTokenLength) << std::left << tokenNames[token->getType(token)] << " = " <<
          token->getText(token)->chars << std::endl;
      }
      return EXIT_SUCCESS;
    }
  
    // parse tokes stream
    parser->ttcn3Module(parser);

    
    if(translator.WarningNum() || translator.ErrorNum()) {
      std::cerr << filePath << ": Errors: " << translator.ErrorNum() << "; Warnings: " << translator.WarningNum() << std::endl;
      return EXIT_FAILURE;
    }
    
    // dump to output file
    translator.Dump(dumper);
    
    // must manually clean up
    //    parser->free(parser);
    tokens->free(tokens);
    lexer->free(lexer);
    input->close(input);
  }
  catch(freettcn::Exception &ex) {
    std::cerr << "Error: Unhandled freettcn exception caught:" << std::endl;
    std::cerr << ex.what() << std::endl;
    return EXIT_FAILURE;
  }
  catch(std::exception &ex) {
    std::cerr << "Error: Unhandled system exception caught:" << std::endl;;
    std::cerr << ex.what() << std::endl;;
    return EXIT_FAILURE;
  }
  catch(...) {
    std::cerr << "Unknown exception caught!!!" << std::endl;
    return EXIT_FAILURE;
  }
  
  return EXIT_SUCCESS;
}
Example #3
0
bool LevelLoader::LoadLevel(std::string filename)
{
	string filePath("resource/data/levels/");
	filePath += filename + ".xml";
	xml_document doc;

	if(!LoadXMLFile(doc,filePath))
		return false;

	bool anythingLoaded = false;

	for(xml_node entityNode = doc.child("entity"); entityNode; entityNode = entityNode.next_sibling("entity"))
	{  
		Entity* entity = nullptr;

		// Get the number of components
		unsigned int componentCount = std::distance(entityNode.children("component").begin(),
			entityNode.children("component").end());

		// Throws on bad allocation and if we pass something wrong to it
		try
		{
			entity = new Entity(m_nextEntityID++,entityNode.attribute("name").as_string(),
				componentCount);
		}
		catch(std::invalid_argument& ia)
		{
			LOG("A new entity could not be allocated. invalid_argument caught: " << ia.what());
			continue;
		}
		catch(std::bad_alloc& ba)
		{
			LOG("A new entity could not be allocated. bad_alloc caught: " << ba.what());
			continue;
		}

		entity->IsActive(entityNode.attribute("active").as_bool());
		entity->SetHP(entityNode.attribute("hp").as_int());
		entity->SetLayer(entityNode.attribute("layer").as_int());

		vec3<float> entityPos(entityNode.attribute("posX").as_float(), 
			entityNode.attribute("posY").as_float(), 0.0f);

		vec3<float> entityVel(entityNode.attribute("velX").as_float(),
			entityNode.attribute("velY").as_float(), 0.0f);

		entity->SetPosition(entityPos);
		entity->SetVelocity(entityVel);			

		for(xml_node componentNode = entityNode.child("component"); componentNode; componentNode = componentNode.next_sibling("component"))
		{
			ComponentAttribute compAt;
			std::string componentName = componentNode.attribute("type").as_string();
						
			if(componentName == "")
			{
				LOG("Tried to load invalid component type on Entity: " << entityNode.attribute("name").as_string() <<
					" Invalid Component Type: " << componentNode.attribute("type").as_string());
				continue;
			}
			
			// Grab all attributes for this component and give to the component factory to construct
			// Iteration is starting at second attribute since first is type and we already have that
			xml_attribute attributeNode = componentNode.first_attribute();
			attributeNode = attributeNode.next_attribute();

			std::vector<xml_attribute> compAttributes;

			for(; attributeNode; attributeNode = attributeNode.next_attribute())
			{
				compAttributes.push_back(attributeNode);
			}
			
			ComponentFactory::GetInstance().AddComponentToEntity(entity, componentName, &compAttributes);
		}

		entity->RegisterForMessages();

		m_worldMan->AddEntity(entity);
		anythingLoaded = true;
	}

	if(!anythingLoaded)
	{
		LOG("No valid entities to load in : " << filePath);
		return false;
	}

	return true;
}
Example #4
0
/// Provide access to files as allowed by process definitions.
void HttpFileAccess::processRequest(const HttpRequestContext& requestContext,
                                    const HttpMessage& request,
                                    HttpMessage*& response
                                    )
{
   UtlString message;
   response = new HttpMessage();

   UtlString peerName;
   if (mSipxRpc->isAllowedPeer(requestContext, peerName))
   {
      if (requestContext.methodIs(HTTP_GET_METHOD))
      {
         UtlString path;
         requestContext.getMappedPath(path);

         FileResource* resource = FileResourceManager::getInstance()->find(path);
         if (resource)
         {
            if (resource->isReadable())
            {
               sendFile(path, peerName, requestContext, request, response);
            }
            else
            {
               message.append("resource ");
               resource->appendDescription(message);
               message.append(" does not allow write access to '");
               message.append(path);
               message.append("'");
               OsSysLog::add(FAC_SUPERVISOR, PRI_ERR, "HttpFileAccess::processRequest from %s %s",
                             peerName.data(), message.data());

               response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION,
                                                    HTTP_FORBIDDEN_CODE,
                                                    "Access denied by process definition");
               response->setBody(new HttpBody(message.data(),message.length()));
               response->setContentType(CONTENT_TYPE_TEXT_PLAIN);
               response->setContentLength(message.length());
            }
         }
         else
         {
            message.append("File resource '");
            message.append(path);
            message.append("' not known to sipXsupervisor.");
            OsSysLog::add(FAC_SUPERVISOR, PRI_ERR, "HttpFileAccess::processRequest from %s %s",
                          peerName.data(), message.data());

            response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION,
                                                 HTTP_FILE_NOT_FOUND_CODE,
                                                 HTTP_FILE_NOT_FOUND_TEXT);
            response->setBody(new HttpBody(message.data(),message.length()));
            response->setContentType(CONTENT_TYPE_TEXT_PLAIN);
            response->setContentLength(message.length());
         }
      }
      else if (requestContext.methodIs(HTTP_DELETE_METHOD))
      {
         UtlString path;
         requestContext.getMappedPath(path);

         FileResource* resource = FileResourceManager::getInstance()->find(path);
         if (resource)
         {
            if (resource->isWriteable())
            {
               OsPath filePath(path);
               if (OsFileSystem::exists(filePath))
               {
                  if (OS_SUCCESS
                      == OsFileSystem::remove(filePath, TRUE /* recursive */, TRUE /* force */))
                  {
                     message.append("File '");
                     message.append(path);
                     message.append("' deleted");
                     OsSysLog::add(FAC_SUPERVISOR, PRI_INFO, "HttpFileAccess::processRequest from %s %s",
                                   peerName.data(), message.data());
                  
                     response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION_1_1,
                                                          HTTP_OK_CODE, "Deleted");
                     response->setContentLength(0);

                     // tell anyone who cares that this has changed
                     resource->modified();
                  }
                  else
                  {
                     int       httpStatusCode;
                     UtlString httpStatusText;

                     switch (errno)
                     {
                     case EACCES:
                        httpStatusCode = HTTP_FORBIDDEN_CODE;
                        httpStatusText = "File Access Denied";
                        break;

                     default:
                        httpStatusCode = HTTP_SERVER_ERROR_CODE;
                        httpStatusText.append("Unknown error ");
                        httpStatusText.appendNumber(errno);
                        break;
                     }

                     message.append("File '");
                     message.append(path);
                     message.append("' errno ");
                     message.appendNumber(errno);
                     message.append(" ");

                     char errnoMsg[1024];
                     strerror_r(errno, errnoMsg, sizeof(errnoMsg));
                     message.append(errnoMsg);

                     OsSysLog::add(FAC_SUPERVISOR, PRI_ERR, "HttpFileAccess::processRequest from %s %s",
                                   peerName.data(), message.data());

                     response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION,
                                                          httpStatusCode,
                                                          httpStatusText);
                     response->setBody(new HttpBody(message.data(),message.length()));
                     response->setContentType(CONTENT_TYPE_TEXT_PLAIN);
                     response->setContentLength(message.length());
                  }                  
               }
               else
               {
                  message.append("File to be deleted '");
                  message.append(path);
                  message.append("' does not exist");
                  OsSysLog::add(FAC_SUPERVISOR, PRI_INFO, "HttpFileAccess::processRequest from %s %s",
                                peerName.data(), message.data());
                  
                  response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION_1_1,
                                                       HTTP_OK_CODE, "File does not exist");
                  response->setContentLength(0);
               }
            }
            else
            {
               message.append("resource ");
               resource->appendDescription(message);
               message.append(" does not allow write access to '");
               message.append(path);
               message.append("'");
               OsSysLog::add(FAC_SUPERVISOR, PRI_ERR, "HttpFileAccess::processRequest from %s %s",
                             peerName.data(), message.data());

               response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION,
                                                    HTTP_FORBIDDEN_CODE,
                                                    "Access denied by process definition");
               response->setBody(new HttpBody(message.data(),message.length()));
               response->setContentType(CONTENT_TYPE_TEXT_PLAIN);
               response->setContentLength(message.length());
            }
         }
         else
         {
            message.append("File resource '");
            message.append(path);
            message.append("' not known to sipXsupervisor.");
            OsSysLog::add(FAC_SUPERVISOR, PRI_ERR, "HttpFileAccess::processRequest from %s %s",
                          peerName.data(), message.data());

            response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION,
                                                 HTTP_FILE_NOT_FOUND_CODE,
                                                 HTTP_FILE_NOT_FOUND_TEXT);
            response->setBody(new HttpBody(message.data(),message.length()));
            response->setContentType(CONTENT_TYPE_TEXT_PLAIN);
            response->setContentLength(message.length());
         }
      }
      else
      {
         OsSysLog::add(FAC_SUPERVISOR, PRI_ERR, "HttpFileAccess::processRequest %s from %s",
                       HTTP_UNSUPPORTED_METHOD_TEXT, peerName.data());

         response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION,
                                              HTTP_UNSUPPORTED_METHOD_CODE,
                                              HTTP_UNSUPPORTED_METHOD_TEXT);
      }
   }
   else
   {
      message.append("Request not supported from untrusted peer.");
      OsSysLog::add(FAC_SUPERVISOR, PRI_ERR, "HttpFileAccess::processRequest %s",
                    message.data());

      response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION,
                                           HTTP_FORBIDDEN_CODE, HTTP_FORBIDDEN_TEXT);

      response->setBody(new HttpBody(message.data(),message.length()));
      response->setContentType(CONTENT_TYPE_TEXT_PLAIN);
      response->setContentLength(message.length());
   }
}
static install_status_t
iterateOverNativeFiles(JNIEnv *env, jstring javaFilePath, jstring javaCpuAbi, jstring javaCpuAbi2,
        iterFunc callFunc, void* callArg) {
    ScopedUtfChars filePath(env, javaFilePath);
    ScopedUtfChars cpuAbi(env, javaCpuAbi);
    ScopedUtfChars cpuAbi2(env, javaCpuAbi2);

    ZipFileRO zipFile;

    if (zipFile.open(filePath.c_str()) != NO_ERROR) {
        ALOGI("Couldn't open APK %s\n", filePath.c_str());
        return INSTALL_FAILED_INVALID_APK;
    }

    const int N = zipFile.getNumEntries();

    char fileName[PATH_MAX];
    bool hasPrimaryAbi = false;

    for (int i = 0; i < N; i++) {
        const ZipEntryRO entry = zipFile.findEntryByIndex(i);
        if (entry == NULL) {
            continue;
        }

        // Make sure this entry has a filename.
        if (zipFile.getEntryFileName(entry, fileName, sizeof(fileName))) {
            continue;
        }

        // Make sure we're in the lib directory of the ZIP.
        if (strncmp(fileName, APK_LIB, APK_LIB_LEN)) {
            continue;
        }

        // Make sure the filename is at least to the minimum library name size.
        const size_t fileNameLen = strlen(fileName);
        static const size_t minLength = APK_LIB_LEN + 2 + LIB_PREFIX_LEN + 1 + LIB_SUFFIX_LEN;
        if (fileNameLen < minLength) {
            continue;
        }

        const char* lastSlash = strrchr(fileName, '/');
        ALOG_ASSERT(lastSlash != NULL, "last slash was null somehow for %s\n", fileName);

        // Check to make sure the CPU ABI of this file is one we support.
        const char* cpuAbiOffset = fileName + APK_LIB_LEN;
        const size_t cpuAbiRegionSize = lastSlash - cpuAbiOffset;

        ALOGV("Comparing ABIs %s and %s versus %s\n", cpuAbi.c_str(), cpuAbi2.c_str(), cpuAbiOffset);
        if (cpuAbi.size() == cpuAbiRegionSize
                && *(cpuAbiOffset + cpuAbi.size()) == '/'
                && !strncmp(cpuAbiOffset, cpuAbi.c_str(), cpuAbiRegionSize)) {
            ALOGV("Using primary ABI %s\n", cpuAbi.c_str());
            hasPrimaryAbi = true;
        } else if (cpuAbi2.size() == cpuAbiRegionSize
                && *(cpuAbiOffset + cpuAbi2.size()) == '/'
                && !strncmp(cpuAbiOffset, cpuAbi2.c_str(), cpuAbiRegionSize)) {

            /*
             * If this library matches both the primary and secondary ABIs,
             * only use the primary ABI.
             */
            if (hasPrimaryAbi) {
                ALOGV("Already saw primary ABI, skipping secondary ABI %s\n", cpuAbi2.c_str());
                continue;
            } else {
                ALOGV("Using secondary ABI %s\n", cpuAbi2.c_str());
            }
        } else {
            ALOGV("abi didn't match anything: %s (end at %zd)\n", cpuAbiOffset, cpuAbiRegionSize);
            continue;
        }

        // If this is a .so file, check to see if we need to copy it.
        if ((!strncmp(fileName + fileNameLen - LIB_SUFFIX_LEN, LIB_SUFFIX, LIB_SUFFIX_LEN)
                    && !strncmp(lastSlash, LIB_PREFIX, LIB_PREFIX_LEN)
                    && isFilenameSafe(lastSlash + 1))
                || !strncmp(lastSlash + 1, GDBSERVER, GDBSERVER_LEN)) {

            install_status_t ret = callFunc(env, callArg, &zipFile, entry, lastSlash + 1);

            if (ret != INSTALL_SUCCEEDED) {
                ALOGV("Failure for entry %s", lastSlash + 1);
                return ret;
            }
        }
    }

    return INSTALL_SUCCEEDED;
}
Example #6
0
void apply_colors_gtk(Fl_Color fg, 
		      Fl_Color bg, 
		      Fl_Color selection, 
		      Fl_Color selection_text, 
		      Fl_Color tooltip, 
		      Fl_Color tooltip_text, 
		      
		      Fl_Color text, 		      
		      Fl_String font)
{
    uchar r, g, b;
    uchar text_r, text_g, text_b;
    //, b1, r2, g2, b2;
    
    uchar selection_r, selection_g, selection_b;
    uchar selection_text_r, selection_text_g, selection_text_b;
    uchar tooltip_r, tooltip_g, tooltip_b;
    uchar tooltip_text_r, tooltip_text_g, tooltip_text_b;
    
    fl_get_color(bg, r, g, b);
    fl_get_color(fg, text_r, text_g, text_b);

    fl_get_color(selection, selection_r, selection_g, selection_b);
    fl_get_color(selection_text, selection_text_r, selection_text_g, selection_text_b);
    fl_get_color(tooltip, tooltip_r, tooltip_g, tooltip_b);
    fl_get_color(tooltip_text, tooltip_text_r, tooltip_text_g, tooltip_text_b);
    
//    fl_get_color(text, r2, g2, b2);

    Fl_String filePath(fl_homedir()); 
    filePath += "/.gtkrc";

    FILE *gtkFile = fopen(filePath.c_str(), "w");
    
    fprintf(gtkFile, "style \"default\" \n");
    fprintf(gtkFile, "{\n");
    fprintf(gtkFile, "fontset = \"%s\" \n", font.c_str());
    fprintf(gtkFile, "bg[NORMAL] = \"#%02X%02X%02X\"\n", r, g, b);
    fprintf(gtkFile, "fg[NORMAL] = \"#%02X%02X%02X\"\n", text_r, text_g, text_b);
    fprintf(gtkFile, "bg[PRELIGHT] = \"#%02X%02X%02X\"\n", r, g, b);
    fprintf(gtkFile, "fg[PRELIGHT] = \"#%02X%02X%02X\"\n", text_r, text_g, text_b);
    fprintf(gtkFile, "bg[ACTIVE] = \"#%02X%02X%02X\"\n", r, g, b);
    fprintf(gtkFile, "fg[ACTIVE] = \"#%02X%02X%02X\"\n", text_r, text_g, text_b);
    fprintf(gtkFile, "bg[SELECTED] = \"#%02X%02X%02X\"\n", selection_r, selection_g, selection_b);
    fprintf(gtkFile, "fg[SELECTED] = \"#%02X%02X%02X\"\n", selection_text_r, selection_text_g, selection_text_b);
    fprintf(gtkFile, "}\n");
    
    fprintf(gtkFile, "style \"menu\" \n");
    fprintf(gtkFile, "{\n");
    fprintf(gtkFile, "bg[PRELIGHT] = \"#%02X%02X%02X\"\n", selection_r, selection_g, selection_b);
    fprintf(gtkFile, "fg[PRELIGHT] = \"#%02X%02X%02X\"\n", selection_text_r, selection_text_g, selection_text_b);
    fprintf(gtkFile, "}\n");

    fprintf(gtkFile, "style \"tooltip\" \n");
    fprintf(gtkFile, "{\n");
    fprintf(gtkFile, "bg[NORMAL] = \"#%02X%02X%02X\"\n", tooltip_r, tooltip_g, tooltip_b);
    fprintf(gtkFile, "fg[NORMAL] = \"#%02X%02X%02X\"\n", tooltip_text_r, tooltip_text_g, tooltip_text_b);
    fprintf(gtkFile, "}\n");
    
    fprintf(gtkFile, "class \"*\" style \"default\"\n");
    fprintf(gtkFile, "widget_class \"*Menu*\" style \"menu\"  \n");
    fprintf(gtkFile, "widget \"gtk-tooltips\" style \"tooltip\"  \n");
    
    
    fclose(gtkFile);
}
Example #7
0
bool Directory::fileIsDir(void) const
{
	if(!mDirent) throw Exception("No more files in directory");
	//return (mDirent->d_type == DT_DIR);
	return Exist(filePath());
}
Example #8
0
bool QDir::mkdir( const QString &dirName, bool acceptAbsPath ) const
{
    return MKDIR( QFile::encodeName(filePath(dirName,acceptAbsPath)), 0777 )
           == 0;
}
Example #9
0
QString ProFileDocument::defaultPath() const
{
    QFileInfo fi(filePath());
    return fi.absolutePath();
}
void DIALOG_SPICE_MODEL::loadLibrary( const wxString& aFilePath )
{
    wxString curModel = m_modelName->GetValue();
    m_models.clear();
    wxFileName filePath( aFilePath );
    bool in_subckt = false;        // flag indicating that the parser is inside a .subckt section

    // Look for the file in the project path
    if( !filePath.Exists() )
    {
        filePath.SetPath( Prj().GetProjectPath() + filePath.GetPath() );

        if( !filePath.Exists() )
            return;
    }

    // Display the library contents
    wxWindowUpdateLocker updateLock( this );
    m_libraryContents->Clear();
    wxTextFile file;
    file.Open( filePath.GetFullPath() );
    int line_nr = 0;

    // Process the file, looking for components
    while( !file.Eof() )
    {
        const wxString& line = line_nr == 0 ? file.GetFirstLine() : file.GetNextLine();
        m_libraryContents->AppendText( line );
        m_libraryContents->AppendText( "\n" );

        wxStringTokenizer tokenizer( line );

        while( tokenizer.HasMoreTokens() )
        {
            wxString token = tokenizer.GetNextToken().Lower();

            // some subckts contain .model clauses inside,
            // skip them as they are a part of the subckt, not another model
            if( token == ".model" && !in_subckt )
            {
                wxString name = tokenizer.GetNextToken();

                if( name.IsEmpty() )
                    break;

                token = tokenizer.GetNextToken();
                SPICE_PRIMITIVE type = MODEL::parseModelType( token );

                if( type != SP_UNKNOWN )
                    m_models.emplace( name, MODEL( line_nr, type ) );
            }

            else if( token == ".subckt" )
            {
                wxASSERT( !in_subckt );
                in_subckt = true;

                wxString name = tokenizer.GetNextToken();

                if( name.IsEmpty() )
                    break;

                m_models.emplace( name, MODEL( line_nr, SP_SUBCKT ) );
            }

            else if( token == ".ends" )
            {
                wxASSERT( in_subckt );
                in_subckt = false;
            }
        }

        ++line_nr;
    }

    wxArrayString modelsList;

    // Refresh the model name combobox values
    m_modelName->Clear();

    for( const auto& model : m_models )
    {
        m_modelName->Append( model.first );
        modelsList.Add( model.first );
    }

    m_modelName->AutoComplete( modelsList );

    // Restore the previous value or if there is none - pick the first one from the loaded library
    if( !curModel.IsEmpty() )
        m_modelName->SetValue( curModel );
    else if( m_modelName->GetCount() > 0 )
        m_modelName->SetSelection( 0 );
}
Example #11
0
bool QDir::rmdir( const QString &dirName, bool acceptAbsPath ) const
{
    return RMDIR( QFile::encodeName(filePath(dirName,acceptAbsPath)) ) == 0;
}
Example #12
0
/// Get example path
static inline std::string getExamplePath()
{
    std::string filePath(__FILE__);
    return filePath.substr( 0, filePath.length() - std::string("main.cpp").length());
}
Example #13
0
boost::filesystem::path FileUtils::filePath(int64_t id) {
  return filePath(id, prefix_);
}
void ReflectionParser::GenerateFiles(void)
{
    fs::path sourceRootDirectory( m_options.sourceRoot );
    fs::path outputFileDirectory( m_options.outputModuleFileDirectory );

    m_moduleFileHeaderTemplate = LoadTemplate( kTemplateModuleFileHeader );

    if (!m_moduleFileHeaderTemplate.isValid( ))
    {
        std::stringstream error;

        error << "Unable to compile module file header template." << std::endl;
        error << m_moduleFileHeaderTemplate.errorMessage( );

        throw std::exception( error.str( ).c_str( ) );
    }

    m_moduleFileSourceTemplate = LoadTemplate( kTemplateModuleFileSource );

    if (!m_moduleFileSourceTemplate.isValid( ))
    {
        std::stringstream error;

        error << "Unable to compile module file source template." << std::endl;
        error << m_moduleFileSourceTemplate.errorMessage( );

        throw std::exception( error.str( ).c_str( ) );
    }

    TemplateData moduleFilesData { TemplateData::Type::List };

    fs::path metaCacheFileName = m_options.outputModuleFileDirectory;

    metaCacheFileName /= ".meta-cache";

    auto metaCacheFileExists = exists( metaCacheFileName );

    std::string moduleFileCache;

    for (auto &file : m_moduleFiles)
    {
        fs::path filePath( file.first );

        // path relative to the source root
        auto relativeDir = utils::MakeRelativePath( sourceRootDirectory, filePath )
            .replace_extension( "" ).string( );

        if (relativeDir.find_first_of( ".." ) != std::string::npos)
            continue;

        auto outputFile = outputFileDirectory / relativeDir;
        auto outputFileHeader = change_extension( outputFile, "Generated.h" );
        auto outputFileSource = change_extension( outputFile, "Generated.cpp" );

        // module file name
        file.second.name = boost::regex_replace(
            relativeDir,
            kSpecialCharsRegex,
            "_"
        );

        moduleFileCache += file.second.name + '\n';

        TemplateData moduleFileData { TemplateData::Type::Object };

        moduleFileData[ "name" ] = file.second.name;
        moduleFileData[ "header" ] = outputFileHeader.string( );

        moduleFilesData << moduleFileData;

        // if the generated file header doesn't exist, we need to regenerate
        if (m_options.forceRebuild || !metaCacheFileExists || !exists( outputFileHeader ))
        {
            generateModuleFile( outputFileHeader, outputFileSource, file.first, file.second );

            continue;
        }

        auto lastSourceWrite = last_write_time( filePath );
        auto lastGeneratedWrite = last_write_time( outputFileHeader );

        // if the generated file is older than the source file, we need to regenerate
        if (lastSourceWrite > lastGeneratedWrite)
            generateModuleFile( outputFileHeader, outputFileSource, file.first, file.second );
    }

    fs::path moduleCacheFileName = m_options.outputModuleFileDirectory;

    moduleCacheFileName /= ".meta-cache";

    if (!m_options.forceRebuild && metaCacheFileExists)
    {
        std::ifstream cacheFile( moduleCacheFileName.string( ) );

        std::istreambuf_iterator<char> cacheFileBegin( cacheFile );
        std::istreambuf_iterator<char> cacheFileEnd( nullptr );
        
        // the cache is the same, so we don't need to write the source files
        if (utils::RangeEqual( 
                moduleFileCache.begin( ), moduleFileCache.end( ), 
                cacheFileBegin, cacheFileEnd 
            ))
        {
            return;
        }
    }

    // update the cache
    utils::WriteText(
        moduleCacheFileName.string( ),
        moduleFileCache
    );

    // module source file
    {
        auto sourceTemplate = LoadTemplate( kTemplateModuleSource );

        if (!sourceTemplate.isValid( ))
        {
            std::stringstream error;

            error << "Unable to compile module source template." << std::endl;
            error << sourceTemplate.errorMessage( );

            throw std::exception( error.str( ).c_str( ) );
        }

        TemplateData sourceData { TemplateData::Type::Object };

        addGlobalTemplateData( sourceData );

        sourceData[ "moduleFile" ] = moduleFilesData;

        COMPILE_TYPE_TEMPLATES( sourceData, "external", m_externals );

        fs::path sourcePath( m_options.outputModuleSource );

        fs::create_directory( sourcePath.parent_path( ) );

        utils::WriteText( 
            sourcePath.string( ),
            sourceTemplate.render( sourceData )
        );
    }
}
Example #15
0
/*!
    Advances the iterator to the next entry, and returns the file path of this
    new entry. If hasNext() returns false, this function does nothing, and
    returns a null QString.

    You can call fileName() or filePath() to get the current entry file name
    or path, or fileInfo() to get a QFileInfo for the current entry.

    \sa hasNext(), fileName(), filePath(), fileInfo()
*/
QString QDirIterator::next()
{
    d->advance();
    return filePath();
}
Example #16
0
QString ProFileDocument::suggestedFileName() const
{
    QFileInfo fi(filePath());
    return fi.fileName();
}
Example #17
0
QString Solid::StorageAccess::filePath() const
{
    Q_D(const StorageAccess);
    return_SOLID_CALL(Ifaces::StorageAccess *, d->backendObject(), QString(), filePath());
}
Example #18
0
Foam::Istream* Foam::IOobject::objectStream()
{
    return objectStream(filePath());
}
Example #19
0
inline void VEventServerDbTask::UpdateDBSession(bool bIsFirst)
{
	std::time_t pTime = time(NULL);

	/* Get the Event Server Conf */
	VidEventDBConf cDBConf;
	m_Factory.GetEventDBConf(cDBConf);

	Poco::Timestamp pTimeStamp = Poco::Timestamp::fromEpochTime(pTime);

	/* Use next sec to check  */
	Poco::DateTime pTimeTime(pTimeStamp);

	int nYear = pTimeTime.year();
	int nMonth = pTimeTime.month();
	int nHour = pTimeTime.hour();

	if (bIsFirst != true)
	{

		/* Every day check if need new database */
		if (pTime%3600 != 0 || nHour != 0)
		{
			return;
		}

		if (nYear == m_nYear && nMonth == m_nMonth)
		{
			return;
		}
	}

	m_nYear = nYear;
	m_nMonth = nMonth;

	char strPlus[1024];
	sprintf(strPlus, "%d_%d", m_nYear, nMonth);
	
	if (cDBConf.ntype() == VID_DB_SQLITE)
	{
		if (m_pSqlSession != NULL)
		{
			delete m_pSqlSession;
			m_pSqlSession = NULL;
		}
		try
		{	
			Poco::Path path(cDBConf.strdbpath());
			Poco::File file(path);
			file.createDirectories();
			SQLite::Connector::registerConnector();
			VDC_DEBUG("Create the Event DB path %s\n", path.toString().c_str());
			
			Poco::Path filePath("eventdb.db");
			path.append(filePath);
			path.makeFile();
			VDC_DEBUG("Create the Event DB file %s\n", path.toString().c_str());

			m_pSqlSession = new Poco::Data::Session("SQLite", path.toString());
			*m_pSqlSession << "CREATE TABLE IF NOT EXISTS events "
				"(id INTEGER PRIMARY KEY, strId TEXT, strDevice TEXT, "
				"strDeviceName TEXT, strType TEXT, nTime INTEGER, strEvttime DATE, strDesc TEXT)", now;
		}
		catch (exception const &e)		
		{			
			VDC_DEBUG("%s Create SQLITE session failed \n", __FUNCTION__);
		}

	}else
	{
		VDC_DEBUG( "%s Do not support the DB TYPE \n",__FUNCTION__);
		ve_sleep(1000);
	}	
}
Example #20
0
QString ProFileDocument::defaultPath() const
{
    return filePath().toFileInfo().absolutePath();
}
Example #21
0
NS_IMETHODIMP
nsGNOMEShellService::SetDesktopBackground(nsIDOMElement* aElement, 
                                          int32_t aPosition)
{
  nsCString brandName;
  nsresult rv = GetBrandName(brandName);
  NS_ENSURE_SUCCESS(rv, rv);

  // build the file name
  nsCString filePath(PR_GetEnv("HOME"));
  filePath.Append('/');
  filePath.Append(brandName);
  filePath.AppendLiteral("_wallpaper.png");

  // get the image container
  nsCOMPtr<nsIImageLoadingContent> imageContent(do_QueryInterface(aElement, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<imgIRequest> request;
  rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                                getter_AddRefs(request));
  NS_ENSURE_TRUE(request, rv);

  nsCOMPtr<imgIContainer> container;
  rv = request->GetImage(getter_AddRefs(container));
  NS_ENSURE_TRUE(request, rv);

  nsCOMPtr<nsIImageToPixbuf> imgToPixbuf(do_GetService("@mozilla.org/widget/image-to-gdk-pixbuf;1"));
  if (!imgToPixbuf)
    return NS_ERROR_NOT_AVAILABLE;

  GdkPixbuf* pixbuf = imgToPixbuf->ConvertImageToPixbuf(container);
  if (!pixbuf)
    return NS_ERROR_NOT_AVAILABLE;

  // write the image to a file in the home dir
  gboolean res = gdk_pixbuf_save(pixbuf, filePath.get(), "png", NULL, NULL);

  g_object_unref(pixbuf);
  if (!res)
    return NS_ERROR_FAILURE;

  // set desktop wallpaper filling style
  const char* options;
  switch (aPosition) {
    case BACKGROUND_TILE:
      options = "wallpaper";
      break;
    case BACKGROUND_STRETCH:
      options = "stretched";
      break;
    case BACKGROUND_FILL:
      options = "zoom";
      break;
    case BACKGROUND_FIT:
      options = "scaled";
      break;
    default:
      options = "centered";
      break;
  }

  // Try GSettings first. If we don't have GSettings or the right schema, fall back
  // to using GConf instead. Note that if GSettings works ok, the changes get
  // mirrored to GConf by the gsettings->gconf bridge in gnome-settings-daemon
  nsCOMPtr<nsIGSettingsService> gsettings(do_GetService(NS_GSETTINGSSERVICE_CONTRACTID));
  if (gsettings) {
    nsCOMPtr<nsIGSettingsCollection> background_settings;
    gsettings->GetCollectionForSchema(NS_LITERAL_CSTRING(OGDB_SCHEMA),
                                      getter_AddRefs(background_settings));
    if (background_settings) {
      gchar *file_uri = g_filename_to_uri(filePath.get(), NULL, NULL);
      if (!file_uri)
       return NS_ERROR_FAILURE;

      background_settings->SetString(NS_LITERAL_CSTRING(OGDB_OPTIONS),
                                     nsDependentCString(options));
      background_settings->SetString(NS_LITERAL_CSTRING(OGDB_IMAGE),
                                     nsDependentCString(file_uri));
      g_free(file_uri);
      background_settings->SetBoolean(NS_LITERAL_CSTRING(OGDB_DRAWBG), true);
      return NS_OK;
    }
  }

  // if the file was written successfully, set it as the system wallpaper
  nsCOMPtr<nsIGConfService> gconf(do_GetService(NS_GCONFSERVICE_CONTRACTID));

  if (gconf) {
    gconf->SetString(NS_LITERAL_CSTRING(DGB_OPTIONS), nsDependentCString(options));

    // Set the image to an empty string first to force a refresh (since we could
    // be writing a new image on top of an existing SeaMonkey_wallpaper.png
    // and nautilus doesn't monitor the file for changes).
    gconf->SetString(NS_LITERAL_CSTRING(DGB_IMAGE), EmptyCString());
    gconf->SetString(NS_LITERAL_CSTRING(DGB_IMAGE), filePath);
    gconf->SetBool(NS_LITERAL_CSTRING(DGB_DRAWBG), true);
  }

  return NS_OK;
}
Example #22
0
QString ProFileDocument::suggestedFileName() const
{
    return filePath().fileName();
}
Example #23
0
std::string File::shortInfo() const
{
    return filePath();
}
// ---------------------------------------------------------------------------
// From MMPXPlaybackCallback
// Handle media
// ---------------------------------------------------------------------------
//
void CAiPlayerPluginEngine::HandleMediaL( const CMPXMedia& aMedia, 
        TInt aError )
    {
    if ( KErrNone == aError )
        {
        delete iUri;
        iUri = NULL;
        if (aMedia.IsSupported(KMPXMediaGeneralUri))
            {
            TParsePtrC filePath(aMedia.ValueText(KMPXMediaGeneralUri) );
            iUri = filePath.FullName().AllocL();
            }
        
		delete iTitle;
		iTitle = NULL;
        if ( aMedia.IsSupported( KMPXMediaGeneralTitle ) )
            {
            iTitle = ( aMedia.ValueText( KMPXMediaGeneralTitle ) ).AllocL();
            }
        else if ( aMedia.IsSupported( KMPXMediaGeneralDuration))
        {
            RDebug::Print(_L("duration found"));
            TInt val=aMedia.ValueTObjectL<TInt>( KMPXMediaGeneralDuration );
            RDebug::Print(_L("val %d"),val);
            iDuration=val/KMPXOneSecInMilliSecs;
        }
        else if ( aMedia.IsSupported( KMPXMediaGeneralUri ) )
            {
            TParsePtrC filePath( aMedia.ValueText( KMPXMediaGeneralUri ) );
            iTitle = (filePath.Name()).AllocL();
            }
		delete iArtist;
		iArtist = NULL;
		if ( aMedia.IsSupported( KMPXMediaMusicArtist ) )
		    {
		    iArtist = ( aMedia.ValueText( KMPXMediaMusicArtist ) ).AllocL();
		    }

		iObserver->TrackInfoChanged(iTitle ? *iTitle : KNullDesC(), iArtist ? *iArtist : KNullDesC());

		if (!iSkipping)
            {
            if (iExtractingAlbumArt)
                {
                if (iAlbumArtUtil){iAlbumArtUtil->CancelRequest();}
                iExtractingAlbumArt=EFalse;
                }
            
            if ( aMedia.IsSupported( KMPXMediaMusicAlbumArtFileName ) )
                {
                delete iMedia;
                iMedia=NULL;
                iMedia = CMPXMedia::NewL( aMedia );
                TRAPD(err,iAlbumArtUtil->ExtractAlbumArtL(
                        *iMedia,
                        *this,
                        KAlbumArtSize,
                        EFalse));
                
                if (err != KErrNone)
                    {
                    iObserver->AlbumArtChanged(NULL);
                    }
                }
            else
                {
                iObserver->AlbumArtChanged(NULL);
                }

            }
		else
		    {
		    iObserver->AlbumArtChanged(NULL);
		    }
        }
    }
String WebInspectorProxy::inspectorPageURL() const
{
    GOwnPtr<gchar> filePath(g_build_filename(inspectorFilesBasePath(), "inspector.html", NULL));
    GOwnPtr<gchar> fileURI(g_filename_to_uri(filePath.get(), 0, 0));
    return WebCore::filenameToString(fileURI.get());
}
Example #26
0
/*!
  Returns the file name part of the file path, ie the
  current file.  Must not be called on an empty Location
  object.
 */
QString Location::fileName() const
{
    QString fp = filePath();
    return fp.mid(fp.lastIndexOf('/') + 1);
}
Example #27
0
DatabaseWidget::DatabaseWidget(Database* db, QWidget* parent)
    : QStackedWidget(parent)
    , m_db(db)
    , m_searchUi(new Ui::SearchWidget())
    , m_searchWidget(new QWidget())
    , m_newGroup(Q_NULLPTR)
    , m_newEntry(Q_NULLPTR)
    , m_newParent(Q_NULLPTR)
{
    m_searchUi->setupUi(m_searchWidget);

    m_searchTimer = new QTimer(this);
    m_searchTimer->setSingleShot(true);

    m_mainWidget = new QWidget(this);
    QLayout* layout = new QHBoxLayout(m_mainWidget);
    QSplitter* splitter = new QSplitter(m_mainWidget);

    QWidget* rightHandSideWidget = new QWidget(splitter);
    m_searchWidget->setParent(rightHandSideWidget);

    m_groupView = new GroupView(db, splitter);
    m_groupView->setObjectName("groupView");
    m_groupView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_groupView, SIGNAL(customContextMenuRequested(QPoint)),
            SLOT(emitGroupContextMenuRequested(QPoint)));

    m_entryView = new EntryView(rightHandSideWidget);
    m_entryView->setObjectName("entryView");
    m_entryView->setContextMenuPolicy(Qt::CustomContextMenu);
    m_entryView->setGroup(db->rootGroup());
    connect(m_entryView, SIGNAL(customContextMenuRequested(QPoint)),
            SLOT(emitEntryContextMenuRequested(QPoint)));

    QSizePolicy policy;
    policy = m_groupView->sizePolicy();
    policy.setHorizontalStretch(30);
    m_groupView->setSizePolicy(policy);
    policy = rightHandSideWidget->sizePolicy();
    policy.setHorizontalStretch(70);
    rightHandSideWidget->setSizePolicy(policy);

    QAction* closeAction = new QAction(m_searchWidget);
    QIcon closeIcon = filePath()->icon("actions", "dialog-close");
    closeAction->setIcon(closeIcon);
    m_searchUi->closeSearchButton->setDefaultAction(closeAction);
    m_searchUi->closeSearchButton->setShortcut(Qt::Key_Escape);
    m_searchWidget->hide();
    m_searchUi->caseSensitiveCheckBox->setVisible(false);

    QVBoxLayout* vLayout = new QVBoxLayout(rightHandSideWidget);
    vLayout->setMargin(0);
    vLayout->addWidget(m_searchWidget);
    vLayout->addWidget(m_entryView);

    rightHandSideWidget->setLayout(vLayout);

    splitter->addWidget(m_groupView);
    splitter->addWidget(rightHandSideWidget);

    layout->addWidget(splitter);
    m_mainWidget->setLayout(layout);

    m_editEntryWidget = new EditEntryWidget();
    m_editEntryWidget->setObjectName("editEntryWidget");
    m_historyEditEntryWidget = new EditEntryWidget();
    m_editGroupWidget = new EditGroupWidget();
    m_editGroupWidget->setObjectName("editGroupWidget");
    m_changeMasterKeyWidget = new ChangeMasterKeyWidget();
    m_changeMasterKeyWidget->headlineLabel()->setText(tr("Change master key"));
    QFont headlineLabelFont = m_changeMasterKeyWidget->headlineLabel()->font();
    headlineLabelFont.setBold(true);
    headlineLabelFont.setPointSize(headlineLabelFont.pointSize() + 2);
    m_changeMasterKeyWidget->headlineLabel()->setFont(headlineLabelFont);
    m_databaseSettingsWidget = new DatabaseSettingsWidget();
    m_databaseSettingsWidget->setObjectName("databaseSettingsWidget");
    m_databaseOpenWidget = new DatabaseOpenWidget();
    m_databaseOpenWidget->setObjectName("databaseOpenWidget");
    m_keepass1OpenWidget = new KeePass1OpenWidget();
    m_keepass1OpenWidget->setObjectName("keepass1OpenWidget");
    m_unlockDatabaseWidget = new UnlockDatabaseWidget();
    m_unlockDatabaseWidget->setObjectName("unlockDatabaseWidget");
    addWidget(m_mainWidget);
    addWidget(m_editEntryWidget);
    addWidget(m_editGroupWidget);
    addWidget(m_changeMasterKeyWidget);
    addWidget(m_databaseSettingsWidget);
    addWidget(m_historyEditEntryWidget);
    addWidget(m_databaseOpenWidget);
    addWidget(m_keepass1OpenWidget);
    addWidget(m_unlockDatabaseWidget);

    connect(m_groupView, SIGNAL(groupChanged(Group*)), this, SLOT(clearLastGroup(Group*)));
    connect(m_groupView, SIGNAL(groupChanged(Group*)), SIGNAL(groupChanged()));
    connect(m_groupView, SIGNAL(groupChanged(Group*)), m_entryView, SLOT(setGroup(Group*)));
    connect(m_entryView, SIGNAL(entryActivated(Entry*, EntryModel::ModelColumn)),
            SLOT(entryActivationSignalReceived(Entry*, EntryModel::ModelColumn)));
    connect(m_entryView, SIGNAL(entrySelectionChanged()), SIGNAL(entrySelectionChanged()));
    connect(m_editEntryWidget, SIGNAL(editFinished(bool)), SLOT(switchToView(bool)));
    connect(m_editEntryWidget, SIGNAL(historyEntryActivated(Entry*)), SLOT(switchToHistoryView(Entry*)));
    connect(m_historyEditEntryWidget, SIGNAL(editFinished(bool)), SLOT(switchBackToEntryEdit()));
    connect(m_editGroupWidget, SIGNAL(editFinished(bool)), SLOT(switchToView(bool)));
    connect(m_changeMasterKeyWidget, SIGNAL(editFinished(bool)), SLOT(updateMasterKey(bool)));
    connect(m_databaseSettingsWidget, SIGNAL(editFinished(bool)), SLOT(switchToView(bool)));
    connect(m_databaseOpenWidget, SIGNAL(editFinished(bool)), SLOT(openDatabase(bool)));
    connect(m_keepass1OpenWidget, SIGNAL(editFinished(bool)), SLOT(openDatabase(bool)));
    connect(m_unlockDatabaseWidget, SIGNAL(editFinished(bool)), SLOT(unlockDatabase(bool)));
    connect(this, SIGNAL(currentChanged(int)), this, SLOT(emitCurrentModeChanged()));
    connect(m_searchUi->searchEdit, SIGNAL(textChanged(QString)), this, SLOT(startSearchTimer()));
    connect(m_searchUi->caseSensitiveCheckBox, SIGNAL(toggled(bool)), this, SLOT(startSearch()));
    connect(m_searchUi->searchCurrentRadioButton, SIGNAL(toggled(bool)), this, SLOT(startSearch()));
    connect(m_searchUi->searchRootRadioButton, SIGNAL(toggled(bool)), this, SLOT(startSearch()));
    connect(m_searchTimer, SIGNAL(timeout()), this, SLOT(search()));
    connect(closeAction, SIGNAL(triggered()), this, SLOT(closeSearch()));

    setCurrentWidget(m_mainWidget);
}
Example #28
0
static void DeserializePrefs(const char *prefsTxt, SerializableGlobalPrefs& globalPrefs,
    FileHistory& fh, Favorites *favs)
{
    BencObj *obj = BencObj::Decode(prefsTxt);
    if (!obj || obj->Type() != BT_DICT)
        goto Exit;
    BencDict *prefs = static_cast<BencDict *>(obj);
    BencDict *global = prefs->GetDict(GLOBAL_PREFS_STR);
    if (!global)
        goto Exit;

    Retrieve(global, TOOLBAR_VISIBLE_STR, globalPrefs.toolbarVisible);
    Retrieve(global, TOC_VISIBLE_STR, globalPrefs.tocVisible);
    Retrieve(global, FAV_VISIBLE_STR, globalPrefs.favVisible);

    Retrieve(global, SIDEBAR_DX_STR, globalPrefs.sidebarDx);
    Retrieve(global, TOC_DY_STR, globalPrefs.tocDy);
    Retrieve(global, PDF_ASSOCIATE_DONT_ASK_STR, globalPrefs.pdfAssociateDontAskAgain);
    Retrieve(global, PDF_ASSOCIATE_ASSOCIATE_STR, globalPrefs.pdfAssociateShouldAssociate);
    Retrieve(global, ESC_TO_EXIT_STR, globalPrefs.escToExit);
    Retrieve(global, USE_SYS_COLORS_STR, globalPrefs.useSysColors);
    Retrieve(global, BG_COLOR_STR, globalPrefs.bgColor);
    Retrieve(global, ENABLE_AUTO_UPDATE_STR, globalPrefs.enableAutoUpdate);
    Retrieve(global, REMEMBER_OPENED_FILES_STR, globalPrefs.rememberOpenedFiles);
    Retrieve(global, GLOBAL_PREFS_ONLY_STR, globalPrefs.globalPrefsOnly);
    Retrieve(global, SHOW_RECENT_FILES_STR, globalPrefs.showStartPage);

    Retrieve(global, DISPLAY_MODE_STR, globalPrefs.defaultDisplayMode);
    Retrieve(global, ZOOM_VIRTUAL_STR, globalPrefs.defaultZoom);
    Retrieve(global, WINDOW_STATE_STR, globalPrefs.windowState);

    Retrieve(global, WINDOW_X_STR, globalPrefs.windowPos.x);
    Retrieve(global, WINDOW_Y_STR, globalPrefs.windowPos.y);
    Retrieve(global, WINDOW_DX_STR, globalPrefs.windowPos.dx);
    Retrieve(global, WINDOW_DY_STR, globalPrefs.windowPos.dy);

    Retrieve(global, INVERSE_SEARCH_COMMANDLINE, globalPrefs.inverseSearchCmdLine);
    Retrieve(global, ENABLE_TEX_ENHANCEMENTS_STR, globalPrefs.enableTeXEnhancements);
    Retrieve(global, VERSION_TO_SKIP_STR, globalPrefs.versionToSkip);
    RetrieveRaw(global, LAST_UPDATE_STR, globalPrefs.lastUpdateTime);

    const char *lang = GetRawString(global, UI_LANGUAGE_STR);
    const char *langCode = trans::ValidateLanguageCode(lang);
    if (langCode)
        globalPrefs.currentLanguage = langCode;

    Retrieve(global, FWDSEARCH_OFFSET, globalPrefs.fwdSearch.offset);
    Retrieve(global, FWDSEARCH_COLOR, globalPrefs.fwdSearch.color);
    Retrieve(global, FWDSEARCH_WIDTH, globalPrefs.fwdSearch.width);
    Retrieve(global, FWDSEARCH_PERMANENT, globalPrefs.fwdSearch.permanent);

    Retrieve(global, CBX_RIGHT2LEFT, globalPrefs.cbxR2L);

    Retrieve(global, OPEN_COUNT_WEEK_STR, globalPrefs.openCountWeek);
    int weekDiff = GetWeekCount() - globalPrefs.openCountWeek;
    globalPrefs.openCountWeek = GetWeekCount();

    BencArray *fileHistory = prefs->GetArray(FILE_HISTORY_STR);
    if (!fileHistory)
        goto Exit;
    size_t dlen = fileHistory->Length();
    for (size_t i = 0; i < dlen; i++) {
        BencDict *dict = fileHistory->GetDict(i);
        assert(dict);
        if (!dict) continue;
        DisplayState *state = DeserializeDisplayState(dict, globalPrefs.globalPrefsOnly);
        if (state) {
            // "age" openCount statistics (cut in in half after every week)
            state->openCount >>= weekDiff;
            fh.Append(state);
        }
    }

    BencArray *favsArr = prefs->GetArray(FAVS_STR);
    if (!favsArr)
        goto Exit;
    for (size_t i = 0; i < favsArr->Length(); i += 2) {
        BencString *filePathBenc = favsArr->GetString(i);
        BencArray *favData = favsArr->GetArray(i+1);
        if (!filePathBenc || !favData)
            break;
        ScopedMem<WCHAR> filePath(filePathBenc->Value());
        for (size_t j = 0; j < favData->Length(); j += 2) {
            // we're lenient about errors
            BencInt *pageNoBenc = favData->GetInt(j);
            BencString *nameBenc = favData->GetString(j + 1);
            if (!pageNoBenc || !nameBenc)
                break;
            int pageNo = (int)pageNoBenc->Value();
            ScopedMem<WCHAR> name(nameBenc->Value());
            favs->AddOrReplace(filePath, pageNo, EmptyToNull(name));
        }
    }

Exit:
    delete obj;
}
/*!
    Returns a QFileInfo for the current directory entry. If the current entry
    is invalid (i.e., isValid() returns false), a null QFileInfo is returned.

    \sa filePath(), fileName()
*/
QFileInfo QFileSystemIterator::fileInfo() const
{
    return QFileInfo(filePath());
}
//-----------------------------------------------------------------------------
int ctkAbstractPluginFactoryTest1(int argc, char * argv [])
{
  QCoreApplication app(argc, argv);

  if (argc <= 1)
    {
    std::cerr << "Missing argument" << std::endl;
    return EXIT_FAILURE;
    }
  QString filePath(argv[1]);
  QFileInfo file(filePath);
  while (filePath.contains("$(OutDir)"))
    {
    QString debugFilePath = filePath;
    debugFilePath.replace("$(OutDir)","Debug");
    if (QFile::exists(QString(debugFilePath)))
      {
      file = QFileInfo(debugFilePath);
      break;
      }
    QString releaseFilePath = filePath;
    releaseFilePath.replace("$(OutDir)","Release");
    if (QFile::exists(QString(releaseFilePath)))
      {
      file = QFileInfo(releaseFilePath);
      break;
      }
    return EXIT_FAILURE;
    }
  ctkAbstractPluginFactory< ctkDummyPlugin > pluginFactory;
  pluginFactory.setVerbose(true);

  QString itemKey = pluginFactory.registerFileItem(QFileInfo("foo/bar.txt"));
  if (!itemKey.isEmpty())
    {
    std::cerr << "ctkAbstractPluginFactory::registerLibrary() registered bad file"
              << std::endl;
    return EXIT_FAILURE;
    }

  itemKey = pluginFactory.registerFileItem(file);
  if (itemKey.isEmpty() || pluginFactory.itemKeys().count() != 1)
    {
    std::cerr << __LINE__ << ": ctkAbstractPluginFactory::registerLibrary() failed: "
              << pluginFactory.itemKeys().count() << std::endl;
    return EXIT_FAILURE;
    }
  // register twice must return false
  itemKey = pluginFactory.registerFileItem(file);
  if (itemKey.isEmpty() || pluginFactory.itemKeys().count() != 1)
    {
    std::cerr << __LINE__ << ": ctkAbstractPluginFactory::registerLibrary() failed: "
              << qPrintable(itemKey) << " count: "
              << pluginFactory.itemKeys().count() << std::endl;
    return EXIT_FAILURE;
    }
  if (QFileInfo(pluginFactory.path(itemKey)) != file)
    {
    std::cerr << __LINE__ << ": ctkAbstractPluginFactory::registerLibrary() failed: "
              << pluginFactory.path(itemKey).toStdString() << std::endl;
    return EXIT_FAILURE;
    }

  ctkDummyPlugin* plugin = pluginFactory.instantiate(itemKey);
  if (plugin == 0)
    {
    std::cerr << __LINE__ << ": ctkAbstractPluginFactory::instantiate() failed" << std::endl;
    return EXIT_FAILURE;
    }

  pluginFactory.uninstantiate(itemKey);

  // ctkDummyPlugin is not a QPushButton, it should fail then.
  ctkAbstractPluginFactory< QTimer > buttonPluginFactory;
  buttonPluginFactory.setVerbose(true);
  // it should register but fail while instanciating
  itemKey = buttonPluginFactory.registerFileItem(file);
  if (itemKey.isEmpty() || buttonPluginFactory.itemKeys().count() != 1)
    {
    std::cerr << __LINE__ << ": ctkAbstractPluginFactory::registerLibrary() failed" << std::endl;
    return EXIT_FAILURE;
    }
  QTimer* timer = buttonPluginFactory.instantiate("foo");
  if (timer != 0)
    {
    std::cerr << __LINE__ << ": ctkAbstractPluginFactory::instantiate() failed" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}