Ejemplo n.º 1
0
 WorkerExceptionTask(const String& errorMessage, int lineNumber, const String& sourceURL, WorkerMessagingProxy* messagingProxy)
     : m_errorMessage(errorMessage.copy())
     , m_lineNumber(lineNumber)
     , m_sourceURL(sourceURL.copy())
     , m_messagingProxy(messagingProxy)
 {
 }
Ejemplo n.º 2
0
void StorageMap::importItem(const String& key, const String& value) const
{
    // Be sure to copy the keys/values as items imported on a background thread are destined
    // to cross a thread boundary
    pair<HashMap<String, String>::iterator, bool> result = m_map.add(key.copy(), String());

    if (result.second)
        result.first->second = value.copy();
}
Ejemplo n.º 3
0
String operator+(const String& a, const String& b)
{
    if (a.isEmpty())
        return b.copy();
    if (b.isEmpty())
        return a.copy();
    String c = a.copy();
    c += b;
    return c;
}
Ejemplo n.º 4
0
// Check if the specified directory exists
bool MassStorage::DirectoryExists(const char *path) const
{
	// Remove any trailing '/' from the directory name, it sometimes (but not always) confuses f_opendir
	String<MaxFilenameLength> loc;
	loc.copy(path);
	return DirectoryExists(loc.GetRef());
}
Ejemplo n.º 5
0
SQLStatement::SQLStatement(const String& statement, const Vector<SQLValue>& arguments, PassRefPtr<SQLStatementCallback> callback, PassRefPtr<SQLStatementErrorCallback> errorCallback)
    : m_statement(statement.copy())
    , m_arguments(arguments)
    , m_statementCallback(callback)
    , m_statementErrorCallback(errorCallback)
{
}
Ejemplo n.º 6
0
	char *AsmBuf::ExtractPublicSymbol(char *sName)
	{
		String str;
		String symName(sName);
		int st,nd,nd1;
		st = 0;
		String s1((char *)"public");
j1:
        s1.add(symName);
		st =find(s1, st);
		if (st < 0)
			return (char *)"";
		// Make sure the name matches exactly, and is not a substring.
		if (IsIdentChar(buf()[st+7+symName.len()])) {
			st += 7+symName.len();
			goto j1;
		}
		s1.copy("endpublic");
		nd = find(s1,st);
		if (nd < 0)
			return (char *)"";
		s1.copy("\r\n");
		nd1 = find(s1,nd);
		if (nd1 > 0)
			nd = nd1;
		else
			nd += 9;	// skip over to end of "endpublic"
		str.copy(&buf()[st],nd-st);
		return str.buf();
	}
