int svlVideoCodecTCPStream::SetCompression(const svlVideoIO::Compression *compression)
{
    if (Opened || !compression || compression->size < sizeof(svlVideoIO::Compression)) return SVL_FAIL;

    std::string extensionlist(GetExtensions());
    std::string extension(compression->extension);
    extension += ";";
    if (extensionlist.find(extension) == std::string::npos) {
        // Codec parameters do not match this codec
        return SVL_FAIL;
    }

    svlVideoIO::ReleaseCompression(Codec);
    Codec = reinterpret_cast<svlVideoIO::Compression*>(new unsigned char[sizeof(svlVideoIO::Compression)]);

    std::string name("CISST Video Stream over TCP/IP");
    memset(&(Codec->extension[0]), 0, 16);
    memcpy(&(Codec->extension[0]), extension.c_str(), std::min(static_cast<int>(extension.length()) - 1, 15));
    memset(&(Codec->name[0]), 0, 64);
    memcpy(&(Codec->name[0]), name.c_str(), std::min(static_cast<int>(name.length()), 63));
    Codec->size = sizeof(svlVideoIO::Compression);
    Codec->datasize = 1;

    unsigned char max, defaultval;
    if (extension == ".ncvi;") {
        max        = 9;
        defaultval = 4;
    }
    else if (extension == ".njpg;") {
        max        = 100;
        defaultval = 75;
    }
    if (compression->data[0] > max) Codec->data[0] = defaultval;
    else Codec->data[0] = compression->data[0];

    return SVL_OK;
}
Example #2
0
void SetFileName(
/***********************************************************************/
HWND	hDlg,
int		idCtl,
LPSTR	lpFileSpec,
LPSTR	lpSaveName,
BOOL	bSaving)
{
FNAME szName, szSpec, szExt;

if (bSaving && !fUntitled)
	{
	lstrcpy( szName, stripdir(lpSaveName) );
	stripext( szName );
	lstrcpy( szExt, extension(lpFileSpec) );
	lstrcpy( szSpec, lpFileSpec );
	stripfile( szSpec );
	FixPath( szSpec );
	lstrcat( szSpec, szName );
	lstrcat( szSpec, szExt );
	SetDlgItemText( hDlg, idCtl, Lowercase(szSpec) );
	}
else	SetDlgItemText( hDlg, idCtl, Lowercase(lpFileSpec) );
}
Example #3
0
void directory_get_files_with_ext(const std::string & dir, 
                                    const std::string & ext,
                                    std::list<std::string> & list) {
    boost::filesystem::path p(dir);
    
    if(!exists(p)) {
      return;
    }
    boost::filesystem::directory_iterator end_itr; 
    for ( boost::filesystem::directory_iterator itr( p );
          itr != end_itr;
          ++itr )
    {
      // is_regular() is deprecated but is_regular_file isn't in 1.34.
      if ( is_regular(*itr) && (ext.empty() || (std_string_to_lower(extension(*itr)) == ext)) )
      {
#if BOOST_VERSION >= 104601
        list.push_back(itr->path().string());
#else
        list.push_back(itr->string());
#endif
      }
    }
  }
QList<SmartPointer<IExtension> > CombinedEventDelta::GetExtensions(const IExtensionPointFilter& filter) const
{
  QList<int> extensions;
  if (!filter.IsNull() && !d->extensionsByID.isEmpty())
  {
    extensions = FilterExtensions(filter);
  }
  else if (filter.IsNull())
  {
    extensions = d->allExtensions;
  }

  if (extensions.isEmpty()) // no changes that fit the filter
    return QList<IExtension::Pointer>();

  QList<IExtension::Pointer> result;
  for (int i = 0; i < extensions.size(); ++i)
  {
    int ext = extensions[i];
    IExtension::Pointer extension(new ExtensionHandle(d->objectManager, ext));
    result.push_back(extension);
  }
  return result;
}
	//TODO: make this function use file hashes instead
	std::vector<fs::path> get_dupes_from_files(const std::vector<fs::path> &files)
	{
		std::vector<fs::path> dupes;
		uintmax_t prev = 0, curr = 0;
		std::string file_exten_prev, file_exten_curr;

		for (auto it = files.crbegin(); it != files.crend(); ++it) //loops in reverse alphabetical order
		{
			file_exten_curr = it->extension().string();
			curr = fs::file_size(*it);

			//we assume a file is a duplicate if the file is next to a file alphabetically with the same file size
			if (file_exten_curr == file_exten_prev && prev == curr && prev != 0)
			{
				std::cout << it->filename().string() << std::endl;
				dupes.push_back(*it);
			}

			prev = curr;
			file_exten_prev = file_exten_curr;
		}

		return dupes;
	}	
