void  layprop::ViewProperties::lockLayer(word layno, bool lock) {
   // No error messages here, because of possible range use
   while (wxMUTEX_NO_ERROR != DBLock.TryLock());
   if (_drawprop._layset.end() != _drawprop._layset.find(layno))
      _drawprop._layset[layno]->_locked = lock;
   DBLock.Unlock();
}
	/*****************************************************
	**
	**   AtlasLogicCountWorker   ---   Entry
	**
	******************************************************/
	ExitCode Entry()
	{
		while ( sharedSection->doExit == false )
		{
			Sleep( COUNT_THREAD_SLEEP_MILLISEC );
			if ( sharedSection->countHasOrder )
			{
#ifdef DEB_ATLAS_LOGIC
				printf( "AtlasLogicCountWorker: location count started, filter \"%s\", country \"%s\", mode %d\n",
					str2char( logic->filter ), str2char( logic->country ), logic->mode );
				wxLongLong starttime = wxGetLocalTimeMillis();
#endif
				sharedSection->countHasOrder = false;
				int c = dao->getMatchCount( logic->filter, logic->country, logic->mode );

				if ( sharedSection->countHasOrder )
				{
					// new order arrived, filter conditions have changed meanwhile: do not write results
					printf( "WARN: AtlasLogicCountWorker has new order before finishing request\n" );
				}
				else
				{
					mutex.Lock();
					sharedSection->countHasNews = true;
					sharedSection->count = c;
					mutex.Unlock();
#ifdef DEB_ATLAS_LOGIC
					wxLongLong duration = wxGetLocalTimeMillis() - starttime;
					printf( "AtlasLogicCountWorker: Location count finished, %d results in %ld millisec\n", c, duration.ToLong() );
#endif
				}
			}
		}
		return 0;
	}