Ejemplo n.º 7
0
void DebugController :: readList(_DebuggerWatch* watch, int* list, int length)
{
   String<ident_c, 10> index;
   for (int i = 0 ; i < length ; i++)  {
      index.copy("[");
      index.appendInt(i);
      index.append("]");
      size_t memberPtr = list[i];
      if (memberPtr==0) {
         watch->write(this, memberPtr, index, "<nil>");
      }
      else {
         int flags = 0;
         ident_t className = NULL;
         DebugLineInfo* item = seekClassInfo(memberPtr, className, flags);
         if (item) {
            watch->write(this, memberPtr, index, className);
         }
         //// if unknown check if it is a dynamic subject
         //else if (test(flags, elDynamicSubjectRole)) {
         //   watch->write(this, memberPtr, index, _T("<subject>"));
         //}
         //// if unknown check if it is a group object
         //else if (test(flags, elGroup)) {
         //   watch->write(this, memberPtr, index, test(flags, elCastGroup) ? _T("<broadcast group>") : _T("<group>"));
         //}
         else watch->write(this, memberPtr, index, "<unknown>");
      }
   }
}
Ejemplo n.º 8
0
InsertIntoTextNodeCommand::InsertIntoTextNodeCommand(Document *document, Text *node, int offset, const String &text)
    : EditCommand(document), m_node(node), m_offset(offset)
{
    ASSERT(m_node);
    ASSERT(m_offset >= 0);
    ASSERT(!text.isEmpty());

    m_text = text.copy(); // make a copy to ensure that the string never changes
}
Ejemplo n.º 9
0
LocalStorage::LocalStorage(const String& path)
    : m_path(path.copy())
{
    // If the path is empty, we know we're never going to be using the thread for anything, so don't start it.
    // In the future, we might also want to consider removing it from the DOM in that case - <rdar://problem/5960470>
    if (path.isEmpty())
        return;

    m_thread = LocalStorageThread::create();
    m_thread->start();
    m_thread->scheduleImport(this);
}
Ejemplo n.º 10
0
Ref<Tip, Owner> HaxeMessageSyntax::parse(String message)
{
	Ref<Tip, Owner> tip;
	Ref<Token, Owner> rootToken = match(message);
	if (rootToken) {
		Ref<Token> token = rootToken->firstChild();
		if (token->rule() == typeTip_) {
			token = token->firstChild();
			if (token->rule() == value_) {
				String typeString = readValue(message, token);
				tip = new TypeTip(readType(typeString));
			}
		}
		else if (token->rule() == membersTip_) {
			Ref<Members, Owner> members = new Members(token->countChildren());
			int memberIndex = 0;
			token = token->firstChild();
			while (token) {
				String name, description;
				Ref<Type, Owner> type;
				Ref<Token> child = token->firstChild();
				while (child) {
					if (child->rule() == memberName_)
						name = message->copy(child->i0(), child->i1());
					else if (child->rule() == memberType_)
						type = readType(readValue(message, child));
					else if (child->rule() == memberDescription_)
						description = message->copy(child->i0(), child->i1());;
					child = child->nextSibling();
				}
				// debug("\"%%\",\"%%\",\"%%\"\n", name, type, description);
				members->set(memberIndex++, new Member(name, type, description));
				token = token->nextSibling();
			}
			tip = new MembersTip(members);
		}
	}
	
	return tip;
}
Ejemplo n.º 11
0
String HaxeMessageSyntax::readValue(String message, Ref<Token> token)
{
	if (token->firstChild()) {
		StringList list;
		Ref<Token> child = token->firstChild();
		int i = token->i0();
		while (child) {
			if (i < child->i0())
				list.append(message->copy(i, child->i0()));
			String s;
			if (child->keyword() == gt_) s = ">";
			else if (child->keyword() == lt_) s = "<";
			else s = message->copy(child->i0(), child->i1());
			list.append(s);
			i = child->i1();
			child = child->nextSibling();
		}
		if (i < token->i1())
			list.append(message->copy(i, token->i1()));
		return list.join();
	}
	else
		return message->copy(token->i0(), token->i1());
}
Ejemplo n.º 12
0
// Open a directory to read a file list. Returns true if it contains any files, false otherwise.
// If this returns true then the file system mutex is owned. The caller must subsequently release the mutex either
// by calling FindNext until it returns false, or by calling AbandonFindNext.
bool MassStorage::FindFirst(const char *directory, FileInfo &file_info)
{
	// Remove any trailing '/' from the directory name, it sometimes (but not always) confuses f_opendir
	String<MaxFilenameLength> loc;
	loc.copy(directory);
	const size_t len = loc.strlen();
	if (len != 0 && (loc[len - 1] == '/' || loc[len - 1] == '\\'))
	{
		loc.Truncate(len - 1);
	}

	if (!dirMutex.Take(10000))
	{
		return false;
	}

	FRESULT res = f_opendir(&findDir, loc.c_str());
	if (res == FR_OK)
	{
		FILINFO entry;

		for (;;)
		{
			res = f_readdir(&findDir, &entry);
			if (res != FR_OK || entry.fname[0] == 0) break;
			if (!StringEqualsIgnoreCase(entry.fname, ".") && !StringEqualsIgnoreCase(entry.fname, ".."))
			{
				file_info.isDirectory = (entry.fattrib & AM_DIR);
				file_info.fileName.copy(entry.fname);
				file_info.size = entry.fsize;
				file_info.lastModified = ConvertTimeStamp(entry.fdate, entry.ftime);
				return true;
			}
		}
		f_closedir(&findDir);
	}

	dirMutex.Release();
	return false;
}
Ejemplo n.º 13
0
void DebugController::readParams(_DebuggerWatch* watch, ref_t address, ident_t name, bool ignoreInline)
{
   if (address != 0) {

      String<ident_c, 255> index;
      for (int i = 0 ; i < 255 ; i++)  {
         index.copy(name);
         index.append("[");
         index.appendInt(i);
         index.append("]");

         size_t memberPtr = 0;
         getValue(address, (char*)&memberPtr, 4);
         // break if zero is found
         if (memberPtr == 0)
            break;

         int flags = 0;
         ident_t className = NULL;
         DebugLineInfo* item = seekClassInfo(memberPtr, className, flags);
         if (item) {
            watch->write(this, memberPtr, index, className);
         }
         //// if unknown check if it is a dynamic subject
         //else if (test(flags, elDynamicSubjectRole)) {
         //   watch->write(this, memberPtr, index, _T("<subject>"));
         //}
         //// if unknown check if it is a group object
         //else if (test(flags, elGroup)) {
         //   watch->write(this, memberPtr, index, test(flags, elCastGroup) ? _T("<broadcast group>") : _T("<group>"));
         //}
         else watch->write(this, memberPtr, index, "<unknown>");

         address += 4;
      }
   }
   else watch->write(this, address, name, "<nil>");
}
Ejemplo n.º 14
0
ProcessStatus::ProcessStatus(pid_t processId)
{
#ifdef __linux
	String path = Format("/proc/%%/stat") << processId;
	Ref<File, Owner> file = new File(path);
	file->open(File::Read);
	Ref<LineSource, Owner> source = new LineSource(file);
	String line = source->readLine();
	{
		// extract command name first, because it may contain whitespace
		int i0 = line->find('(') + 1, i1 = line->find(')');
		commandName_ = line->copy(i0, i1);
		for (int i = i0; i < i1; ++i)
			line->set(i, 'x');
	}
	Ref<StringList, Owner> parts = line.split(" ");
	processId_ = parts->at(0).toInt();
	parentProcessId_ = parts->at(3).toInt();
	processGroupId_ = parts->at(4).toInt();
	foregroundProcessGroupId_ = parts->at(7).toInt();
	/*{
		int code = parts->get(6).toInt();
		int major = (code >> 8) & 0xFF;
		int minor = (code & 0xFF) | ((code >> 20) << 8);
		// interpretation according to lanana.org
		if (major == 4)
			terminalName_ = Format("tty%%") << minor;
		else if ((136 <= major) && (major <= 143))
			terminalName_ = Format("pts/%%") << minor;
		else if (major == 3)
			terminalName_ = Format("ttyp%%") << minor;
	}*/
	loginName_ = User(FileStatus(path).ownerId()).loginName();
	processStatus_ = parts->at(2)->get(0);
	file->close();
#else // def __linux
#ifdef KERN_PROC2 // e.g. on OpenBSD
	size_t sz = sizeof(kinfo_proc2);
	struct kinfo_proc2* proc = (kinfo_proc2*)ftl::malloc(sz);
	mem::clr(proc, sz);
	int mib[] = {
		CTL_KERN,
		KERN_PROC2,
		KERN_PROC_PID,
		processId,
		sz,
		1
	};
	if (::sysctl(mib, sizeof(mib)/sizeof(mib[0]), proc, &sz, NULL, 0) == -1)
		FTL_SYSTEM_EXCEPTION;
	processId_ = proc->p_pid;
	parentProcessId_ = proc->p_ppid;
	processGroupId_ = proc->p__pgid;
	foregroundProcessGroupId_ = proc->p_tpgid;
	/*const int ttyNameSize = 256;
	char ttyName[ttyNameSize];
	terminalName_ = devname_r(proc->kp_eproc.e_tdev, S_IFCHR, ttyName, ttyNameSize);*/
	loginName_ = User(proc->p_ruid).loginName();
	commandName_ = proc->p_comm;
	processStatus_ = proc->p_stat;
	if (processStatus_ == SIDL) processStatus_ = 'W';
	else if (processStatus_ == SRUN) processStatus_ = 'R';
	#ifdef SONPROC
	else if (processStatus_ == SONPROC) processStatus_ = 'R';
	#endif
	else if (processStatus_ == SSLEEP) processStatus_ = 'S';
	else if (processStatus_ == SSTOP) processStatus_ = 'T';
	else if (processStatus_ == SZOMB) processStatus_ = 'Z';
	#ifdef SDEAD
	else if (processStatus_ == SDEAD) processStatus_ = 'Z';
	#endif
	else processStatus_ = '?';
	ftl::free(proc);
#else // def KERN_PROC2
	struct kinfo_proc* proc;
	int mib[4];
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PID;
	mib[3] = processId;
	size_t sz = 0;
	if (::sysctl(mib, 4, NULL, &sz, NULL, 0) == -1)
		FTL_SYSTEM_EXCEPTION;
	proc = (kinfo_proc*)ftl::malloc(sz);
	mem::clr(proc, sz);
	if (::sysctl(mib, 4, proc, &sz, NULL, 0) == -1)
		FTL_SYSTEM_EXCEPTION;
	processId_ = proc->kp_proc.p_pid;
	parentProcessId_ = proc->kp_eproc.e_ppid;
	processGroupId_ = proc->kp_eproc.e_pgid;
	foregroundProcessGroupId_ = proc->kp_eproc.e_tpgid;
	/*const int ttyNameSize = 256;
	char ttyName[ttyNameSize];
	terminalName_ = devname_r(proc->kp_eproc.e_tdev, S_IFCHR, ttyName, ttyNameSize);*/
	loginName_ = User(proc->kp_eproc.e_pcred.p_ruid).loginName();
	commandName_ = proc->kp_proc.p_comm;
	processStatus_ = proc->kp_proc.p_stat;
	if (processStatus_ == SIDL) processStatus_ = 'W';
	else if (processStatus_ == SRUN) processStatus_ = 'R';
	#ifdef SONPROC
	else if (processStatus_ == SONPROC) processStatus_ = 'R';
	#endif
	#ifdef __MACH__
	else if (processStatus_ == SSLEEP) processStatus_ = (proc->kp_proc.sigwait) ? 'S' : 'D';
	#else
	else if (processStatus_ == SSLEEP) processStatus_ = 'S';
	#endif
	else if (processStatus_ == SSTOP) processStatus_ = 'T';
	else if (processStatus_ == SZOMB) processStatus_ = 'Z';
	#ifdef SDEAD
	else if (processStatus_ == SDEAD) processStatus_ = 'Z';
	#endif
	else processStatus_ = '?';
	ftl::free(proc);
#endif // def KERN_PROC2
#endif // def __linux
}
Ejemplo n.º 15
0
void WebIconDatabase::dispatchDidAddIconForPageURL(const String& pageURL)
{   
    MutexLocker locker(m_notificationMutex);
    m_notificationQueue.append(pageURL.copy());
    scheduleNotificationDelivery();
}
Ejemplo n.º 16
0
/**
* Windows specific file dialog opener
*
*  @param fileName the name of the file to save (in case @param mode is FILEMODE_SAVE)
*  otherwise ignored.
*  @param mode either FILEMODE_SAVE or FILEMODE_OPEN depending on whether
*  the dialog should be "Save as.." og "Open file.."
*  @param owner handle to the owner window
*/
String Environment::LoadFileDialog( String fileName, UInt mode, HWND owner )
{
	char Filestring[4196];
	//reset Filestring
	for ( UInt i = 0; i < 4196; i++ )
		Filestring[i] = 0;
	String returnstring;
	OPENFILENAME opf;
	LPCTSTR filter;
	Vector<char> str2;

	if ( mode == FILEMODE_OPEN )
	{
		filter = "Fits files\0*.FITS;*.FIT;*.FTS;*.IMG;*.LBL;\0\0";
		opf.lpstrDefExt = "fit";
		
		
	
	}
	else if ( mode == FILEMODE_SAVE )
	{		
		filter = "Tiff files\0*.TIFF;*.TIF\0\0";
		opf.lpstrDefExt = "tif";
		//get the position of the last '.' which defines the file extension
		Int pos = fileName.find_last_of( ".", String::npos );
		if ( pos > 0 )
			fileName = fileName.substr( 0, pos );

		fileName = fileName + ".tif";

		fileName = Environment::getFilePart( fileName );
		
		
		fileName.copy( Filestring, fileName.length(), 0 );

		
	}
	
	opf.lpstrTitle = NULL;
	opf.hwndOwner = owner;
	opf.hInstance = NULL;
	opf.lpstrFilter = filter;
	opf.lpstrCustomFilter = NULL;
	opf.nMaxCustFilter = 0L;
	opf.nFilterIndex = 1L;
	opf.lpstrFile = Filestring;	
	opf.nMaxFile = 4196;
	opf.lpstrFileTitle = NULL;
	opf.nMaxFileTitle=50;
	opf.lpstrInitialDir = NULL;

	opf.nFileOffset = NULL;
	opf.nFileExtension = NULL;
	
	opf.lpfnHook = NULL; 
	opf.lCustData = NULL;
	opf.Flags = (OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT) & ~OFN_ALLOWMULTISELECT;  
	opf.lStructSize = sizeof(OPENFILENAME);
	opf.FlagsEx = 0; 
	if ( mode == FILEMODE_OPEN )
	{
		if(GetOpenFileName(&opf))    		        
			returnstring = opf.lpstrFile;
	}
	else if ( mode == FILEMODE_SAVE )
	{
		if(GetSaveFileName(&opf))    		        
			returnstring = opf.lpstrFile;
	}
	return returnstring;
}
Ejemplo n.º 17
0
 MessageWorkerContextTask(const String& message)
     : m_message(message.copy())
 {
 }