Example #6
0
void
CSDReader::softpkg (DOMElement* element)
throw(CSDReadException)
{
	if ( !package_ ) abort();
	std::string element_name;
    DOMNode* child = element->getFirstChild();
	while (child != 0)
	{
		if (child->getNodeType() == DOMNode::ELEMENT_NODE)
		{
			element_name = Qedo::transcode(child->getNodeName());

			//
			// title
			//
			if (element_name == "title")
			{
				title((DOMElement*)child);
			}

			//
			// pkgtype
			//
			else if (element_name == "pkgtype")
			{
				pkgtype((DOMElement*)child);
			}

			//
			// repository
			//
			else if (element_name == "repository")
			{
				// TODO
			}

			//
			// author
			//
			else if (element_name == "author")
			{
				author((DOMElement*)child);
			}

			//
			// description
			//
			else if (element_name == "description")
			{
				description((DOMElement*)child);
			}

			//
			// license
			//
			else if (element_name == "license")
			{
				license((DOMElement*)child);
			}

			//
			// idl
			//
			else if (element_name == "idl")
			{
				idl((DOMElement*)child);
			}

			//
			// propertyfile
			//
			else if (element_name == "propertyfile")
			{
				propertyfile((DOMElement*)child);
			}

			//
			// dependency
			//
			else if (element_name == "dependency")
			{
				dependency((DOMElement*)child);
			}

			//
			// extension
			//
			else if (element_name == "extension")
			{
				extension((DOMElement*)child);
			}
		}

		// get next child
		child = child->getNextSibling();
    }

	DOMNodeList* nodeList;
	DOMElement* elem;
	unsigned int len = 0;
	unsigned int i = 0;
	std::string uuid = data_->uuid;

    //
	// implementation
	//
	nodeList = element->getElementsByTagName(X("implementation"));
	len = nodeList->getLength();
	bool impl_found = false;
    for (i = 0; i < len; ++i)
    {
		elem = (DOMElement*)(nodeList->item(i));
		if (!XMLString::compareString(elem->getAttribute(X("id")), X(uuid.c_str())))
		{
			impl_found = true;
			break;
		}
    }
	if(impl_found)
	{
		implementation(elem);
	}
	else
	{
		NORMAL_ERR3( "CSDReader: implementation for ", uuid, " missing!" );
		throw CSDReadException();
	}

    //
	// corba component descriptor
	//
    if (ccd_file_.empty())
    {
		nodeList = element->getElementsByTagName(X("descriptor"));
		len = nodeList->getLength();
		if(len == 1)
		{
			ccd_file_ = descriptor((DOMElement*)(nodeList->item(0)));
		}
		else if(len > 1)
		{
			NORMAL_ERR( "CSDReader: multiple descriptor elements!" );
		}

		if (ccd_file_.empty())
        {
			NORMAL_ERR2( "CSDReader: missing component descriptor for ", uuid );
	        throw CSDReadException();
        }
    }
	//
	// parse the corba component descriptor file
    //
	CCDReader reader( path_ + ccd_file_, path_ );
	reader.readCCD( &(data_->component), package_ );
}
::boost::shared_ptr<Bundle> BundleDescriptorReader::processPlugin(xmlNodePtr node, const ::boost::filesystem::path& location) throw(RuntimeException)
{
    // Creates the bundle.
    ::boost::shared_ptr<Bundle> bundle;
    // Processes all plugin attributes.
    xmlAttrPtr  curAttr;
    std::string bundleIdentifier;
    std::string version;
    std::string pluginClass;
    for(curAttr = node->properties; curAttr != 0; curAttr = curAttr->next)
    {
        if(xmlStrcmp(curAttr->name, (const xmlChar*) ID.c_str()) == 0)
        {
            bundleIdentifier = (const char*) curAttr->children->content;
            continue;
        }

        if(xmlStrcmp(curAttr->name, (const xmlChar*) CLASS.c_str()) == 0)
        {
            pluginClass = (const char*) curAttr->children->content;
            continue;
        }

        if(xmlStrcmp(curAttr->name, (const xmlChar*) VERSION.c_str()) == 0)
        {
            version = (const char*) curAttr->children->content;
            continue;
        }
    }
    SLM_ASSERT("bundle identifier is empty", !bundleIdentifier.empty());

    if( ::fwRuntime::Runtime::getDefault()->findBundle(bundleIdentifier, Version(version)))
    {
        return bundle;
    }
    if(pluginClass.empty() == true)
    {
        bundle = ::boost::shared_ptr<Bundle>( new Bundle(location, bundleIdentifier, version) );
    }
    else
    {
        bundle = ::boost::shared_ptr<Bundle>( new Bundle(location, bundleIdentifier, version, pluginClass) );
    }

    // Processes all child nodes.
    xmlNodePtr curChild;
    for(curChild = node->children; curChild != 0; curChild = curChild->next)
    {
        // Skip non element nodes.
        if(curChild->type != XML_ELEMENT_NODE)
        {
            continue;
        }

        // Extension declaration.
        if(xmlStrcmp(curChild->name, (const xmlChar*) EXTENSION.c_str()) == 0)
        {
            ::boost::shared_ptr<Extension> extension(processExtension(curChild, bundle));
            bundle->addExtension(extension);
            continue;
        }

        // Extension point declaration.
        if(xmlStrcmp(curChild->name, (const xmlChar*) EXTENSION_POINT.c_str()) == 0)
        {
            ::boost::shared_ptr<ExtensionPoint> point(processExtensionPoint(curChild, bundle));
            bundle->addExtensionPoint(point);
            continue;
        }

        // Library declaration.
        if(xmlStrcmp(curChild->name, (const xmlChar*) LIBRARY.c_str()) == 0)
        {
            ::boost::shared_ptr<dl::Library> library(processLibrary(curChild));
            bundle->addLibrary(library);
            continue;
        }

        // Requirement declaration.
        if(xmlStrcmp(curChild->name, (const xmlChar*) REQUIREMENT.c_str()) == 0)
        {
            const std::string   requirement(processRequirement(curChild));
            bundle->addRequirement(requirement);
        }

        // Point declaration.
        if(xmlStrcmp(curChild->name, (const xmlChar*) POINT.c_str()) == 0)
        {
            SLM_FATAL("Sorry, this xml element  ( <point ... > </point> ) is depreciated (" + location.string() + ")" );
        }
    }

    // Job's done.
    return bundle;
}
QVariant DhQGraphicsItemGroup::Dvhextension(const QVariant& x1) const {
  return extension(x1);
}
Example #9
0
File: user.c Project: dborca/mc
char *
expand_format (struct WEdit *edit_widget, char c, int quote)
{
    WPanel *panel = NULL;
    char *(*quote_func) (const char *, int);
    char *fname;
    char *result;
    char c_lc;

    if (c == '%')
	return g_strdup ("%");

    if (edit_one_file != NULL)
	fname = edit_widget->filename;
    else {
	if (islower ((unsigned char) c))
	    panel = current_panel;
	else {
	    if (get_other_type () != view_listing)
		return g_strdup ("");
	    panel = other_panel;
	}
	fname = panel->dir.list[panel->selected].fname;
    }

    if (quote)
	quote_func = name_quote;
    else
	quote_func = fake_name_quote;

    c_lc = tolower ((unsigned char) c);

    switch (c_lc) {
    case 'f':
    case 'p':
	return (*quote_func) (fname, 0);
    case 'x':
	return (*quote_func) (extension (fname), 0);
    case 'd':
	{
	    char *cwd;
	    char *qstr;

	    cwd = g_malloc(MC_MAXPATHLEN + 1);

	    if (panel)
		g_strlcpy(cwd, panel->cwd, MC_MAXPATHLEN + 1);
	    else
		mc_get_current_wd(cwd, MC_MAXPATHLEN + 1);

	    qstr = (*quote_func) (cwd, 0);

	    g_free (cwd);

	    return qstr;
	}
    case 'i':			/* indent equal number cursor position in line */
	if (edit_widget)
	    return g_strnfill (edit_widget->curs_col, ' ');
	break;
    case 'y':			/* syntax type */
	if (edit_widget && edit_widget->syntax_type)
	    return g_strdup (edit_widget->syntax_type);
	break;
    case 'k':			/* block file name */
    case 'b':			/* block file name / strip extension */  {
	    if (edit_widget) {
		char *file = g_strconcat (home_dir, PATH_SEP_STR BLOCK_FILE, (char *) NULL);
		fname = (*quote_func) (file, 0);
		g_free (file);
		return fname;
	    } else if (c_lc == 'b') {
		return strip_ext ((*quote_func) (fname, 0));
	    }
	    break;
	}
    case 'e':			/* was "cooledit.error" */
	return g_strdup("/dev/null");
    case 'n':			/* strip extension in editor */
	if (edit_widget)
	    return strip_ext ((*quote_func) (fname, 0));
	break;
    case 'm':			/* menu file name */
	if (menu)
	    return (*quote_func) (menu, 0);
	break;
    case 's':
	if (!panel || !panel->marked)
	    return (*quote_func) (fname, 0);

	/* Fall through */

    case 't':
    case 'u':
	{
	    int length = 2, i;
	    char *block, *tmp;

	    if (!panel)
		return g_strdup ("");

	    for (i = 0; i < panel->count; i++)
		if (panel->dir.list[i].f.marked)
		    length += strlen (panel->dir.list[i].fname) + 1;	/* for space */

	    block = g_malloc (length * 2 + 1);
	    *block = 0;
	    for (i = 0; i < panel->count; i++)
		if (panel->dir.list[i].f.marked) {
		    strcat (block, tmp =
			    (*quote_func) (panel->dir.list[i].fname, 0));
		    g_free (tmp);
		    strcat (block, " ");
		    if (c_lc == 'u')
			do_file_mark (panel, i, 0);
		}
	    return block;
	}			/* sub case block */
    }				/* switch */
    result = g_strdup ("% ");
    result[1] = c;
    return result;
}
Example #10
0
QString FileItem::extension( void )
{
	return extension( fullName() );
}
Example #11
0
void ExtensionsLoader::LoadExtension(const gd::String & fullpath, gd::Platform & platform, bool forgiving)
{
    if ( platform.GetExtensionCreateFunctionName().empty() )
    {
        cout << "Unable to load extension " << fullpath << ":" << endl;
        cout << "The plaftorm does not support extensions creation." << endl;
        return;
    }

    Handle extensionHdl = OpenLibrary(fullpath.c_str());
    if (extensionHdl == NULL)
    {
        gd::String error = DynamicLibraryLastError();

        cout << "Unable to load extension " << fullpath << "." << endl;
        cout << "Error returned : \"" << error << "\"" << endl;
        #if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
        wxString userMsg = _("Extension ")+ fullpath + _(" could not be loaded.\nContact the developer for more informations.\n\nDetailed log:\n") + error;
        wxMessageBox(userMsg, _("Extension not compatible"), wxOK | wxICON_EXCLAMATION);
        #endif

        return;
    }

    createExtension create_extension = (createExtension)GetSymbol(extensionHdl, platform.GetExtensionCreateFunctionName().c_str());

    if (create_extension == NULL)
    {
        if (!forgiving)
        {
            cout << "Unable to load extension " << fullpath << " (Creation function symbol not found)." << endl;
            #if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
            wxString userMsg = _("Extension ")+ fullpath + _(" could not be loaded.\nContact the developer for more informations." );
            wxMessageBox(userMsg, _("Extension not compatible"), wxOK | wxICON_EXCLAMATION);
            #endif
        }

        CloseLibrary(extensionHdl);
        return;
    }

    #if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
    gd::LocaleManager::Get()->AddCatalog(wxFileName(fullpath).GetName()); //In editor, load catalog associated with extension, if any.
    #endif

    gd::PlatformExtension * extensionPtr = create_extension();
    gd::String error;

    //Perform safety check about the compilation
    if ( !extensionPtr->compilationInfo.informationCompleted )
        error += "Compilation information not filled.\n";

    #if defined(GD_IDE_ONLY)
    else if ( extensionPtr->compilationInfo.runtimeOnly )
        error += "Extension compiled for runtime only.\n";

    #if !defined(GD_NO_WX_GUI)
    else if ( extensionPtr->compilationInfo.wxWidgetsMajorVersion != wxMAJOR_VERSION ||
              extensionPtr->compilationInfo.wxWidgetsMinorVersion != wxMINOR_VERSION ||
              extensionPtr->compilationInfo.wxWidgetsReleaseNumber != wxRELEASE_NUMBER ||
              extensionPtr->compilationInfo.wxWidgetsSubReleaseNumber != wxSUBRELEASE_NUMBER )
        error += "Not the same wxWidgets version.\n";
    #endif
    #endif
    #if defined(__GNUC__)
    else if ( extensionPtr->compilationInfo.gccMajorVersion != __GNUC__ ||
              extensionPtr->compilationInfo.gccMinorVersion != __GNUC_MINOR__ )
        error += "Not the same GNU Compiler version.\n";

    #endif
    else if ( extensionPtr->compilationInfo.sfmlMajorVersion != 2 ||
              extensionPtr->compilationInfo.sfmlMinorVersion != 0 )
        error += "Not the same SFML version.\n";

    else if ( extensionPtr->compilationInfo.gdCoreVersion != GDCore_RC_FILEVERSION_STRING)
        error += "Not the same GDevelop Core version.\n(Extension is using "+extensionPtr->compilationInfo.gdCoreVersion+", GDevelop is using "+GDCore_RC_FILEVERSION_STRING+")\n";

    else if ( extensionPtr->compilationInfo.sizeOfpInt != sizeof(int*))
        error += "Not the same architecture.\n(Extension sizeof(int*) is "+gd::String::From(extensionPtr->compilationInfo.sizeOfpInt)+", GDevelop sizeof(int*) is "+gd::String::From(sizeof(int*))+")\n";

    if ( !error.empty() )
    {
        char beep = 7;
        cout << "-- WARNING ! --" << beep << endl;
        cout << "Bad extension " + fullpath + " loaded :\n" + error;
        cout << "---------------" << endl;

        #if defined(RELEASE)//Load extension despite errors in non release build

        //Destroy the extension class THEN unload the library from memory
        delete extensionPtr;
        CloseLibrary(extensionHdl);
        #endif

        #if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI) && defined(RELEASE) //Show errors in IDE only
        wxString userMsg = _("Extension ") + fullpath + _(" has errors :\n") +
            error + _("\nThe extension was not loaded. Contact the developer to get more information." );
        wxMessageBox(userMsg, _("Extension not compatible"), wxOK | wxICON_EXCLAMATION);
        #endif

        #if defined(RELEASE)//Load extension despite errors in non release build
        return;
        #endif
    }

    std::shared_ptr<gd::PlatformExtension> extension(extensionPtr);
    platform.AddExtension(extension);
    return;
}
Example #12
0
VfsPath CColladaManager::GetLoadableFilename(const VfsPath& pathnameNoExtension, FileType type)
{
	std::wstring extn;
	switch (type)
	{
	case PMD: extn = L".pmd"; break;
	case PSA: extn = L".psa"; break;
		// no other alternatives
	}

	/*

	If there is a .dae file:
		* Calculate a hash to identify it.
		* Look for a cached .pmd file matching that hash.
		* If it exists, load it. Else, convert the .dae into .pmd and load it.
	Otherwise, if there is a (non-cache) .pmd file:
		* Load it.
	Else, fail.

	The hash calculation ought to be fast, since normally (during development)
	the .dae file will exist but won't have changed recently and so the cache
	would be used. Hence, just hash the file's size, mtime, and the converter
	version number (so updates of the converter can cause regeneration of .pmds)
	instead of the file's actual contents.

	TODO (maybe): The .dae -> .pmd conversion may fail (e.g. if the .dae is
	invalid or unsupported), but it may take a long time to start the conversion
	then realise it's not going to work. That will delay the loading of the game
	every time, which is annoying, so maybe it should cache the error message
	until the .dae is updated and fixed. (Alternatively, avoid having that many
	broken .daes in the game.)

	*/

	// (TODO: the comments and variable names say "pmd" but actually they can
	// be "psa" too.)

	VfsPath dae(pathnameNoExtension.ChangeExtension(L".dae"));
	if (! VfsFileExists(dae))
	{
		// No .dae - got to use the .pmd, assuming there is one
		return pathnameNoExtension.ChangeExtension(extn);
	}

	// There is a .dae - see if there's an up-to-date cached copy

	FileInfo fileInfo;
	if (g_VFS->GetFileInfo(dae, &fileInfo) < 0)
	{
		// This shouldn't occur for any sensible reasons
		LOGERROR(L"Failed to stat DAE file '%ls'", dae.string().c_str());
		return VfsPath();
	}

	// Build a struct of all the data we want to hash.
	// (Use ints and not time_t/off_t because we don't care about overflow
	// but do care about the fields not being 64-bit aligned)
	// (Remove the lowest bit of mtime because some things round it to a
	// resolution of 2 seconds)
#pragma pack(push, 1)
	struct { int version; int mtime; int size; } hashSource
		= { COLLADA_CONVERTER_VERSION, (int)fileInfo.MTime() & ~1, (int)fileInfo.Size() };
	cassert(sizeof(hashSource) == sizeof(int) * 3); // no padding, because that would be bad
#pragma pack(pop)

	// Calculate the hash, convert to hex
	u32 hash = fnv_hash(static_cast<void*>(&hashSource), sizeof(hashSource));
	wchar_t hashString[9];
	swprintf_s(hashString, ARRAY_SIZE(hashString), L"%08x", hash);
	std::wstring extension(L"_");
	extension += hashString;
	extension += extn;

	// realDaePath_ is "[..]/mods/whatever/art/meshes/whatever.dae"
	OsPath realDaePath_;
	Status ret = g_VFS->GetRealPath(dae, realDaePath_);
	ENSURE(ret == INFO::OK);
	wchar_t realDaeBuf[PATH_MAX];
	wcscpy_s(realDaeBuf, ARRAY_SIZE(realDaeBuf), realDaePath_.string().c_str());
	std::replace(realDaeBuf, realDaeBuf+ARRAY_SIZE(realDaeBuf), '\\', '/');
	const wchar_t* realDaePath = wcsstr(realDaeBuf, L"mods/");

	// cachedPmdVfsPath is "cache/mods/whatever/art/meshes/whatever_{hash}.pmd"
	VfsPath cachedPmdVfsPath = VfsPath("cache") / realDaePath;
	cachedPmdVfsPath = cachedPmdVfsPath.ChangeExtension(extension);

	// If it's not in the cache, we'll have to create it first
	if (! VfsFileExists(cachedPmdVfsPath))
	{
		if (! m->Convert(dae, cachedPmdVfsPath, type))
			return L""; // failed to convert
	}

	return cachedPmdVfsPath;
}
Example #13
0
int main (int argc, char *argv[])
{
	char *p, *pp, *bp;
	char **oldargv = argv;
	char **link_lib;
	long smacptr;
	int first = 1;
	char *asmdefs_global_end;

	macptr = 0;
	ctext = 0;
	argc--; argv++;
	errs = 0;
	sflag = 0;
	cdflag = 0;
	verboseflag = 0;
	startup_incl = 0;
	optimize = 2;	/* -O2 by default */
	overlayflag = 0;
	asmdefs[0] = '\0';

	while ((p = *argv++)) {
		if (*p == '-') {
			while (*++p) switch (*p) {
				case 't': case 'T':
					ctext = 1;
					break;

				case 'c':
					if ((*(p + 1) == 'd')) {
						cdflag = 1;	/* pass '-cd' to assembler */
						p++;
						break;
					}
					else {
						usage(oldargv[0]);
						break;
					}

				case 's':
					if (strncmp(p, "scd", 3) == 0) {
						cdflag = 2;	/* pass '-scd' to assembler */
						p += 2;
						break;
					}
					else if (strncmp(p, "sgx", 3) == 0) {
						strcat(asmdefs, "_SGX = 1\n");
						defmac("_SGX");
						p += 2;
						break;
					}
				/* fallthrough */
				case 'S':
					sflag = 1;
					break;

				/* defines to pass to assembler */
				case 'a':
					if (strncmp(p, "acd", 3) == 0) {
						cdflag = 2;	/* pass '-scd' to assembler */
						strcat(asmdefs, "_AC = 1\n");
						defmac("_AC");
						p += 2;
						break;
					}
				/* fallthrough */
				case 'A':
					bp = ++p;
					if (!*p) usage(oldargv[0]);
					while (*p && *p != '=') p++;
					strncat(asmdefs, bp, (p - bp));
/*					if (*p == '=') *p = '\t'; */
					bp = ++p;
					strcat(asmdefs, "\t= ");
					if (*bp == '\0')
						strcat(asmdefs, "1\n");
					else {
						strcat(asmdefs, bp);
						strcat(asmdefs, "\n");
					}
					break;


				case 'v':
					verboseflag++;
					if (verboseflag > 1)
						ctext = 1;		/* "C" code in asm output */
					break;

				case 'd': case 'D':
					bp = ++p;
					if (!*p) usage(oldargv[0]);
					while (*p && *p != '=') p++;
					if (*p == '=') *p = '\t';
					while (*p) p++;
					p--;
					defmac(bp);
					break;

				case 'o':
					if (strncmp(p, "over", 4) == 0) {
						overlayflag = 1;
						if (strncmp(p, "overlay", 7) == 0)
							p += 6;
						else
							p += 3;
					}
					else {
						bp = ++p;
						while (*p && *p != ' ' && *p != '\t')
							p++;
						memcpy(user_outfile, bp, p - bp);
						user_outfile[p - bp] = 0;
						p--;
					}
					break;
				case 'O':
					/* David, made -O equal to -O2
					 * I'm too lazy to tape -O2 each time :)
					 */
					if (!p[1]) optimize = 2;
					else optimize = atoi(++p);
					break;

				case 'f':
					p++;
					if (!strcmp(p, "no-recursive")) {
						user_norecurse = 1;
						p += 11;
					}
					else if (!strcmp(p, "recursive")) {
						user_norecurse = 0;
						p += 8;
					}
					else if (!strcmp(p, "no-short-enums")) {
						user_short_enums = 0;
						p += 13;
					}
					else if (!strcmp(p, "short-enums")) {
						user_short_enums = 1;
						p += 10;
					}
					else
						goto unknown_option;
					break;

				case 'l':
					bp = ++p;
					while (*p && *p != ' ' && *p != '\t')
						p++;
					link_libs = realloc(link_libs, (link_lib_ptr + 2) * sizeof(*link_libs));
					link_libs[link_lib_ptr] = malloc(p - bp + 1);
					memcpy(link_libs[link_lib_ptr], bp, p - bp);
					link_libs[link_lib_ptr][p - bp] = 0;
					strcat(asmdefs, "LINK_");
					strcat(asmdefs, link_libs[link_lib_ptr]);
					strcat(asmdefs, "\t= 1\n");
					link_libs[++link_lib_ptr] = 0;
					p--;
					break;

				case 'm':
					if (!strcmp(p + 1, "small")) {
						strcat(asmdefs, "SMALL\t= 1\n");
						p += 5;
					}
					else {
unknown_option:
						fprintf(stderr, "unknown option %s\n", p);
						exit(1);
					}
					break;

				default:
					usage(oldargv[0]);
				}
		}
		else {
			infiles = realloc(infiles, (infile_ptr + 2) * sizeof(*infiles));
			infiles[infile_ptr++] = p;
			infiles[infile_ptr] = 0;
		}
	}

	smacptr = macptr;
	if (!infiles)
		usage(oldargv[0]);
	printf(HUC_VERSION);
	printf("\n");
	init_path();
	/* Remember the first file, it will be used as the base for the
	   output file name unless there is a user-specified outfile. */
	p = pp = infiles[0];
	/* Labels count is not reset for each file because labels are
	   global and conflicts would arise. */
	nxtlab = 0;
	link_lib = link_libs;
	infile_ptr = 1;
	/* Remember where the global assembler defines end so we can
	   reset to that point for each file. */
	/* XXX: Even if we don't repeat the local asm defines, they
	   are still defined because we compile everything into one
	   assembly file. */
	asmdefs_global_end = asmdefs + strlen(asmdefs);
	while (p) {
		errfile = 0;
		/* Truncate asm defines to the point where global
		   defines end. */
		asmdefs_global_end[0] = 0;
		if (extension(p) == 'c' || extension(p) == 'C') {
			glbptr = STARTGLB;
			locptr = STARTLOC;
			wsptr = ws;
			inclsp =
			iflevel =
			skiplevel =
			swstp =
			litptr =
			stkp =
			errcnt =
			ncmp =
			lastst =
			quote[1] =
			const_nb =
			line_number = 0;
			macptr = smacptr;
			input2 = NULL;
			quote[0] = '"';
			cmode = 1;
			glbflag = 1;
			litlab = getlabel();
			member_table_index = 0;
			memset(member_table, 0, sizeof(member_table));
			tag_table_index = 0;
			norecurse = user_norecurse;
			typedef_ptr = 0;
			enum_ptr = 0;
			enum_type_ptr = 0;
			memset(fastcall_tbl, 0, sizeof(fastcall_tbl));
			defpragma();

			/* Macros and globals have to be reset for each
			   file, so we have to define the defaults all over
			   each time. */
			defmac("__end\t__memory");
			addglb("__memory", ARRAY, CCHAR, 0, EXTERN, 0);
			addglb("stack", ARRAY, CCHAR, 0, EXTERN, 0);
			rglbptr = glbptr;
			addglb("etext", ARRAY, CCHAR, 0, EXTERN, 0);
			addglb("edata", ARRAY, CCHAR, 0, EXTERN, 0);
			/* PCE specific externs */
			addglb("font_base", VARIABLE, CINT, 0, EXTERN, 0);
			addglb_far("vdc", CINT);
			addglb_far("vram", CCHAR);
			/* end specific externs */
			defmac("huc6280\t1");
			defmac("huc\t1");

			if (cdflag == 1)
				defmac("_CD\t1");
			else if (cdflag == 2)
				defmac("_SCD\t1");
			else
				defmac("_ROM\t1");

			if (overlayflag == 1)
				defmac("_OVERLAY\t1");

//			initmac();
			/*
			 *	compiler body
			 */
			if (!openin(p))
				exit(1);
			if (first && !openout())
				exit(1);
			if (first)
				header();
			asmdefines();
//			gtext ();
			parse();
			fclose(input);
//			gdata ();
			dumplits();
			dumpglbs();
			errorsummary();
//			trailer ();
			pl("");
			errs = errs || errfile;
		}
		else {
			fputs("Don't understand file ", stderr);
			fputs(p, stderr);
			fputc('\n', stderr);
			exit(1);
		}
		p = infiles[infile_ptr];
		if (!p && link_lib && *link_lib) {
			/* No more command-line files, continue with
			   libraries. */
			p = lib_to_file(*link_lib);
			if (!p) {
				fprintf(stderr, "cannot find library %s\n", *link_lib);
				exit(1);
			}
			link_lib++;
		}
		else
			infile_ptr++;
		first = 0;
	}
	dumpfinal();
	fclose(output);
	if (!errs && !sflag) {
		if (user_outfile[0])
			errs = errs || assemble(user_outfile);
		else
			errs = errs || assemble(pp);
	}
	exit(errs != 0);
}
Example #14
0
void
UrlWrapper::RefsReceived(BMessage* msg)
{
	char buff[B_PATH_NAME_LENGTH];
	int32 index = 0;
	entry_ref ref;
	char* args[] = { const_cast<char*>("urlwrapper"), buff, NULL };
	status_t err;

	while (msg->FindRef("refs", index++, &ref) == B_OK) {
		BFile f(&ref, B_READ_ONLY);
		BNodeInfo ni(&f);
		BString mimetype;
		BString extension(ref.name);
		extension.Remove(0, extension.FindLast('.') + 1);
		if (f.InitCheck() == B_OK && ni.InitCheck() == B_OK) {
			ni.GetType(mimetype.LockBuffer(B_MIME_TYPE_LENGTH));
			mimetype.UnlockBuffer();

			// Internet Explorer Shortcut
			if (mimetype == "text/x-url" || extension == "url") {
				// http://filext.com/file-extension/URL
				// http://www.cyanwerks.com/file-format-url.html
				off_t size;
				if (f.GetSize(&size) < B_OK)
					continue;
				BString contents;
				BString url;
				if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK)
					continue;
				contents.UnlockBuffer();
				while (contents.Length()) {
					BString line;
					int32 cr = contents.FindFirst('\n');
					if (cr < 0)
						cr = contents.Length();
					//contents.MoveInto(line, 0, cr);
					contents.CopyInto(line, 0, cr);
					contents.Remove(0, cr+1);
					line.RemoveAll("\r");
					if (!line.Length())
						continue;
					if (!line.ICompare("URL=", 4)) {
						line.MoveInto(url, 4, line.Length());
						break;
					}
				}
				if (url.Length()) {
					BPrivate::Support::BUrl u(url.String());
					args[1] = (char*)u.String();
					mimetype = kURLHandlerSigBase;
					mimetype += u.Proto();
					err = be_roster->Launch(mimetype.String(), 1, args + 1);
					if (err != B_OK && err != B_ALREADY_RUNNING)
						err = be_roster->Launch(kAppSig, 1, args + 1);
					continue;
				}
			}
			if (mimetype == "text/x-webloc" || extension == "webloc") {
				// OSX url shortcuts
				// XML file + resource fork
				off_t size;
				if (f.GetSize(&size) < B_OK)
					continue;
				BString contents;
				BString url;
				if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK)
					continue;
				contents.UnlockBuffer();
				int state = 0;
				while (contents.Length()) {
					BString line;
					int32 cr = contents.FindFirst('\n');
					if (cr < 0)
						cr = contents.Length();
					contents.CopyInto(line, 0, cr);
					contents.Remove(0, cr+1);
					line.RemoveAll("\r");
					if (!line.Length())
						continue;
					int32 s, e;
					switch (state) {
						case 0:
							if (!line.ICompare("<?xml", 5))
								state = 1;
							break;
						case 1:
							if (!line.ICompare("<plist", 6))
								state = 2;
							break;
						case 2:
							if (!line.ICompare("<dict>", 6))
								state = 3;
							break;
						case 3:
							if (line.IFindFirst("<key>URL</key>") > -1)
								state = 4;
							break;
						case 4:
							if ((s = line.IFindFirst("<string>")) > -1
								&& (e = line.IFindFirst("</string>")) > s) {
								state = 5;
								s += 8;
								line.MoveInto(url, s, e - s);
								break;
							} else
								state = 3;
							break;
						default:
							break;
					}
					if (state == 5) {
						break;
					}
				}
				if (url.Length()) {
					BPrivate::Support::BUrl u(url.String());
					args[1] = (char*)u.String();
					mimetype = kURLHandlerSigBase;
					mimetype += u.Proto();
					err = be_roster->Launch(mimetype.String(), 1, args + 1);
					if (err != B_OK && err != B_ALREADY_RUNNING)
						err = be_roster->Launch(kAppSig, 1, args + 1);
					continue;
				}
			}

			// NetPositive Bookmark or any file with a META:url attribute
			if (f.ReadAttr("META:url", B_STRING_TYPE, 0LL, buff,
				B_PATH_NAME_LENGTH) > 0) {
				BPrivate::Support::BUrl u(buff);
				args[1] = (char*)u.String();
				mimetype = kURLHandlerSigBase;
				mimetype += u.Proto();
				err = be_roster->Launch(mimetype.String(), 1, args + 1);
				if (err != B_OK && err != B_ALREADY_RUNNING)
					err = be_roster->Launch(kAppSig, 1, args + 1);
				continue;
			}
		}
	}
}
Example #15
0
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) {

    setGourceDefaults();

    if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name);

    if(gource_settings == 0) {
        gource_settings = conffile.addSection("gource");
    }

    ConfEntry* entry = 0;

    //hide flags

    std::vector<std::string> hide_fields;

    if((entry = gource_settings->getEntry("hide")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        std::string hide_string = entry->getString();

        size_t sep;
        while((sep = hide_string.find(",")) != std::string::npos) {

            if(sep == 0 && hide_string.size()==1) break;

            if(sep == 0) {
                hide_string = hide_string.substr(sep+1, hide_string.size()-1);
                continue;
            }

            std::string hide_field  = hide_string.substr(0, sep);
            hide_fields.push_back(hide_field);
            hide_string = hide_string.substr(sep+1, hide_string.size()-1);
        }

        if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string);

        //validate field list

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hide_field = (*it);

            if(   hide_field != "date"
               && hide_field != "users"
               && hide_field != "tree"
               && hide_field != "files"
               && hide_field != "usernames"
               && hide_field != "filenames"
               && hide_field != "dirnames"
               && hide_field != "bloom"
               && hide_field != "progress"
               && hide_field != "mouse"
               && hide_field != "root") {
                std::string unknown_hide_option = std::string("unknown option hide ") + hide_field;
                conffile.entryException(entry, unknown_hide_option);
            }
        }
    }

    //check hide booleans
    for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) {
        if(it->first.find("hide-") == 0 && it->second == "bool") {

            if(gource_settings->getBool(it->first)) {
                std::string hide_field = it->first.substr(5, it->first.size()-5);
                hide_fields.push_back(hide_field);
            }
        }
    }

    if(hide_fields.size()>0) {

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hidestr = (*it);

                if(hidestr == "date")       hide_date      = true;
            else if(hidestr == "users")     hide_users     = true;
            else if(hidestr == "tree")      hide_tree      = true;
            else if(hidestr == "files")     hide_files     = true;
            else if(hidestr == "usernames") hide_usernames = true;
            else if(hidestr == "filenames") hide_filenames = true;
            else if(hidestr == "dirnames")  hide_dirnames  = true;
            else if(hidestr == "bloom")     hide_bloom     = true;
            else if(hidestr == "progress")  hide_progress  = true;
            else if(hidestr == "root")      hide_root      = true;
            else if(hidestr == "mouse")     {
                hide_mouse     = true;
                hide_progress  = true;
            }
        }
    }

    if((entry = gource_settings->getEntry("date-format")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        date_format = entry->getString();
    }

    if(gource_settings->getBool("disable-auto-rotate")) {
        disable_auto_rotate=true;
    }

    if(gource_settings->getBool("disable-auto-skip")) {
        auto_skip_seconds = -1.0;
    }

    if(gource_settings->getBool("loop")) {
        loop = true;
    }

    if((entry = gource_settings->getEntry("git-branch")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        Regex branch_regex("^(?!-)[/\\w.,;_=+{}\\[\\]-]+$");

        std::string branch = entry->getString();

        if(branch_regex.match(branch)) {
            git_branch = branch;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("colour-images")) {
        colour_user_images = true;
    }

    if((entry = gource_settings->getEntry("crop")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)");

        std::string crop = entry->getString();

        if(crop == "vertical") {
            crop_vertical = true;
        } else if (crop == "horizontal") {
            crop_horizontal = true;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("log-format")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)");

        log_format = entry->getString();

        if(log_format == "cvs") {
            conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'");
        }

        if(   log_format != "git"
           && log_format != "cvs-exp"
           && log_format != "cvs2cl"
           && log_format != "svn"
           && log_format != "custom"
           && log_format != "hg"
           && log_format != "bzr"
           && log_format != "apache") {

            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("default-user-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)");

        default_user_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("user-image-dir")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)");

        user_image_dir = entry->getString();

        //append slash
        if(user_image_dir[user_image_dir.size()-1] != '/') {
            user_image_dir += std::string("/");
        }

        user_image_map.clear();

        boost::filesystem::path image_dir_path(user_image_dir);

        if(!is_directory(image_dir_path)) {
             conffile.entryException(entry, "specified user-image-dir is not a directory");
        }

        std::vector<boost::filesystem::path> image_dir_files;

        try {
            copy(boost::filesystem::directory_iterator(image_dir_path), boost::filesystem::directory_iterator(), back_inserter(image_dir_files));
        } catch(const boost::filesystem::filesystem_error& exception) {
             conffile.entryException(entry, "error reading specified user-image-dir");
        }

        for(boost::filesystem::path& p : image_dir_files) {

            std::string dirfile;

#ifdef _WIN32
            std::wstring dirfile_16 = p.filename().wstring();
            utf8::utf16to8(dirfile_16.begin(), dirfile_16.end(), back_inserter(dirfile));
#else
            dirfile = p.filename().string();
#endif
            std::string file_ext = extension(p);
            boost::algorithm::to_lower(file_ext);

            if(file_ext != ".jpg" && file_ext != ".jpeg" && file_ext != ".png") continue;

            std::string image_path = gGourceSettings.user_image_dir + dirfile;
            std::string name       = dirfile.substr(0,dirfile.size() - file_ext.size());

#ifdef __APPLE__
                CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0);
                CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8);
                CFStringNormalize(help, kCFStringNormalizationFormC);
                char data[4096];
                CFStringGetCString(help,
                                   data,
                                   sizeof(data),
                                   kCFStringEncodingUTF8);
                name = data;
#endif

            debugLog("%s => %s", name.c_str(), image_path.c_str());

            user_image_map[name] = image_path;
        }
    }

    if((entry = gource_settings->getEntry("caption-file")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption file (filename)");

        caption_file = entry->getString();

        if(!boost::filesystem::exists(caption_file)) {
            conffile.entryException(entry, "caption file not found");
        }
    }

    if((entry = gource_settings->getEntry("caption-duration")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption duration (seconds)");

        caption_duration = entry->getFloat();

        if(caption_duration <= 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption size");

        caption_size = entry->getInt();

        if(caption_size<1 || caption_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption offset");

        caption_offset = entry->getInt();
    }

    if((entry = gource_settings->getEntry("caption-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            caption_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            caption_colour = vec3(r,g,b);
            caption_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-colour")) != 0) {
        if(!entry->hasValue()) conffile.entryException(entry, "specify filename colour (FFFFFF)");

	int r,g,b;

	std::string colstring = entry->getString();

	if(entry->isVec3()) {
	    filename_colour = entry->getVec3();
	} else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            filename_colour = vec3(r,g,b);
            filename_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify duration to keep files on screen (float)");

        filename_time = entry->getFloat();

        if(filename_time<2.0f) {
            conffile.entryException(entry, "filename-time must be >= 2.0");
        }
    }

    if((entry = gource_settings->getEntry("bloom-intensity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)");

        bloom_intensity = entry->getFloat();

        if(bloom_intensity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)");

        bloom_multiplier = entry->getFloat();

        if(bloom_multiplier<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("elasticity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)");

        elasticity = entry->getFloat();

        if(elasticity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("font-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font size");

        font_size = entry->getInt();

        if(font_size<1 || font_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("hash-seed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)");

        gStringHashSeed = entry->getInt();
    }

    if((entry = gource_settings->getEntry("font-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            font_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            font_colour = vec3(r,g,b);
            font_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            background_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            background_colour = vec3(r,g,b);
            background_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("highlight-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            highlight_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            highlight_colour = vec3(r,g,b);
            highlight_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("selection-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            selection_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            selection_colour = vec3(r,g,b);
            selection_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            dir_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            dir_colour = vec3(r,g,b);
            dir_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)");

        background_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("title")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify title");

        title = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)");

        logo = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)");

        std::string logo_offset_str = entry->getString();

        int posx = 0;
        int posy = 0;

        if(parseRectangle(logo_offset_str, posx, posy)) {
            logo_offset = vec2(posx, posy);
        } else {
            conffile.invalidValueException(entry);
        }

    }

    if((entry = gource_settings->getEntry("seconds-per-day")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)");

        float seconds_per_day = entry->getFloat();

        if(seconds_per_day<=0.0f) {
            conffile.invalidValueException(entry);
        }

        // convert seconds-per-day to days-per-second
        days_per_second = 1.0 / seconds_per_day;
    }

    if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)");

        auto_skip_seconds = entry->getFloat();

        if(auto_skip_seconds <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("file-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)");

        std::string file_idle_str = entry->getString();

        file_idle_time = (float) atoi(file_idle_str.c_str());

        if(file_idle_time<0.0f || (file_idle_time == 0.0f && file_idle_str[0] != '0') ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)");

        user_idle_time = entry->getFloat();

        if(user_idle_time < 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("time-scale")) != 0) {

        if(!entry->hasValue())
            conffile.entryException(entry, "specify time-scale (scale)");

        time_scale = entry->getFloat();

        if(time_scale <= 0.0f || time_scale > 4.0f) {
            conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0");
        }
    }

    if((entry = gource_settings->getEntry("start-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-date (YYYY-MM-DD hh:mm:ss)");

        std::string start_date_string = entry->getString();

        if(parseDateTime(start_date_string, start_timestamp)) {

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &start_timestamp ));
            start_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("stop-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-date (YYYY-MM-DD hh:mm:ss)");

        std::string end_date_string = entry->getString();

        if(parseDateTime(end_date_string, stop_timestamp)) {

            struct tm * timeinfo;
            timeinfo = localtime ( &stop_timestamp );

            time_t stop_timestamp_rounded = stop_timestamp;

            if(timeinfo->tm_hour > 0 || timeinfo->tm_min > 0 || timeinfo->tm_sec > 0) {
                stop_timestamp_rounded += 60*60*24;
            }

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &stop_timestamp_rounded ));
            stop_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("start-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)");

        if(entry->getString() == "random") {
            srand(time(0));
            start_position = (rand() % 1000) / 1000.0f;
        } else {
            start_position = entry->getFloat();

            if(start_position<=0.0 || start_position>=1.0) {
                conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)");
            }
        }
    }

    if((entry = gource_settings->getEntry("stop-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)");

        stop_position = entry->getFloat();

        if(stop_position<=0.0 || stop_position>1.0) {
            conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)");
        }
    }

    if((entry = gource_settings->getEntry("stop-at-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)");

        stop_at_time = entry->getFloat();

        if(stop_at_time <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("key")) {
        show_key = true;
    }

    if(gource_settings->getBool("ffp")) {
        ffp = true;
    }

    if(gource_settings->getBool("realtime")) {
        days_per_second = 1.0 / 86400.0;
    }

    if(gource_settings->getBool("no-time-travel")) {
        no_time_travel = true;
    }

    if(gource_settings->getBool("dont-stop")) {
        dont_stop = true;
    }

    if(gource_settings->getBool("stop-at-end")) {
        stop_at_end = true;
    }

    //NOTE: this no longer does anything
    if(gource_settings->getBool("stop-on-idle")) {
        stop_on_idle = true;
    }

    if((entry = gource_settings->getEntry("max-files")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)");

        max_files = entry->getInt();

        if( max_files<0 || (max_files == 0 && entry->getString() != "0") ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-file-lag")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)");

        max_file_lag = entry->getFloat();

        if(max_file_lag==0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-friction")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)");

        user_friction = entry->getFloat();

        if(user_friction<=0.0) {
            conffile.invalidValueException(entry);
        }

        user_friction = 1.0 / user_friction;
    }

    if((entry = gource_settings->getEntry("user-scale")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)");

        user_scale = entry->getFloat();

        if(user_scale<=0.0 || user_scale>100.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-user-speed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)");

        max_user_speed = entry->getFloat();

        if(max_user_speed<=0) {
            conffile.invalidValueException(entry);
        }
    }

    if(   gource_settings->getBool("highlight-users")
       || gource_settings->getBool("highlight-all-users")) {
        highlight_all_users = true;
    }

    if(gource_settings->getBool("highlight-dirs")) {
        highlight_dirs = true;
    }

    if((entry = gource_settings->getEntry("camera-mode")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)");

        camera_mode = entry->getString();

        if(camera_mode != "overview" && camera_mode != "track") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("padding")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)");

        padding = entry->getFloat();

        if(padding <= 0.0f || padding >= 2.0f) {
            conffile.invalidValueException(entry);
        }
    }

    // multi-value entries

    if((entry = gource_settings->getEntry("highlight-user")) != 0) {

        ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user");

        for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)");

            highlight_users.push_back(entry->getString());
        }
    }

    if((entry = gource_settings->getEntry("follow-user")) != 0) {

        ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");

        for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");

            follow_users.push_back(entry->getString());
        }
    }

    if(gource_settings->getBool("file-extensions")) {
        file_extensions=true;
    }

    if(gource_settings->getBool("file-extension-fallback")) {
        file_extension_fallback=true;
    }

    if((entry = gource_settings->getEntry("file-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-filter regular expression");
            }

            file_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("file-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-show-filter regular expression");
            }

            file_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-filter regular expression");
            }

            user_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-show-filter regular expression");
            }

            user_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-depth")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-depth (depth)");

        dir_name_depth = entry->getInt();

        if(dir_name_depth <= 0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-position (float)");

        dir_name_position = entry->getFloat();

        if(dir_name_position < 0.1f || dir_name_position > 1.0f) {
            conffile.entryException(entry, "dir-name-position outside of range 0.1 - 1.0 (inclusive)");
        }
    }

    //validate path
    if(gource_settings->hasValue("path")) {
        path = gource_settings->getString("path");
        default_path = false;
    }

    if(path == "-") {

        if(log_format.size() == 0) {
            throw ConfFileException("log-format required when reading from STDIN", "", 0);
        }

#ifdef _WIN32
        DWORD available_bytes;
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);

        while(PeekNamedPipe(stdin_handle, 0, 0, 0,
            &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) {
            SDL_Delay(100);
        }
#else
        while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100);
#endif

        std::cin.clear();

    } else if(!path.empty() && path != ".") {

        //remove trailing slash
        if(path[path.size()-1] == '\\' || path[path.size()-1] == '/') {
            path.resize(path.size()-1);
        }

        // check path exists
        if(!boost::filesystem::exists(path)) {
            throw ConfFileException(str(boost::format("'%s' does not appear to be a valid file or directory") % path), "", 0);
        }
    }
}
Example #16
0
void load_root_dexen(DexStore& store,
                     const std::string& dexen_dir_str,
                     bool balloon,
                     bool verbose,
                     bool support_dex_v37) {
  namespace fs = boost::filesystem;
  fs::path dexen_dir_path(dexen_dir_str);
  redex_assert(fs::is_directory(dexen_dir_path));

  // Discover dex files
  auto end = fs::directory_iterator();
  std::vector<fs::path> dexen;
  for (fs::directory_iterator it(dexen_dir_path) ; it != end ; ++it) {
    auto file = it->path();
    if (fs::is_regular_file(file) &&
        !file.extension().compare(std::string(".dex"))) {
      dexen.emplace_back(file);
    }
  }

  /*
   * Comparator for dexen filename. 'classes.dex' should sort first,
   * followed by [^\d]*[\d]+.dex ordered by N numerically.
   */
  auto dex_comparator = [](const fs::path& a, const fs::path& b){
    boost::regex s_dex_regex("[^0-9]*([0-9]+)\\.dex");

    auto as = a.filename().string();
    auto bs = b.filename().string();
    boost::smatch amatch;
    boost::smatch bmatch;
    bool amatched = boost::regex_match(as, amatch, s_dex_regex);
    bool bmatched = boost::regex_match(bs, bmatch, s_dex_regex);

    if (!amatched && bmatched) {
      return true;
    } else if (amatched && !bmatched) {
      return false;
    } else if (!amatched && !bmatched) {
      // Compare strings, probably the same
      return strcmp(as.c_str(), bs.c_str()) > 0;
    } else {
      // Compare captures as integers
      auto anum = std::stoi(amatch[1]);
      auto bnum = std::stoi(bmatch[1]);
      return bnum > anum ;
    }
  };

  // Sort all discovered dex files
  std::sort(dexen.begin(), dexen.end(), dex_comparator);
  // Load all discovered dex files
  for (const auto& dex : dexen) {
    if (verbose) {
      TRACE(MAIN, 1, "Loading %s\n", dex.string().c_str());
    }
    // N.B. throaway stats for now
    DexClasses classes =
        load_classes_from_dex(dex.string().c_str(), balloon, support_dex_v37);
    store.add_classes(std::move(classes));
  }
}
/*virtual*/ nsresult 
sbGStreamerMediacoreFactory::OnGetCapabilities(
                             sbIMediacoreCapabilities **aCapabilities)
{
  NS_ENSURE_TRUE(mMonitor, NS_ERROR_NOT_INITIALIZED);
  nsAutoMonitor mon(mMonitor);

  // TODO: This function is now a _huge_ mess. We should talk to product about
  // what files we want to import / etc, some time soon - e.g. the current
  // approach is to treat anything even vaguely-plausibly audio-related as
  // audio (even if we can't play it!), but to only import a small list of fixed
  // extensions for videos (excluding many things we might be able to play).

  nsresult rv;
  if (!mCapabilities) {
    nsRefPtr<sbMediacoreCapabilities> caps;
    NS_NEWXPCOM(caps, sbMediacoreCapabilities);
    NS_ENSURE_TRUE(caps, NS_ERROR_OUT_OF_MEMORY);

    rv = caps->Init();
    NS_ENSURE_SUCCESS(rv, rv);

    // Build a big list of extensions based on everything gstreamer knows about,
    // plus some known ones, minus a few known non-media-file extensions that
    // gstreamer has typefinders for.

    nsCOMPtr<nsIPrefBranch> rootPrefBranch =
      do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsTArray<nsString> audioExtensions;
    nsTArray<nsString> videoExtensions;
    
    // XXX Mook: we have a silly list of blacklisted extensions because we don't
    // support them and we're being stupid and guessing things based on them.
    // This crap should really look for a plugin that may possibly actually decode
    // these things, or something better.  Whatever the real solution is, this
    // isn't it :(
    nsCString blacklistExtensions;
    { // for scope
      const char defaultBlacklistExtensions[] =
        "txt,htm,html,xml,pdf,cpl,msstyles,scr,sys,ocx,bz2,gz,zip,Z,rar,tar,dll,"
        "exe,a,bmp,png,gif,jpeg,jpg,jpe,tif,tiff,xpm,dat,swf,swfl,stm,cgi,sf,xcf,"
        "far,wvc,mpc,mpp,mp+,ra,rm,rmvb";
      char* blacklistExtensionsPtr = nsnull;
      rv = rootPrefBranch->GetCharPref(BLACKLIST_EXTENSIONS_PREF,
                                       &blacklistExtensionsPtr);
      if (NS_SUCCEEDED(rv)) {
        blacklistExtensions.Adopt(blacklistExtensionsPtr);
      } else {
        blacklistExtensions.Assign(defaultBlacklistExtensions);
      }
      blacklistExtensions.Insert(',', 0);
      blacklistExtensions.Append(',');
      LOG(("sbGStreamerMediacoreFactory: blacklisted extensions: %s\n",
           blacklistExtensions.BeginReading()));
    }

    const char *extraAudioExtensions[] = {"m4r", "m4p", "oga",
                                          "ogg", "aac", "3gp"};
#ifdef XP_WIN
    const char *extraWindowsAudioExtensions[] = {"wma" };
#endif

    { // for scope

      // Per bug 19550 -
      // Severly limit the video extensions that are imported by default to:
      //   * ogv (all platforms)
      //   * wmv (windows only)
      //   * mp4/m4v/mov (w/ qtvideowrapper plugin)
      //   * divx/avi/mkv (w/ ewmpeg4dec plugin)
      videoExtensions.AppendElement(NS_LITERAL_STRING("ogv"));
#ifdef XP_WIN
      videoExtensions.AppendElement(NS_LITERAL_STRING("wmv"));
#endif

      char* knownVideoExtensionsPtr = nsnull;
      rv = rootPrefBranch->GetCharPref(VIDEO_EXTENSIONS_PREF,
                                       &knownVideoExtensionsPtr);
      if (NS_SUCCEEDED(rv)) {
        // The override video extension pref contains a CSV string.
        nsString_Split(NS_ConvertUTF8toUTF16(knownVideoExtensionsPtr),
                       NS_LITERAL_STRING(","),
                       videoExtensions);
      }

#ifdef PR_LOGGING
      nsString videoExtensionStr;
      for (PRUint32 i = 0; i < videoExtensions.Length(); i++) {
        videoExtensionStr.Append(videoExtensions[i]);
        if (i < videoExtensions.Length() - 1) {
          videoExtensionStr.AppendLiteral(", ");
        }
      }

      LOG(("sbGStreamerMediacoreFactory: video file extensions: %s\n",
            videoExtensionStr.get()));
#endif

      // Check for the 'qtvideowrapper' plugin to add mp4/m4v extensions.
      PRBool foundQTPlugin = PR_FALSE;
      GstPlugin *plugin = gst_default_registry_find_plugin("qtvideowrapper");
      if (plugin) {
        foundQTPlugin = PR_TRUE;
        videoExtensions.AppendElement(NS_LITERAL_STRING("mp4"));
        videoExtensions.AppendElement(NS_LITERAL_STRING("m4v"));
        videoExtensions.AppendElement(NS_LITERAL_STRING("mov"));
        gst_object_unref(plugin);
      }

      // Check for the 'ewmpeg4dec' plugin to add divx/avi extensions.
      plugin = gst_default_registry_find_plugin("ewmpeg4dec");
      if (plugin) {
        videoExtensions.AppendElement(NS_LITERAL_STRING("divx"));
        videoExtensions.AppendElement(NS_LITERAL_STRING("avi"));
        videoExtensions.AppendElement(NS_LITERAL_STRING("mkv"));

        // This plugin will also handle "mp4" and "m4v", only append those
        // extensions if they haven't been added already.
        if (!foundQTPlugin) {
          videoExtensions.AppendElement(NS_LITERAL_STRING("mp4"));
          videoExtensions.AppendElement(NS_LITERAL_STRING("m4v"));
        }

        gst_object_unref(plugin);
      }
    }

    GList *walker, *list;

    list = gst_type_find_factory_get_list ();
    walker = list;
    while (walker) {
      GstTypeFindFactory *factory = GST_TYPE_FIND_FACTORY (walker->data);
      gboolean blacklisted = FALSE;
      const gchar* factoryName = gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory));
      gboolean isAudioFactory = g_str_has_prefix(factoryName, "audio/");

      gchar **factoryexts = gst_type_find_factory_get_extensions (factory);
      if (factoryexts) {
        while (*factoryexts) {
          gboolean isAudioExtension = isAudioFactory;
          nsCString extension(*factoryexts);
          nsCString delimitedExtension(extension);
          delimitedExtension.Insert(',', 0);
          delimitedExtension.Append(',');
          
          blacklisted = (blacklistExtensions.Find(delimitedExtension) != -1);
          #if PR_LOGGING
            if (blacklisted) {
                LOG(("sbGStreamerMediacoreFactory: Ignoring extension '%s'", *factoryexts));
            }
          #endif /* PR_LOGGING */

          if (!blacklisted && isAudioExtension) {
            audioExtensions.AppendElement(NS_ConvertUTF8toUTF16(*factoryexts));
            LOG(("sbGStreamerMediacoreFactory: registering audio extension %s\n",
                  *factoryexts));
          }

          factoryexts++;
        }
      }
      walker = g_list_next (walker);
    }
    g_list_free (list);

    for (unsigned int i = 0; i < NS_ARRAY_LENGTH(extraAudioExtensions); i++) {
      nsString ext = NS_ConvertUTF8toUTF16(extraAudioExtensions[i]);
      if(!audioExtensions.Contains(ext))
        audioExtensions.AppendElement(ext);
    }

#if XP_WIN
    for (unsigned int i = 0; i < NS_ARRAY_LENGTH(extraWindowsAudioExtensions); i++) {
      nsString ext = NS_ConvertUTF8toUTF16(extraWindowsAudioExtensions[i]);
      if(!audioExtensions.Contains(ext))
        audioExtensions.AppendElement(ext);
    }
#endif

    rv = caps->SetAudioExtensions(audioExtensions);
    NS_ENSURE_SUCCESS(rv, rv);

    // Audio playback is always allowed.
    rv = caps->SetSupportsAudioPlayback(PR_TRUE);
    NS_ENSURE_SUCCESS(rv, rv);

    PRBool videoDisabled = PR_FALSE;
    rv = rootPrefBranch->GetBoolPref(
                                    "songbird.mediacore.gstreamer.disablevideo",
                                    &videoDisabled);
    NS_ENSURE_SUCCESS(rv, rv);
    if (!videoDisabled) {
      rv = caps->SetVideoExtensions(videoExtensions);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = caps->SetSupportsVideoPlayback(PR_TRUE);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    mCapabilities = caps;
  }

  rv = CallQueryInterface(mCapabilities.get(), aCapabilities);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Example #18
0
void CHlpFileEntry::ConstructL(TLanguage aLanguage)
	{
	_LIT(KDefaultHelpFileExtension, ".hlp");

	// Decide what type of file this is....
	TFileName file;

	TChar driveLetter;
	User::LeaveIfError(RFs::DriveToChar(iDrive, driveLetter));
	file.Append(driveLetter);
	file.Append(':');
	file.Append(KHlpFileSearchPath);
	file.Append(iFile);

	TParsePtrC parser(file);
	if	(!parser.ExtPresent())
		User::Leave(KErrCorrupt);

	iName.Copy(parser.Name());

	TPtrC extension(parser.Ext());
	if	(extension.CompareF(KDefaultHelpFileExtension) == 0)
		iType = EGeneral;
	else
		{
		TFileName idealHelpFileName(parser.DriveAndPath());
		idealHelpFileName.Append(parser.Name());

		MakeLocaleSpecificExtension(idealHelpFileName, aLanguage);

		if	(idealHelpFileName.CompareF(file) == 0)
			{
			// This is a primary match
			iType = EPrimary;
			iHelpFileLocale = aLanguage;
			}
		else
			{
			// Is it a secondary match? If it isn't then it should be discarded....
			idealHelpFileName = parser.DriveAndPath();
			idealHelpFileName.Append(parser.Name());
	
			// Get the nearest secondary language
			aLanguage = NextLanguage(aLanguage);
			MakeLocaleSpecificExtension(idealHelpFileName, aLanguage);

			if	(idealHelpFileName.CompareF(file) == 0)
				{
				iHelpFileLocale = aLanguage;
				iType = ESecondary;
				}
			else
				{
				TLex lexer(extension);

				// Skip the leading .H
				lexer.Inc(2);
				
				// Lex the value, but silently ignore errors
				TUint localeAsUnsignedInt = ELangOther;
				lexer.Val(localeAsUnsignedInt);
				iHelpFileLocale = STATIC_CAST(TLanguage, localeAsUnsignedInt);
				iType = EInpropperLocale;
				}
			}
		}
	}
Example #19
0
void json_of_line(char *line, char *output){

  sprintf(output, "{\n  src: \"%s\",\n  type: \"%s\"\n}", line, extension(line));
}
Example #20
0
File: os.hpp Project: krig/simplex
			inline const char* extension(const string& full_path) { return extension(full_path.c_str()); }
/*!
    \since 4.4

    Unmaps the memory \a address.  Returns \c true if the unmap succeeds; otherwise
    returns \c false.

    This function bases its behavior on calling extension() with
    UnMapExtensionOption. If the engine does not support this extension, false is
    returned.

    \sa map(), supportsExtension()
 */
bool QAbstractFileEngine::unmap(uchar *address)
{
    UnMapExtensionOption options;
    options.address = address;
    return extension(UnMapExtension, &options);
}
		TITANIUM_FUNCTION(File, extension)
		{
			return get_context().CreateString(extension());
		}
Example #23
0
/* print_html_localized_typography -- convert to "smart" typography */
void print_html_localized_typography(GString *out, int character, scratch_pad *scratch) {
	if (!extension(EXT_SMART, scratch->extensions)) {
		g_string_append_c(out, character);
		return;
	}
	switch (character) {
		case LSQUOTE:
			switch (scratch->language) {
				case SWEDISH:
					g_string_append_printf(out, "&#8217;");
					break;
				case FRENCH:
					g_string_append_printf(out,"&#39;");
					break;
				case GERMAN:
					g_string_append_printf(out,"&#8218;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#8250;");
					break;
				default:
					g_string_append_printf(out,"&#8216;");
				}
			break;
		case RSQUOTE:
			switch (scratch->language) {
				case GERMAN:
					g_string_append_printf(out,"&#8216;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#8249;");
					break;
				default:
					g_string_append_printf(out,"&#8217;");
				}
			break;
		case APOS:
			g_string_append_printf(out,"&#8217;");
			break;
		case LDQUOTE:
			switch (scratch->language) {
				case DUTCH:
				case GERMAN:
					g_string_append_printf(out,"&#8222;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#187;");
					break;
				case FRENCH:
					g_string_append_printf(out,"&#171;");
					break;
				case SWEDISH:
					g_string_append_printf(out, "&#8221;");
					break;
				default:
					g_string_append_printf(out,"&#8220;");
				}
			break;
		case RDQUOTE:
			switch (scratch->language) {
				case SWEDISH:
				case DUTCH:
					g_string_append_printf(out,"&#8221;");
					break;
				case GERMAN:
					g_string_append_printf(out,"&#8220;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#171;");
					break;
				case FRENCH:
					g_string_append_printf(out,"&#187;");
					break;
				default:
					g_string_append_printf(out,"&#8221;");
				}
			break;
		case NDASH:
			g_string_append_printf(out,"&#8211;");
			break;
		case MDASH:
			g_string_append_printf(out,"&#8212;");
			break;
		case ELLIP:
			g_string_append_printf(out,"&#8230;");
			break;
			default:;
	}
}
// cancels all the data, considering transferers, both uploading and downloading
// such as pids and last times of creation, and sends SIGKILL signals to the
// stuck processes
void
AbstractReplicatorStateMachine::killTransferers()
{
    if( m_downloadTransfererMetadata.isValid() ) {
       /* Beware of sending SIGKILL with download transferer's pid = -1, because
        * according to POSIX it will be sent to every process that the
        * current process is able to sent signals to
        */
        dprintf( D_FULLDEBUG,
            "AbstractReplicatorStateMachine::killTransferers "
            "killing downloading condor_transferer pid = %d\n",
                   m_downloadTransfererMetadata.m_pid );
        //kill( m_downloadTransfererMetadata.m_pid, SIGKILL );
        daemonCore->Send_Signal( m_downloadTransfererMetadata.m_pid, SIGKILL );
		// when the process is killed, it could have not yet erased its
        // temporary files, this is why we ensure it by erasing it in killer
        // function
        MyString extension( m_downloadTransfererMetadata.m_pid );
        // the .down ending is needed in order not to confuse between upload and
        // download processes temporary files
        extension += ".";
        extension += DOWNLOADING_TEMPORARY_FILES_EXTENSION;

        FilesOperations::safeUnlinkFile( m_versionFilePath.Value( ),
                                         extension.Value( ) );
        FilesOperations::safeUnlinkFile( m_stateFilePath.Value( ),
                                         extension.Value( ) );
		m_downloadTransfererMetadata.set();
    }

	m_uploadTransfererMetadataList.Rewind( );

	ProcessMetadata* uploadTransfererMetadata = NULL;    

    while( m_uploadTransfererMetadataList.Next( uploadTransfererMetadata ) ) {
        if( uploadTransfererMetadata->isValid( ) ) {
            dprintf( D_FULLDEBUG,
                "AbstractReplicatorStateMachine::killTransferers "
                "killing uploading condor_transferer pid = %d\n",
                uploadTransfererMetadata->m_pid );
            //kill( uploadTransfererMetadata->m_pid, SIGKILL );
			daemonCore->Send_Signal( uploadTransfererMetadata->m_pid, SIGKILL );
			
			            // when the process is killed, it could have not yet
			            // erased its
            // temporary files, this is why we ensure it by erasing it in killer
            // function
            MyString extension( uploadTransfererMetadata->m_pid );
            // the .up ending is needed in order not to confuse between
            // upload and download processes temporary files
            extension += ".";
            extension += UPLOADING_TEMPORARY_FILES_EXTENSION;

            FilesOperations::safeUnlinkFile( m_versionFilePath.Value( ),
                                             extension.Value( ) );
            FilesOperations::safeUnlinkFile( m_stateFilePath.Value( ),
                                             extension.Value( ) );
			delete uploadTransfererMetadata;
			// after deletion the iterator is moved to the previous member
			// so advancing the iterator twice and missing one entry does not
			// happen
        	m_uploadTransfererMetadataList.DeleteCurrent( );
		}
    }
	m_uploadTransfererMetadataList.Rewind( );
}
Example #25
0
void SongLoader::LoadSong7KFromDir(std::filesystem::path songPath, std::vector<VSRG::Song*> &VecOut)
{
	if (!std::filesystem::is_directory(songPath))
		return;

    std::vector<std::filesystem::path> Listing = Utility::GetFileListing(songPath);
    std::filesystem::path SongDirectory = std::filesystem::absolute(songPath);

    /*
        Procedure:
        1.- Check all files if cache needs to be renewed or created.
        2.- If it needs to, load the song again.
        3.- If it loaded the song for either reason, rewrite the difficulty cache.
        4.- If it does not need to be renewed or created, just read the metadata and leave it like that.
    */

    bool RenewCache = false;

    /*
        We want the following:
        All BMS must be packed together.
        All osu!mania charts must be packed together.
        OJNs must be their own chart.
        SMs must be their own chart. (And SSCs have priority if more loaders are supported later)
        All FCFs to be grouped together

        Therefore; it's not the song directory which we check, but the difficulties' files.
    */

    /* First we need to see whether these file need to be renewed.*/
    for (auto i = Listing.begin(); i != Listing.end(); ++i)
    {
        auto File = *i;
        std::wstring Ext = File.extension().wstring();

        /*
            Some people leave nameless, blank .bms files on their folder.
            This causes the cache to do a full reload, so we check if
            we should just ignore this file.
            It'll be loaded in any case, but not considered for cache.
        */
        std::string Fname = File.filename().string();

		if (VSRGValidExtension(Ext) &&
			Fname.length() &&
			DB->CacheNeedsRenewal(File))
				RenewCache = true;
    }

    // Files were modified- we have to reload the charts.
    if (RenewCache)
    {
		CfgVar NoFileGrouping("NoFileGrouping");
        // First, pack BMS charts together.
        std::map<std::string, VSRG::Song*> bmsk;
        VSRG::Song *BMSSong = new VSRG::Song;

        // Every OJN gets its own Song object.
        VSRG::Song *OJNSong = new VSRG::Song;
        OJNSong->SongDirectory = SongDirectory;

        // osu!mania charts are packed together, with FTB charts.
        VSRG::Song *osuSong = new VSRG::Song;
        osuSong->SongDirectory = SongDirectory;

        // Stepmania charts get their own song objects too.
        VSRG::Song *smSong = new VSRG::Song;
        smSong->SongDirectory = SongDirectory;

        for (auto File : Listing)
        {
            std::wstring Ext = File.extension().wstring();
			File = File.filename();

            // We want to group charts with the same title together.
            if (ValidBMSExtension(Ext) || Ext == L".bmson")
            {
                BMSSong->SongDirectory = SongDirectory;

                try
                {
                    LoadSong7KFromFilename(File, SongDirectory, BMSSong);
                }
                catch (std::exception &ex)
                {
                    Log::Logf("\nSongLoader::LoadSong7KFromDir(): Exception \"%s\" occurred while loading file \"%s\"\n",
                        ex.what(), File.filename().c_str());
                    Utility::DebugBreak();
                }

                // We found a chart with the same title (and subtitle) already.

				if (!NoFileGrouping) {
					std::string key;
					if (Configuration::GetConfigf("SeparateBySubtitle"))
						key = BMSSong->SongName + BMSSong->Subtitle;
					else
						key = BMSSong->SongName;

					if (bmsk.find(key) != bmsk.end())
					{
						VSRG::Song *oldSng = bmsk[key];

						if (BMSSong->Difficulties.size()) // BMS charts don't have more than one difficulty anyway.
							oldSng->Difficulties.push_back(BMSSong->Difficulties[0]);

						BMSSong->Difficulties.clear();
						delete BMSSong;
					}
					else // Ah then, don't delete it.
					{
						bmsk[key] = BMSSong;
					}

					BMSSong = new VSRG::Song;
				} else
				{
					VSRGUpdateDatabaseDifficulties(DB, BMSSong);
					PushVSRGSong(VecOut, BMSSong);
					BMSSong = new VSRG::Song;
				}
            }

            if (Ext == L".ojn")
            {
                LoadSong7KFromFilename(File, SongDirectory, OJNSong);
                VSRGUpdateDatabaseDifficulties(DB, OJNSong);
                PushVSRGSong(VecOut, OJNSong);
                OJNSong = new VSRG::Song;
                OJNSong->SongDirectory = SongDirectory;
            }

            if (Ext == L".osu" || Ext == L".fcf")
                LoadSong7KFromFilename(File, SongDirectory, osuSong);

            if (Ext == L".sm" || Ext == L".ssc")
            {
                LoadSong7KFromFilename(File, SongDirectory, smSong);
                VSRGUpdateDatabaseDifficulties(DB, smSong);
                PushVSRGSong(VecOut, smSong);
                smSong = new VSRG::Song;
                smSong->SongDirectory = SongDirectory;
            }
        }

        // PushVSRGSong() handles the cleanup.
        for (auto i = bmsk.begin();
        i != bmsk.end(); ++i)
        {
            VSRGUpdateDatabaseDifficulties(DB, i->second);
            PushVSRGSong(VecOut, i->second);
        }

        VSRGUpdateDatabaseDifficulties(DB, OJNSong);
        PushVSRGSong(VecOut, OJNSong);

        VSRGUpdateDatabaseDifficulties(DB, osuSong);
        PushVSRGSong(VecOut, osuSong);

        VSRGUpdateDatabaseDifficulties(DB, smSong);
        PushVSRGSong(VecOut, smSong);
    }
    else // We can reload from cache. We do this on a per-file basis.
    {
        // We need to get the song IDs for every file; it's guaranteed that they exist, in theory.
        int ID = -1;
        std::vector<int> IDList;

        for (auto File : Listing)
        {
            std::wstring Ext = File.extension().wstring();
            if (VSRGValidExtension(Ext))
            {
                int CurrentID = DB->GetSongIDForFile(File, nullptr);
                if (CurrentID != ID)
                {
                    ID = CurrentID;
                    IDList.push_back(ID);
                }
            }
        }

        // So now we have our list with song IDs that are present on the current directory.
        // Time to load from cache.
        for (auto i = IDList.begin();
        i != IDList.end();
            ++i)
        {
            VSRG::Song *New = new VSRG::Song;
            Log::Logf("Song ID %d load from cache...", *i);
			try {
				DB->GetSongInformation7K(*i, New);
				New->SongDirectory = SongDirectory;

				PushVSRGSong(VecOut, New);
				Log::Logf(" ok\n");
			}
			catch (std::exception &e) {
				Log::Logf("Error loading from cache: %s\n", e.what());
			}
        }
    }
}
Example #26
0
std::string Media::filePath(Format f) const{
    return eqbeatsDir() + "/tracks/" + number(id()) + (f == Original ? ".orig" : "") + extension(f);
}
Example #27
0
bool wxHtmlHelpData::AddBook(const wxString& book)
{
    wxString extension(book.Right(4).Lower());
    if (extension == wxT(".zip") ||
#if wxUSE_LIBMSPACK
        extension == wxT(".chm") /*compressed html help book*/ ||
#endif
        extension == wxT(".htb") /*html book*/)
    {
        wxFileSystem fsys;
        wxString s;
        bool rt = false;

#if wxUSE_LIBMSPACK
        if (extension == wxT(".chm"))
            s = fsys.FindFirst(book + wxT("#chm:*.hhp"), wxFILE);
        else
#endif
            s = fsys.FindFirst(book + wxT("#zip:*.hhp"), wxFILE);

        while (!s.empty())
        {
            if (AddBook(s)) rt = true;
            s = fsys.FindNext();
        }

        return rt;
    }

    wxFSFile *fi;
    wxFileSystem fsys;

    wxString title = _("noname"),
             safetitle,
             start = wxEmptyString,
             contents = wxEmptyString,
             index = wxEmptyString,
             charset = wxEmptyString;

    fi = fsys.OpenFile(book);
    if (fi == NULL)
    {
        wxLogError(_("Cannot open HTML help book: %s"), book.c_str());
        return false;
    }
    fsys.ChangePathTo(book);

    const wxChar *lineptr;
    wxChar linebuf[300];
    wxString tmp;
    wxHtmlFilterPlainText filter;
    tmp = filter.ReadFile(*fi);
    lineptr = tmp.c_str();

    do
    {
        lineptr = ReadLine(lineptr, linebuf, 300);

        for (wxChar *ch = linebuf; *ch != wxT('\0') && *ch != wxT('='); ch++)
           *ch = (wxChar)wxTolower(*ch);

        if (wxStrstr(linebuf, wxT("title=")) == linebuf)
            title = linebuf + wxStrlen(wxT("title="));
        if (wxStrstr(linebuf, wxT("default topic=")) == linebuf)
            start = linebuf + wxStrlen(wxT("default topic="));
        if (wxStrstr(linebuf, wxT("index file=")) == linebuf)
            index = linebuf + wxStrlen(wxT("index file="));
        if (wxStrstr(linebuf, wxT("contents file=")) == linebuf)
            contents = linebuf + wxStrlen(wxT("contents file="));
        if (wxStrstr(linebuf, wxT("charset=")) == linebuf)
            charset = linebuf + wxStrlen(wxT("charset="));
    } while (lineptr != NULL);

    wxFontEncoding enc = wxFONTENCODING_SYSTEM;
#if wxUSE_FONTMAP
    if (charset != wxEmptyString)
        enc = wxFontMapper::Get()->CharsetToEncoding(charset);
#endif

    // No conversion was done on the title yet; at least
    // test for a common case.
    if (charset == wxT("utf-8") && !title.IsEmpty())
    {
        char *buf = new char[title.Length()+1];
        size_t i;
        for (i = 0; i < title.Length(); i++)
            buf[i] = (char) title[i];
        buf[i] = 0;
        title = wxString::FromUTF8(buf);
        delete[] buf;
    }

    bool rtval = AddBookParam(*fi, enc,
                              title, contents, index, start, fsys.GetPath());
    delete fi;

    return rtval;
}
Example #28
0
ClangCompiler::ClangCompiler(const std::string& file_name) : pimpl(new ClangCompilerImpl) {

    setDiagnosticClient(pimpl->clang);

    pimpl->clang.createFileManager();
    pimpl->clang.createSourceManager( pimpl->clang.getFileManager() );

    // A compiler invocation object has to be created in order for the diagnostic object to work
    CompilerInvocation* CI = new CompilerInvocation; // CompilerInvocation will be deleted by CompilerInstance
    CompilerInvocation::CreateFromArgs(*CI, 0, 0, pimpl->clang.getDiagnostics());
    pimpl->clang.setInvocation(CI);

    //setup headers
    pimpl->clang.getHeaderSearchOpts().UseBuiltinIncludes = 0;
    pimpl->clang.getHeaderSearchOpts().UseStandardSystemIncludes = 1;  // Includes system includes, usually  /usr/include
    pimpl->clang.getHeaderSearchOpts().UseStandardCXXIncludes = 0;

    // Add default header
    pimpl->clang.getHeaderSearchOpts().AddPath (CLANG_SYSTEM_INCLUDE_FOLDER,
            clang::frontend::System, true, false, false);

    // fix the target architecture to be a 64 bit machine
    pimpl->TO->Triple = llvm::Triple("x86_64", "PC", "Linux").getTriple();
    // TO.Triple = llvm::sys::getHostTriple();
    pimpl->clang.setTarget( TargetInfo::CreateTargetInfo (pimpl->clang.getDiagnostics(), *(pimpl->TO)) );


    std::string extension(file_name.substr(file_name.rfind('.')+1, std::string::npos));
    bool enableCpp = extension == "C" || extension == "cpp" || extension == "cxx" || extension == "hpp" || extension == "hxx";

    LangOptions& LO = pimpl->clang.getLangOpts();
    LO.GNUMode = 1;
    LO.Bool = 1;
    LO.POSIXThreads = 1;

    // if(CommandLineOptions::STD == "c99") LO.C99 = 1; 		// set c99

    if(enableCpp) {
        LO.CPlusPlus = 1; 	// set C++ 98 support
        LO.CXXOperatorNames = 1;
        //if(CommandLineOptions::STD == "c++0x") {
        //	LO.CPlusPlus0x = 1; // set C++0x support
        //}
        LO.RTTI = 1;
        LO.Exceptions = 1;
        LO.CXXExceptions = 1;
    }

    // Do this AFTER setting preprocessor options
    pimpl->clang.createPreprocessor();
    pimpl->clang.createASTContext();

    getPreprocessor().getBuiltinInfo().InitializeBuiltins(
        getPreprocessor().getIdentifierTable(),
        getPreprocessor().getLangOpts()
    );

    std::cout << file_name << std::endl;

    const FileEntry *FileIn = pimpl->clang.getFileManager().getFile(file_name, true);
    assert(FileIn && "file not found");
    pimpl->clang.getSourceManager().createMainFileID(FileIn);
    pimpl->clang.getDiagnosticClient().BeginSourceFile(
        pimpl->clang.getLangOpts(),
        &pimpl->clang.getPreprocessor());
}
Example #29
0
void ICMPExtensionsStructure::add_extension(MPLS& mpls) {
    ICMPExtension extension(1, 1);
    extension.payload(mpls.serialize());
    add_extension(extension);
}
Example #30
0
int main(int argc, char *argv[]) {
	FILE *input, *output, *auxil;
	char fn_in[FILENAME_MAX], fn_out[FILENAME_MAX], fn_aux[FILENAME_MAX];
	char *s;
	int m, k;
	
	if (argc < 2) {
		fprintf(stderr, "Need argument specifying source file");
		exit(1);
	}

	for(m = 1; m < argc; m++) {

		strcpy(fn_aux, argv[m]);
		forceexten(fn_aux, "aux");
		if((auxil = fopen(fn_aux, "r")) == NULL) {
			perror(fn_aux);	exit(1);
		}

		readaux(auxil);
		fclose(auxil); 

		strcpy(fn_in, argv[m]);	/* input file given as argument */
		extension(fn_in, "afm");
		if((input = fopen(fn_in, "r")) == NULL) {
			perror(fn_in);	exit(1);
		}
	
		if (verboseflag != 0) printf("Processing %s\n", fn_in);

/* strip off pathname */
		if ((s = strrchr(fn_in, '\\')) != NULL) *s++;
		else if ((s = strrchr(fn_in, '/')) != NULL) *s++;
		else if ((s = strrchr(fn_in, ':')) != NULL) *s++;	
		else s = fn_in;
	
/* output goes in current directory */
		strcpy(fn_out, s);
		forceexten(fn_out, "afm");
		if((output = fopen(fn_out, "w")) == NULL) {
			perror(fn_out);	exit(1);
		}	

/*		printf("Ready to adjust AFM\n"); getch(); */
		adjustafm(input, output);
/*		printf("Ready to flush kern\n"); getch(); */
		if (flushkernflag != 0)	k = flushkern(input, output);
		else k = scantocomp(input, output);
		if (k > 0) {
/*			printf("Ready to adjust composites\n"); getch(); */
			adjustcompose(input, output);
		}
/*		printf("Ready to copy the rest\n"); getch(); */
		copyrest(input, output);

		fclose(input);
		if (ferror(output) != 0) {
			perror(fn_out); exit(3);
		}
		else fclose(output);

	}
	if (argc> 2) printf("Processed %d afm files", argc - 1);
	return 0;
}