bool wxSoundSyncOnlyAdaptor::Play(wxSoundData *data, unsigned flags,
                                  volatile wxSoundPlaybackStatus *status)
{
    Stop();
    if (flags & wxSOUND_ASYNC)
    {
#if wxUSE_THREADS
        m_mutexRightToPlay.Lock();
        m_status.m_playing = true;
        m_status.m_stopRequested = false;
        data->IncRef();
        wxThread *th = new wxSoundAsyncPlaybackThread(this, data, flags);
        th->Create();
        th->Run();
        wxLogTrace(_T("sound"), _T("launched async playback thread"));
        return true;
#else
        wxLogError(_("Unable to play sound asynchronously."));
        return false;
#endif
    }
    else
    {
#if wxUSE_THREADS
        m_mutexRightToPlay.Lock();
#endif
        bool rv = m_backend->Play(data, flags, status);
#if wxUSE_THREADS
        m_mutexRightToPlay.Unlock();
#endif
        return rv;
    }
}
/*****************************************************
**
**   AtlasLogic   ---   getEntryByRowId
**
******************************************************/
AtlasEntry *AtlasLogic::getEntryByRowId( const int &rowid )
{
	assert( sharedSection );

	mutex.Lock();
	for ( int i = 0; i < ATLAS_MAX_GRID_ELEMENTS; i++ )
	{
		if ( entries[i] != 0 && entries[i]->rowid == rowid )
		{
			mutex.Unlock();
			return entries[i];
		}
	}
	mutex.Unlock();

	if ( rowid > 0 && ! sharedSection->fetchHasOrder && ! sharedSection->fetchIsWorking )
	{
		mutex.Lock();
		resetEntries();
		sharedSection->fetchOffset = Max( 0, rowid - 15 );
		sharedSection->fetchHasOrder = true;
		mutex.Unlock();
	}
	return 0;
}
void AtlasImporter::setDatabaseFile( wxString s )
{
	assert( sharedSection );
	mutex.Lock();
	sharedSection->dbfile = s;
	mutex.Unlock();
}
void AtlasImporter::setImportFile( wxString s )
{
	assert( sharedSection );
	mutex.Lock();
	sharedSection->sqlfile = s;
	mutex.Unlock();
}
void layprop::ViewProperties::setGrid(byte No, real step, std::string colname) {
   while (wxMUTEX_NO_ERROR != DBLock.TryLock());
   if (_grid.end() != _grid.find(No)) // if this grid No is already defined
      _grid[No]->Init(step,colname);
   else // define a new grid
      _grid[No] = new layprop::LayoutGrid(step, colname);
   DBLock.Unlock();
}
bool layprop::ViewProperties::viewGrid(byte No, bool status) {
   while (wxMUTEX_NO_ERROR != DBLock.TryLock());
   if (_grid.end() != _grid.find(No)) 
      _grid[No]->turnover(status);
   else status = false;
   DBLock.Unlock();
   return status;
}
/*****************************************************
**
**   AtlasLogic   ---   updateFilter
**
******************************************************/
void AtlasLogic::updateFilter()
{
	mutex.Lock();
	resetEntries();

	assert( sharedSection );
	sharedSection->countHasOrder = true;
	sharedSection->fetchHasOrder = true;
	mutex.Unlock();
}
void DataCenter::openGL_draw(layprop::DrawProperties& drawprop) {
// Maybe we need another try/catch in the layoutcanvas ?   
   if (_TEDDB) {
//      _TEDDB->check_active();
      while (wxMUTEX_NO_ERROR != DBLock.TryLock());
      _TEDDB->openGL_draw(drawprop);
      DBLock.Unlock();
   }
// 
//   else throw EXPTNactive_DB();      
}
Beispiel #11
0
void layprop::ViewProperties::addfill(std::string name, byte* ptrn) {
   while (wxMUTEX_NO_ERROR != DBLock.TryLock());
   if (_drawprop._layfill.end() != _drawprop._layfill.find(name)) {
      delete [] _drawprop._layfill[name];
      std::ostringstream ost;
      ost << "Warning! Fill \""<<name<<"\" redefined";
      tell_log(console::MT_WARNING, ost.str());
   }
   _drawprop._layfill[name] = ptrn;
   DBLock.Unlock();
}
void DataCenter::tmp_draw(const layprop::DrawProperties& drawprop,
                              TP base, TP newp) {
   if (_TEDDB) {
//      _TEDDB->check_active();
      while (wxMUTEX_NO_ERROR != DBLock.TryLock());
      _TEDDB->tmp_draw(drawprop, base, newp);
      DBLock.Unlock();
   }
// 
//   else throw EXPTNactive_DB();      
}
Beispiel #13
0
void layprop::ViewProperties::addcolor(std::string name, byte R, byte G, byte B, byte A) {
   while (wxMUTEX_NO_ERROR != DBLock.TryLock());
   if (_drawprop._laycolors.end() != _drawprop._laycolors.find(name)) {
      delete _drawprop._laycolors[name];
      std::ostringstream ost;
      ost << "Warning! Color \""<<name<<"\" redefined";
      tell_log(console::MT_WARNING, ost.str());
   }
   tellRGB* col = new tellRGB(R,G,B,A);
   _drawprop._laycolors[name] = col;
   DBLock.Unlock();
}
Beispiel #14
0
	/*****************************************************
	**
	**   AtlasLogicFetchWorker   ---   Entry
	**
	******************************************************/
	ExitCode Entry()
	{
		while ( sharedSection->doExit == false )
		{
			Sleep( FETCH_THREAD_SLEEP_MILLISEC );
			if ( sharedSection->fetchHasOrder )
			{
				sharedSection->fetchIsWorking = true;
#ifdef DEB_ATLAS_LOGIC
				printf( "AtlasLogicFetchWorker: location fetch started, filter \"%s\", country \"%s\", mode %d offset %d\n",
					str2char( logic->filter ), str2char( logic->country ), logic->mode, sharedSection->fetchOffset );
				wxLongLong starttime = wxGetLocalTimeMillis();
#endif

				sharedSection->fetchHasOrder = false;
				logic->resetEntries();

				vector<AtlasEntry> l = dao->getEntries( logic->filter, logic->country, logic->mode,
					ATLAS_MAX_GRID_ELEMENTS, sharedSection->fetchOffset );

				if ( l.size() > 0 )
				{
					mutex.Lock();
					for ( unsigned int i = 0; i < l.size(); i++ )
					{
						l[i].country = logic->getCountryName( l[i].country_code );
						l[i].admin = logic->getAdminName( l[i].country_code, l[i].admin1_code );

						logic->entries[i] = new AtlasEntry( l[i] );
					}
#ifdef DEB_ATLAS_LOGIC
					wxLongLong duration = wxGetLocalTimeMillis() - starttime;
					printf( "AtlasLogicFetchWorker: location fetch finished, %d results in %ld millisec\n", (int)l.size(), duration.ToLong() );
#endif

					if ( sharedSection->fetchHasOrder )
					{
						// filter conditions have changed meanwhile: do not write results
						printf( "WARN: AtlasLogicFetchWorker has new order before finishing request\n" );
					}
					else
					{
						sharedSection->fetchHasNews = true;
						sharedSection->fetchIsWorking = false;
					}
					mutex.Unlock();
				}
			}
		}
		return 0;
	}
	/*****************************************************
	**
	**   AtlasImportWorker   ---   execQueryBundle
	**
	******************************************************/
	int execQueryBundle()
	{
		int ret = dao->executeQueryBundle( qb, false );
		if( ret != (int)qb.size())
		{
			mutex.Lock();
			sharedSection->errorCount++;
			sharedSection->errorMessage = dao->getLastErrorMessage();
			sharedSection->threadStatus = THREADSTATUS_ERROR;
			mutex.Unlock();
		}
		qb.clear();
		return ret;
	}