Ejemplo n.º 18
0
 MessageWorkerTask(const String& message, WorkerMessagingProxy* messagingProxy)
     : m_message(message.copy())
     , m_messagingProxy(messagingProxy)
 {
 }
Ejemplo n.º 19
0
FALCON_FUNC img_Load ( VMachine *vm )
{
   // Check provided parameters
   Item *i_file = vm->param(0);
   Item *i_type = vm->param(1);

   if ( i_file == 0 ||
      ( ! i_file->isString() &&
            !( i_file->isObject() && i_file->asObject()->derivedFrom("Stream") ))||
      ( i_type != 0 && ! i_type->isString() ) )
   {
      throw new ParamError( ErrorParam( e_inv_params, __LINE__ ).
         extra( "S|Stream, [S]" ) ) ;
      return;
   }

   // see if we need to cache our service
   if( s_sdlservice == 0 )
   {
      s_sdlservice = static_cast<SDLService*>(vm->getService ( SDL_SERVICE_SIGNATURE ));
   }

   // Load the new image
   ::SDL_Surface *surf;
   if( i_file->isString() )
   {
      String* file = i_file->asString();

      // Get the right path on the current system
      Path filePath( *file );
#ifdef FALCON_SYSTEM_WIN
      file->size( 0 );
      filePath.getWinFormat( *file );
#else
      file->copy( filePath.get() );
#endif

      // Convert filename to a C string
      AutoCString fname( *file );

      surf = ::IMG_Load( fname.c_str() );
      if ( surf == NULL )
      {
         throw new SDLError( ErrorParam( FALCON_SDL_ERROR_BASE + 3, __LINE__ )
            .desc( "IMG_Load" )
            .extra( IMG_GetError() ) ) ;
         return;
      }
   }
   else {
      struct SDL_RWops rwops;
      Stream* stream = static_cast<Stream *>(i_file->asObject()->getUserData());
      s_sdlservice->rwopsFromStream( rwops, stream );
      if ( i_type != 0 )
      {
         AutoCString type( *i_type->asString() );
         surf = ::IMG_LoadTyped_RW( &rwops, 0, const_cast<char *>( type.c_str() ) );
      }
      else
         surf = ::IMG_Load_RW( &rwops, 0 );
   }

   // Copy the new item in a surface
   CoreObject* ret = s_sdlservice->createSurfaceInstance ( vm, surf );

   vm->retval( ret );
}
Ejemplo n.º 20
0
int main(int argc, char** argv)
{
	if (argc != 2) {
		print("Usage: %% [FILE]\n", File(argv[0]).name());
		return 0;
	}
	
	String text = File::load(argv[1]);
	if (!text.valid()) {
		print("Input data is not conforming to UTF8 encoding.\n");
		return 1;
	}
	if (text == "") {
		print("Input file empty.\n");
		return 2;
	}
	
	print("text = \"%%\"\n", text->data());
	
	int nf = 0, nb = 0; // forward, backward character count
	for (String::Index i = text.first(); i.valid(); ++i) ++nf;
	for (String::Index i = text.last(); i.valid(); --i) ++nb;
	
	print("======================\n");
	
	for (String::Index i = text.last(); i.valid(); --i) {
		uchar_t ch = text.get(i);
		print("text[0x%%] = %% / '%%'\n", i.pos() - i.data(), ch, text.copy(i, i+1));
	}
	
	print("----------------------\n");
	
	for (String::Index i = text.first(); i.valid(); ++i) {
		uchar_t ch = text.get(i);
		print("text[0x%%] = %% / '%%'\n", i.pos() - i.data(), ch, text.copy(i, i+1));
	}
	
	print("nf, nb = %%, %%\n", nf, nb);
	if (nf != nb) {
		print("Test failed: nf != nb\n");
		return 3;
	}
	
	print("----------------------\n");
	
	{
		String s("123x");
		const char* pattern = "x";
		String::Index i = s.find(pattern);
		print("Find \"%%\" in \"%%\": valid = %%\n", pattern, s->data(), s.def(i));
		/*print("s == String(s.split(pattern), pattern): %%\n", s == String(s.split(pattern), pattern));
		print("s.split(pattern)->length() = %%\n", s.split(pattern)->length());
		print("String(s.split(pattern), pattern) = '%%'\n", String(s.split(pattern), pattern).data());*/
	}
	
	Ref<StringList, Owner> lines = text.split("\n");
	print("Number of lines: %%\n", lines->length());
	int j = 0;
	for (StringList::Index i = lines->first(); lines->def(i); ++i, ++j)
		print("%%: '%%' (%%)\n", j, lines->at(i)->data(), lines->at(i)->size());
	
	return 0;
}
Ejemplo n.º 21
0
void PreflightResultCache::appendEntry(const String& origin, const KURL& url, PreflightResultCacheItem* preflightResult)
{
    MutexLocker lock(m_mutex);
    // Note that the entry may already be present in the HashMap if another thread is accessing the same location.
    m_preflightHashMap.set(std::make_pair(origin.copy(), url.copy()), preflightResult);
}
SharedVariant::SharedVariant(CVarRef source, bool serialized,
                             bool inner /* = false */,
                             bool unserializeObj /* = false */)
  : m_count (1), m_shouldCache(false), m_flags(0){
  ASSERT(!serialized || source.isString());

  m_type = source.getType();

  switch (m_type) {
  case KindOfBoolean:
    {
      m_data.num = source.toBoolean();
      break;
    }
  case KindOfByte:
  case KindOfInt16:
  case KindOfInt32:
  case KindOfInt64:
    {
      m_type = KindOfInt64;
      m_data.num = source.toInt64();
      break;
    }
  case KindOfDouble:
    {
      m_data.dbl = source.toDouble();
      break;
    }
  case KindOfStaticString:
  case KindOfString:
    {
      String s = source.toString();
      if (serialized) {
        m_type = KindOfObject;
        // It is priming, and there might not be the right class definitions
        // for unserialization.
        s = apc_reserialize(s);
      }
      m_data.str = s->copy(true);
      break;
    }
  case KindOfArray:
    {
      ArrayData *arr = source.getArrayData();

      if (!inner) {
        // only need to call hasInternalReference() on the toplevel array
        PointerSet seen;
        if (arr->hasInternalReference(seen)) {
          setSerializedArray();
          m_shouldCache = true;
          String s = apc_serialize(source);
          m_data.str = new StringData(s.data(), s.size(), CopyString);
          break;
        }
      }

      size_t size = arr->size();
      if (arr->isVectorData()) {
        setIsVector();
        m_data.vec = new VectorData(size);
        uint i = 0;
        for (ArrayIter it(arr); !it.end(); it.next(), i++) {
          SharedVariant* val = Create(it.secondRef(), false, true,
                                      unserializeObj);
          if (val->m_shouldCache) m_shouldCache = true;
          m_data.vec->vals[i] = val;
        }
      } else {
        m_data.map = new ImmutableMap(size);
        for (ArrayIter it(arr); !it.end(); it.next()) {
          SharedVariant* key = Create(it.first(), false, true,
                                      unserializeObj);
          SharedVariant* val = Create(it.secondRef(), false, true,
                                      unserializeObj);
          if (val->m_shouldCache) m_shouldCache = true;
          m_data.map->add(key, val);
        }
      }
      break;
    }
  case KindOfNull:
    {
      m_data.num = 0;
      break;
    }
  default:
    {
      ASSERT(source.isObject());
      m_shouldCache = true;
      if (unserializeObj) {
        // This assumes hasInternalReference(seen, true) is false
        ImmutableObj* obj = new ImmutableObj(source.getObjectData());
        m_data.obj = obj;
        setIsObj();
      } else {
        String s = apc_serialize(source);
        m_data.str = new StringData(s.data(), s.size(), CopyString);
      }
      break;
    }
  }
}
WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode)
    : m_scriptURL(scriptURL.copy())
    , m_userAgent(userAgent.copy())
    , m_sourceCode(sourceCode.copy())
{
}
 Task(PassRefPtr<ScriptExecutionContext::Task> task, const String& mode)
     : m_task(task)
     , m_mode(mode.copy())
 {
 }
Ejemplo n.º 25
0
ThreadSharedVariant::ThreadSharedVariant(CVarRef source, bool serialized,
                                         bool inner /* = false */) {
  ASSERT(!serialized || source.isString());

  setOwner();
  m_ref = 1;

  switch (source.getType()) {
  case KindOfBoolean:
    {
      m_type = KindOfBoolean;
      m_data.num = source.toBoolean();
      break;
    }
  case KindOfByte:
  case KindOfInt16:
  case KindOfInt32:
  case KindOfInt64:
    {
      m_type = KindOfInt64;
      m_data.num = source.toInt64();
      break;
    }
  case KindOfDouble:
    {
      m_type = KindOfDouble;
      m_data.dbl = source.toDouble();
      break;
    }
  case KindOfStaticString:
  case KindOfString:
    {
      String s = source.toString();
      m_type = serialized ? KindOfObject : KindOfString;
      if (serialized) {
        // It is priming, and there might not be the right class definitions
        // for unserialization.
        s = apc_reserialize(s);
      }
      m_data.str = s->copy(true);
      break;
    }
  case KindOfArray:
    {
      m_type = KindOfArray;

      ArrayData *arr = source.getArrayData();

      if (!inner) {
        // only need to call hasInternalReference() on the toplevel array
        PointerSet seen;
        if (arr->hasInternalReference(seen)) {
          setSerializedArray();
          setShouldCache();
          String s = apc_serialize(source);
          m_data.str = new StringData(s.data(), s.size(), CopyString);
          break;
        }
      }

      size_t size = arr->size();
      if (arr->isVectorData()) {
        setIsVector();
        m_data.vec = new VectorData(size);
        uint i = 0;
        for (ArrayIter it(arr); !it.end(); it.next(), i++) {
          ThreadSharedVariant* val = createAnother(it.second(), false, true);
          if (val->shouldCache()) setShouldCache();
          m_data.vec->vals[i] = val;
        }
      } else {
        m_data.map = new ImmutableMap(size);
        uint i = 0;
        for (ArrayIter it(arr); !it.end(); it.next(), i++) {
          ThreadSharedVariant* key = createAnother(it.first(), false);
          ThreadSharedVariant* val = createAnother(it.second(), false, true);
          if (val->shouldCache()) setShouldCache();
          m_data.map->add(key, val);
        }
      }
      break;
    }
  default:
    {
      m_type = KindOfObject;
      setShouldCache();
      String s = apc_serialize(source);
      m_data.str = new StringData(s.data(), s.size(), CopyString);
      break;
    }
  }
}
Ejemplo n.º 26
0
		static void copy(String const& input, char* dest)
		{ 
			UINT32 len = (UINT32)input.length();
			input.copy(dest, len);
			dest[len] = '\0';
		}