//==============================================================================
void* console::parse_thread::Entry() {
//   wxLogMessage(_T("Mouse is %s (%ld, %ld)"), where.c_str(), x, y);
//   wxLogMessage(_T("Mutex try to lock..."));
   while (wxMUTEX_NO_ERROR != Mutex.TryLock());
//   wxLogMessage(_T("Mutex locked!"));
   telllloc.first_column = telllloc.first_line = 1;
   telllloc.last_column  = telllloc.last_line  = 1;
   telllloc.filename = NULL;
   void* b = tell_scan_string( command.c_str() );
   tellparse();
   my_delete_yy_buffer( b );
   Mutex.Unlock();
//   wxLogMessage(_T("Mutex unlocked"));
   return NULL;
};
Beispiel #17
0
void HexEditorCtrl::ReadFromBuffer( uint64_t position, unsigned lenght, char *buffer, bool cursor_reset, bool paint ){
	static wxMutex MyBufferMutex;
	MyBufferMutex.Lock();
	page_offset = position;
	if( lenght != ByteCapacity() ){
		//last line could be NULL;
		}
	Clear( false, cursor_reset );
	wxString text_string;
// Optimized Code
	for( unsigned i=0 ; i<lenght ; i++ )
		text_string << text_ctrl->Filter(buffer[i]);

	//Painting Zebra Stripes, -1 means no stripe. 0 means start with normal, 1 means start with zebra
	*ZebraStriping=(ZebraEnable ? position/BytePerLine()%2 : -1);
	if(sector_size > 1){
		offset_ctrl->sector_size=sector_size;
		int draw_line=sector_size-(page_offset%sector_size);
		hex_ctrl->ThinSeperationLines.Clear();
		text_ctrl->ThinSeperationLines.Clear();
			do{
			hex_ctrl->ThinSeperationLines.Add( 2*draw_line );
			text_ctrl->ThinSeperationLines.Add( draw_line );
			draw_line += sector_size;
			}while (draw_line < lenght );
		}

	hex_ctrl->SetBinValue(buffer, lenght, false );
	text_ctrl->ChangeValue(text_string, false);
	offset_ctrl->SetValue( position, BytePerLine() );

	if( offset_scroll->GetThumbPosition() not_eq (page_offset / BytePerLine()) )
		offset_scroll->SetThumbPosition( page_offset / BytePerLine() );

	if( paint ){
		PaintSelection();
		}
//	sector_size=128;
//	if(sector_size > 1){
//		int draw_line=sector_size-(page_offset%sector_size);
//			do{
//			hex_ctrl->DrawSeperationLineAfterChar( 2*draw_line );
//			text_ctrl->DrawSeperationLineAfterChar( draw_line );
//			draw_line += sector_size;
//			}while (draw_line < GetByteCount() );
//		}
	MyBufferMutex.Unlock();
	}