Ejemplo n.º 27
0
// Open a local file (for example on an SD card).
// This is protected - only Platform can access it.
bool FileStore::Open(const char* directory, const char* fileName, OpenMode mode, uint32_t preAllocSize)
{
	String<MaxFilenameLength> location;
	MassStorage::CombineName(location.GetRef(), directory, fileName);
	const bool writing = (mode == OpenMode::write || mode == OpenMode::append);
	writeBuffer = nullptr;

	if (writing)
	{
		// Try to create the path of this file if we want to write to it
		String<MaxFilenameLength> filePath;
		filePath.copy(location.c_str());

		size_t i = (isdigit(filePath[0]) && filePath[1] == ':') ? 2 : 0;
		if (filePath[i] == '/')
		{
			++i;
		}

		while (i < filePath.strlen())
		{
			if (filePath[i] == '/')
			{
				filePath[i] = 0;
				if (!reprap.GetPlatform().GetMassStorage()->DirectoryExists(filePath.GetRef()) && !reprap.GetPlatform().GetMassStorage()->MakeDirectory(filePath.c_str()))
				{
					reprap.GetPlatform().MessageF(ErrorMessage, "Failed to create folder %s while trying to open file %s\n", filePath.c_str(), location.c_str());
					return false;
				}
				filePath[i] = '/';
			}
			++i;
		}

		// Also try to allocate a write buffer so we can perform faster writes
		// We only do this if the mode is write, not append, because we don't want to use up a large buffer to append messages to the log file,
		// especially as we need to flush messages to SD card regularly.
		// Currently, append mode is used for the log file and for appending simulated print times to GCodes files (which required read access too).
		if (mode == OpenMode::write)
		{
			writeBuffer = reprap.GetPlatform().GetMassStorage()->AllocateWriteBuffer();
		}
	}

	const FRESULT openReturn = f_open(&file, location.c_str(),
										(mode == OpenMode::write) ?  FA_CREATE_ALWAYS | FA_WRITE
											: (mode == OpenMode::append) ? FA_READ | FA_WRITE | FA_OPEN_ALWAYS
												: FA_OPEN_EXISTING | FA_READ);
	if (openReturn != FR_OK)
	{
		if (writeBuffer != nullptr)
		{
			reprap.GetPlatform().GetMassStorage()->ReleaseWriteBuffer(writeBuffer);
			writeBuffer = nullptr;
		}

		// We no longer report an error if opening a file in read mode fails unless debugging is enabled, because sometimes that is quite normal.
		// It is up to the caller to report an error if necessary.
		if (reprap.Debug(modulePlatform))
		{
			reprap.GetPlatform().MessageF(WarningMessage, "Failed to open %s to %s, error code %d\n", location.c_str(), (writing) ? "write" : "read", (int)openReturn);
		}
		return false;
	}

	crc.Reset();
	usageMode = (writing) ? FileUseMode::readWrite : FileUseMode::readOnly;
	openCount = 1;
	if (mode == OpenMode::write && preAllocSize != 0)
	{
		const FRESULT expandReturn = f_expand(&file, preAllocSize, 1);		// try to pre-allocate contiguous space - it doesn't matter if it fails
		if (reprap.Debug(moduleStorage))
		{
			debugPrintf("Preallocating %" PRIu32 " bytes returned %d\n", preAllocSize, (int)expandReturn);
		}
	}
	return true;
}
Ejemplo n.º 28
0
CrossThreadCopierBase<false, String>::Type CrossThreadCopierBase<false, String>::copy(const String& str)
{
    return str.copy();
}
SharedWorkerProxy::SharedWorkerProxy(const String& name, const KURL& url)
    : m_closing(false)
    , m_name(name.copy())
    , m_url(url.copy())
{
}
void WorkerRunLoop::postTaskForMode(PassRefPtr<ScriptExecutionContext::Task> task, const String& mode)
{
    m_messageQueue.append(Task::create(task, mode.copy()));
}