Beispiel #18
0
////////////////////////////////////////////////////////////////////////////////
// This handler will display a popup menu for the item at the mouse position
////////////////////////////////////////////////////////////////////////////////
void frmMain::OnSelRightClick(wxTreeEvent &event)
{
	wxTreeItemId item = event.GetItem();
	if (item != browser->GetSelection())
	{
		browser->SelectItem(item);

		// Prevent changes to "currentObject" by "execSelchange" function by another
		// thread. Will hold the lock until we have the actual object in hand.
		s_currentObjectMutex.Lock();
		currentObject = browser->GetObject(item);
		s_currentObjectMutex.Unlock();
	}

	if (currentObject)
		doPopup(browser, event.GetPoint(), currentObject);
}
void wxSoundSyncOnlyAdaptor::Stop()
{
    wxLogTrace(_T("sound"), _T("asking audio to stop"));

#if wxUSE_THREADS
    // tell the player thread (if running) to stop playback ASAP:
    m_status.m_stopRequested = true;

    // acquire the mutex to be sure no sound is being played, then
    // release it because we don't need it for anything (the effect of this
    // is that calling thread will wait until playback thread reacts to
    // our request to interrupt playback):
    m_mutexRightToPlay.Lock();
    m_mutexRightToPlay.Unlock();
    wxLogTrace(_T("sound"), _T("audio was stopped"));
#endif
}
laydata::tdtdesign*  DataCenter::lockDB(bool checkACTcell) 
{
   if (_TEDDB) 
   {
      if (checkACTcell) _TEDDB->check_active();
      while (wxMUTEX_NO_ERROR != DBLock.TryLock());
      return _TEDDB;
   }
   else throw EXPTNactive_DB();
}
wxThread::ExitCode AegisubVersionCheckerThread::Entry()
{
	if (!interactive)
	{
		// Automatic checking enabled?
		if (!OPT_GET("App/Auto/Check For Updates")->GetBool())
			return 0;

		// Is it actually time for a check?
		time_t next_check = OPT_GET("Version/Next Check")->GetInt();
		if (next_check > wxDateTime::GetTimeNow())
			return 0;
	}

	if (VersionCheckLock.TryLock() != wxMUTEX_NO_ERROR) return 0;

	try {
		DoCheck();
	}
	catch (const agi::Exception &e) {
		PostErrorEvent(wxString::Format(
			_("There was an error checking for updates to Aegisub:\n%s\n\nIf other applications can access the Internet fine, this is probably a temporary server problem on our end."),
			e.GetMessage()));
	}
	catch (...) {
		PostErrorEvent(_("An unknown error occurred while checking for updates to Aegisub."));
	}

	VersionCheckLock.Unlock();

	// While Options isn't perfectly thread safe, this should still be okay.
	// Traversing the std::map to find the key-value pair doesn't modify any data as long as
	// the key already exists (which it does at this point), and modifying the value only
	// touches that specific key-value pair and will never cause a rebalancing of the tree,
	// because the tree only depends on the keys.
	// Lastly, writing options to disk only happens when Options.Save() is called.
	time_t new_next_check_time = wxDateTime::GetTimeNow() + 60*60; // in one hour
	OPT_SET("Version/Next Check")->SetInt((int)new_next_check_time);

	return 0;
}
Beispiel #22
0
void layprop::ViewProperties::addlayer(std::string name, word layno, std::string col,
                                                             std::string fill) {
   while (wxMUTEX_NO_ERROR != DBLock.TryLock());
   if ((col != "") && (_drawprop._laycolors.end() == _drawprop._laycolors.find(col))) {
      std::ostringstream ost;
      ost << "Warning! Color \""<<col<<"\" is not defined";
      tell_log(console::MT_WARNING,ost.str());
   }
   if ((fill != "") && (_drawprop._layfill.end() == _drawprop._layfill.find(fill))) {
      std::ostringstream ost;
      ost << "Warning! Fill \""<<fill<<"\" is not defined";
      tell_log(console::MT_WARNING, ost.str());
   }
   if (_drawprop._layset.end() != _drawprop._layset.find(layno)) {
      delete _drawprop._layset[layno];
      std::ostringstream ost;
      ost << "Warning! Layer "<<layno<<" redefined";
      tell_log(console::MT_WARNING, ost.str());
   }   
   _drawprop._layset[layno] = new LayerSettings(name,col,fill);
   DBLock.Unlock();
}
Beispiel #23
0
void* Thread_ChangedSince::Entry()
{

	wxString timeStamp = m_pKbSvr->GetKBServerLastSync();

	s_BulkDeleteMutex.Lock();

	int rv = m_pKbSvr->ChangedSince_Timed(timeStamp); // 2nd param, bDoTimestampUpdate is default TRUE

	s_BulkDeleteMutex.Unlock();

	// If rv = 0 (ie. no error) is returned, the server's downloaded timestamp will have
	// been used at the end of ChangedSince_Queued() to update the stored value at the
	// client end , so it doesn't need to be done here - but that's provided
	// bDoTimestampUpdate param takes the default TRUE value; if an explicit
	// FALSE were passed in, no timestamp update would be done
	if (rv != 0)
	{
		; // do nothing, error handling is at a lower level
	}
	return (void*)NULL;
}
GDSin::GDSFile* DataCenter::lockGDS(bool throwexception) 
{
   // Carefull HERE! When GDS is locked form the main thread
   // (GDS browser), then there is no catch pending -i.e.
   // throwing an exception will make the things worse
   // When it is locked from the parser command - then exception
   // is fine 
   if (_GDSDB) 
   {
      while (wxMUTEX_NO_ERROR != GDSLock.TryLock());
      return _GDSDB;
   }
   else {
      if (throwexception) throw EXPTNactive_GDS();
      else return NULL;
   }
}
void DataCenter::GDSparse(std::string filename, std::list<std::string>& topcells) 
{
   if (_GDSDB) 
   {
      std::string news = "Removing existing GDS data from memory...";
      tell_log(console::MT_WARNING,news);
      GDSclose();
   }
   while (wxMUTEX_NO_ERROR != GDSLock.TryLock());
   // parse the GDS file
   _GDSDB = new GDSin::GDSFile(filename.c_str());
   if (!_GDSDB->status()) return;
   // generate the hierarchy tree of cells
   _GDSDB->HierOut();
   // add GDS tab in the browser
   browsers::addGDStab();
   GDSin::GDSHierTree* root = _GDSDB->hierTree()->GetFirstRoot();
   do 
   {
      topcells.push_back(std::string(root->GetItem()->Get_StrName()));
   } while (NULL != (root = root->GetNextRoot()));
   unlockGDS();
}
Beispiel #26
0
void frmMain::execSelChange(wxTreeItemId item, bool currentNode)
{
	static bool refresh = true;

	if (currentNode)
	{
		ResetLists();
		sqlPane->Clear();
	}

	// Get the item data, and feed it to the relevant handler,
	// cast as required.
	//
	// Lock the assignment to prevent the race conditions between onSelRightClick and execSelChange.
	//
	s_currentObjectMutex.Lock();
	currentObject = browser->GetObject(item);
	s_currentObjectMutex.Unlock();

	// If we didn't get an object, then we may have a right click, or
	// invalid click, so ignore.
	if (!currentObject)
	{
		menuFactories->CheckMenu(currentObject, menuBar, toolBar);
	}
	else
	{
		int settingRefreshOnClick = settings->GetRefreshOnClick();

		if (settingRefreshOnClick != REFRESH_OBJECT_NONE
		        && refresh
		        && currentObject->GetTypeName() != wxT("Server")
		        && currentObject->GetTypeName() != wxT("Servers")
		        && currentObject->GetTypeName() != wxT("Database")
		        && !currentObject->IsCollection())
		{
			refresh = false;

			if (settingRefreshOnClick == REFRESH_OBJECT_ONLY )
			{
				// We can not update the schema, because it would cause an update to the entire tree.
				if (currentObject->GetTypeName() != wxT("Schema"))
				{
					wxTreeItemId currentItem = currentObject->GetId();

					// Do not refresh and instead bail out if dialog of the currently selected
					// node or it's child node is open, as refresh would delete this node's object
					// and could cause a crash
					pgObject *obj = NULL;
					if (currentItem)
						obj = browser->GetObject(currentItem);

					if (obj && obj->CheckOpenDialogs(browser, currentItem))
					{
						properties->Freeze();
						setDisplay(currentObject, properties, sqlPane);
						properties->Thaw();
						refresh = true;
						return;
					}

					pgObject *newData = currentObject->Refresh(browser, currentItem);

					if (newData != 0)
					{
						wxLogInfo(wxT("Replacing with new node %s %s for refresh"), newData->GetTypeName().c_str(), newData->GetQuotedFullIdentifier().c_str());

						browser->DeleteChildren(currentItem);
						newData->SetId(currentItem);    // not done automatically
						browser->SetItemData(currentItem, newData);

						// Update the node text if this is an object, as it may have been renamed
						if (!newData->IsCollection())
							browser->SetItemText(currentItem, newData->GetDisplayName());

						delete currentObject;
						currentObject = newData;
					}
					else
					{
						// OK, we failed to refresh, so select the parent and delete the child.
						browser->SelectItem(browser->GetItemParent(currentItem));
						browser->Delete(currentItem);
					}
				}
			}
			else
				Refresh(currentObject);

			refresh = true;
		}


		if (currentNode)
		{
			properties->Freeze();
			setDisplay(currentObject, properties, sqlPane);
			properties->Thaw();
		}
		else
			setDisplay(currentObject, 0, 0);
	}
}
Beispiel #27
0
 void unlock(){ m_QueueLock.Unlock(); }
//-----READ/WRITE FUNCTIONS-------//
void HexEditorCtrl::ReadFromBuffer( uint64_t position, unsigned lenght, char *buffer, bool cursor_reset, bool paint ){
	if( lenght==4294967295LL ){
		std::cout << "Buffer has no data!" << std::endl;
		return;
		}
	static wxMutex MyBufferMutex;
	MyBufferMutex.Lock();
	page_offset = position;
	if( lenght != ByteCapacity() ){
		//last line could be NULL;
		}
	Clear( false, cursor_reset );
	wxString text_string;

// Optimized Code
//	for( unsigned i=0 ; i<lenght ; i++ )
		//text_string << text_ctrl->Filter(buffer[i]);
//		text_string << static_cast<wxChar>((unsigned char)(buffer[i]));
//		text_string << CP473toUnicode((unsigned char)(buffer[i]));

	//Painting Zebra Stripes, -1 means no stripe. 0 means start with normal, 1 means start with zebra
	*ZebraStriping=(ZebraEnable ? position/BytePerLine()%2 : -1);
	if(sector_size > 1){
		offset_ctrl->sector_size=sector_size;
		unsigned draw_line=sector_size-(page_offset%sector_size);
		hex_ctrl->ThinSeparationLines.Clear();
		text_ctrl->ThinSeparationLines.Clear();
			do{
			hex_ctrl->ThinSeparationLines.Add( 2*draw_line );
			text_ctrl->ThinSeparationLines.Add( draw_line );
			draw_line += sector_size;
			}while (draw_line < lenght );
		}

	if(ProcessRAMMap.Count()){
		hex_ctrl->ThinSeparationLines.Clear();
		text_ctrl->ThinSeparationLines.Clear();
		//Notice that, ProcessRAMMap is SORTED.
		for( unsigned i=0; i < ProcessRAMMap.Count(); i++ ){
			int64_t M = ProcessRAMMap.Item(i);
			if( M > page_offset + ByteCapacity() )
				break;

			if(    (M > page_offset)
				&& (M <= page_offset + ByteCapacity()) ){

				int draw_line = M - page_offset;
				hex_ctrl->ThinSeparationLines.Add( 2*draw_line );
				text_ctrl->ThinSeparationLines.Add( draw_line );
				}
			}
		}

	hex_ctrl->SetBinValue(buffer, lenght, false );
	//text_ctrl->ChangeValue(text_string, false);
	text_ctrl->SetBinValue(buffer, lenght, false);

	offset_ctrl->SetValue( position, BytePerLine() );

	if( offset_scroll->GetThumbPosition() != (page_offset / BytePerLine()) )
		offset_scroll->SetThumbPosition( page_offset / BytePerLine() );

	if( paint ){
		PaintSelection();
		}

	MyBufferMutex.Unlock();
	}
void DataCenter::unlockDB() 
{
   DBLock.Unlock();
}
void DataCenter::unlockGDS() 
{
   GDSLock.Unlock();
}