1 // terrasync.cxx -- scenery fetcher
3 // Started by Curtis Olson, November 2002.
5 // Copyright (C) 2002 Curtis L. Olson - http://www.flightgear.org/~curt
6 // Copyright (C) 2008 Alexander R. Perry <alex.perry@ieee.org>
7 // Copyright (C) 2011 Thorsten Brehm <brehmt@gmail.com>
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include <simgear_config.h>
26 #include <simgear/compiler.h>
35 #elif defined(_MSC_VER)
41 #include <stdlib.h> // atoi() atof() abs() system()
42 #include <signal.h> // signal()
50 #include <simgear/version.h>
52 #include "terrasync.hxx"
54 #include <simgear/bucket/newbucket.hxx>
55 #include <simgear/misc/sg_path.hxx>
56 #include <simgear/misc/strutils.hxx>
57 #include <simgear/threads/SGQueue.hxx>
58 #include <simgear/misc/sg_dir.hxx>
59 #include <simgear/debug/BufferedLogCallback.hxx>
60 #include <simgear/props/props_io.hxx>
61 #include <simgear/io/HTTPClient.hxx>
62 #include <simgear/io/SVNRepository.hxx>
63 #include <simgear/io/HTTPRepository.hxx>
64 #include <simgear/structure/exception.hxx>
66 static const bool svn_built_in_available = true;
68 using namespace simgear;
71 const char* rsync_cmd =
72 "rsync --verbose --archive --delete --perms --owner --group";
74 const char* svn_options =
77 namespace UpdateInterval
79 // interval in seconds to allow an update to repeat after a successful update (=daily)
80 static const double SuccessfulAttempt = 24*60*60;
81 // interval in seconds to allow another update after a failed attempt (10 minutes)
82 static const double FailedAttempt = 10*60;
85 typedef map<string,time_t> TileAgeCache;
87 ///////////////////////////////////////////////////////////////////////////////
88 // helper functions ///////////////////////////////////////////////////////////
89 ///////////////////////////////////////////////////////////////////////////////
90 string stripPath(string path)
92 // svn doesn't like trailing white-spaces or path separators - strip them!
93 path = simgear::strutils::strip(path);
94 size_t slen = path.length();
96 ((path[slen-1]=='/')||(path[slen-1]=='\\')))
100 return path.substr(0,slen);
103 bool hasWhitespace(string path)
105 return path.find(' ')!=string::npos;
108 ///////////////////////////////////////////////////////////////////////////////
109 // SyncItem ////////////////////////////////////////////////////////////
110 ///////////////////////////////////////////////////////////////////////////////
116 Stop = 0, ///< special item indicating to stop the SVNThread
127 Cached, ///< using already cached result
140 SyncItem(string dir, Type ty) :
151 ///////////////////////////////////////////////////////////////////////////////
154 * @brief SyncSlot encapsulates a queue of sync items we will fetch
155 * serially. Multiple slots exist to sync different types of item in
162 isNewDirectory(false),
166 SyncItem currentItem;
168 std::queue<SyncItem> queue;
169 std::auto_ptr<AbstractRepository> repository;
171 bool busy; ///< is the slot working or idle
173 unsigned int nextWarnTimeout;
176 static const int SYNC_SLOT_TILES = 0; ///< Terrain and Objects sync
177 static const int SYNC_SLOT_SHARED_DATA = 1; /// shared Models and Airport data
178 static const int SYNC_SLOT_AI_DATA = 2; /// AI traffic and models
179 static const unsigned int NUM_SYNC_SLOTS = 3;
182 * @brief translate a sync item type into one of the available slots.
183 * This provides the scheduling / balancing / prioritising between slots.
185 static unsigned int syncSlotForType(SyncItem::Type ty)
188 case SyncItem::Tile: return SYNC_SLOT_TILES;
189 case SyncItem::SharedModels:
190 case SyncItem::AirportData:
191 return SYNC_SLOT_SHARED_DATA;
192 case SyncItem::AIData:
193 return SYNC_SLOT_AI_DATA;
196 return SYNC_SLOT_SHARED_DATA;
200 ///////////////////////////////////////////////////////////////////////////////
202 ///////////////////////////////////////////////////////////////////////////////
204 class ServerSelectQuery : public HTTP::Request
207 ServerSelectQuery() :
208 HTTP::Request("http://scenery.flightgear.org/svn-server", "GET")
212 std::string svnUrl() const
214 std::string s = simgear::strutils::strip(m_url);
215 if (s.at(s.length() - 1) == '/') {
216 s = s.substr(0, s.length() - 1);
222 virtual void gotBodyData(const char* s, int n)
224 m_url.append(std::string(s, n));
227 virtual void onFail()
229 SG_LOG(SG_TERRASYNC, SG_ALERT, "Failed to query TerraSync SVN server");
230 HTTP::Request::onFail();
238 ///////////////////////////////////////////////////////////////////////////////
239 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
240 ///////////////////////////////////////////////////////////////////////////////
241 class SGTerraSync::SvnThread : public SGThread
245 virtual ~SvnThread( ) { stop(); }
250 bool isIdle() {return !_busy; }
251 void request(const SyncItem& dir) {waitingTiles.push_front(dir);}
252 bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
253 bool hasNewTiles() { return !_freshTiles.empty();}
254 SyncItem getNewTile() { return _freshTiles.pop_front();}
256 void setSvnServer(string server) { _svn_server = stripPath(server);}
257 void setSvnDataServer(string server) { _svn_data_server = stripPath(server);}
258 void setHTTPServer(const std::string& server)
260 _httpServer = stripPath(server);
263 void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);}
264 void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);}
265 void setLocalDir(string dir) { _local_dir = stripPath(dir);}
266 string getLocalDir() { return _local_dir;}
267 void setUseSvn(bool use_svn) { _use_svn = use_svn;}
268 void setAllowedErrorCount(int errors) {_allowed_errors = errors;}
270 void setCachePath(const SGPath& p) {_persistentCachePath = p;}
271 void setCacheHits(unsigned int hits) {_cache_hits = hits;}
272 void setUseBuiltin(bool built_in) { _use_built_in = built_in;}
274 volatile bool _active;
275 volatile bool _running;
277 volatile bool _stalled;
278 volatile int _fail_count;
279 volatile int _updated_tile_count;
280 volatile int _success_count;
281 volatile int _consecutive_errors;
282 volatile int _allowed_errors;
283 volatile int _cache_hits;
284 volatile int _transfer_rate;
285 // kbytes, not bytes, because bytes might overflow 2^31
286 volatile int _total_kb_downloaded;
291 // external model run and helpers
293 void syncPathExternal(const SyncItem& next);
294 bool runExternalSyncCommand(const char* dir);
296 // internal mode run and helpers
298 void updateSyncSlot(SyncSlot& slot);
300 // commond helpers between both internal and external models
302 SyncItem::Status isPathCached(const SyncItem& next) const;
303 void initCompletedTilesPersistentCache();
304 void writeCompletedTilesPersistentCache() const;
305 void updated(SyncItem item, bool isNewDirectory);
306 void fail(SyncItem failedItem);
307 void notFound(SyncItem notFoundItem);
311 SyncSlot _syncSlots[NUM_SYNC_SLOTS];
313 volatile bool _is_dirty;
315 SGBlockingDeque <SyncItem> waitingTiles;
317 TileAgeCache _completedTiles;
318 TileAgeCache _notFoundItems;
320 SGBlockingDeque <SyncItem> _freshTiles;
323 string _svn_data_server;
325 string _rsync_server;
327 SGPath _persistentCachePath;
331 SGTerraSync::SvnThread::SvnThread() :
337 _updated_tile_count(0),
339 _consecutive_errors(0),
343 _total_kb_downloaded(0),
349 _http.setUserAgent("terrascenery-" SG_STRINGIZE(SIMGEAR_VERSION));
352 void SGTerraSync::SvnThread::stop()
354 // drop any pending requests
355 waitingTiles.clear();
360 // set stop flag and wake up the thread with an empty request
362 SyncItem w(string(), SyncItem::Stop);
368 bool SGTerraSync::SvnThread::start()
375 SG_LOG(SG_TERRASYNC,SG_ALERT,
376 "Cannot start scenery download. Local cache directory is undefined.");
382 SGPath path(_local_dir);
385 SG_LOG(SG_TERRASYNC,SG_ALERT,
386 "Cannot start scenery download. Directory '" << _local_dir <<
387 "' does not exist. Set correct directory path or create directory folder.");
393 path.append("version");
396 SG_LOG(SG_TERRASYNC,SG_ALERT,
397 "Cannot start scenery download. Directory '" << _local_dir <<
398 "' contains the base package. Use a separate directory.");
404 _use_svn |= _use_built_in;
407 if ((!_use_svn)&&(_rsync_server==""))
409 SG_LOG(SG_TERRASYNC,SG_ALERT,
410 "Cannot start scenery download. Rsync scenery server is undefined.");
417 _updated_tile_count = 0;
419 _consecutive_errors = 0;
426 if (_use_svn && _use_built_in)
427 status = "Using built-in SVN support. ";
430 status = "Using external SVN utility '";
431 status += _svn_command;
436 status = "Using RSYNC. ";
439 // not really an alert - but we want to (always) see this message, so user is
440 // aware we're downloading scenery (and using bandwidth).
441 SG_LOG(SG_TERRASYNC,SG_ALERT,
442 "Starting automatic scenery download/synchronization. "
444 << "Directory: '" << _local_dir << "'.");
450 bool SGTerraSync::SvnThread::runExternalSyncCommand(const char* dir)
453 SGPath localPath( _local_dir );
454 localPath.append( dir );
458 buf << "\"" << _svn_command << "\" "
459 << svn_options << " "
460 << "\"" << _svn_server << "/" << dir << "\" "
461 << "\"" << localPath.str_native() << "\"";
463 buf << rsync_cmd << " "
464 << "\"" << _rsync_server << "/" << dir << "/\" "
465 << "\"" << localPath.str_native() << "/\"";
470 // windows command line parsing is just lovely...
471 // to allow white spaces, the system call needs this:
472 // ""C:\Program Files\something.exe" somearg "some other arg""
473 // Note: whitespace strings quoted by a pair of "" _and_ the
474 // entire string needs to be wrapped by "" too.
475 // The svn url needs forward slashes (/) as a path separator while
476 // the local path needs windows-native backslash as a path separator.
477 command = "\"" + buf.str() + "\"";
481 SG_LOG(SG_TERRASYNC,SG_DEBUG, "sync command '" << command << "'");
484 // tbd: does Windows support "popen"?
485 int rc = system( command.c_str() );
487 FILE* pipe = popen( command.c_str(), "r");
489 // wait for external process to finish
496 SG_LOG(SG_TERRASYNC,SG_ALERT,
497 "Failed to synchronize directory '" << dir << "', " <<
498 "error code= " << rc);
504 void SGTerraSync::SvnThread::run()
507 initCompletedTilesPersistentCache();
510 if (_svn_server.empty()) {
511 SG_LOG(SG_TERRASYNC,SG_INFO, "Querying closest TerraSync server");
512 ServerSelectQuery* ssq = new ServerSelectQuery;
513 HTTP::Request_ptr req = ssq;
514 _http.makeRequest(req);
515 while (!req->isComplete()) {
519 if (req->readyState() == HTTP::Request::DONE) {
520 _svn_server = ssq->svnUrl();
521 SG_LOG(SG_TERRASYNC,SG_INFO, "Closest TerraSync server:" << _svn_server);
523 SG_LOG(SG_TERRASYNC,SG_WARN, "Failed to query closest TerraSync server");
526 SG_LOG(SG_TERRASYNC,SG_INFO, "Explicit: TerraSync server:" << _svn_server);
529 if (_svn_server.empty()) {
531 _svn_server = "http://foxtrot.mgras.net:8080/terrascenery/trunk/data/Scenery";
546 void SGTerraSync::SvnThread::runExternal()
550 SyncItem next = waitingTiles.pop_front();
554 SyncItem::Status cacheStatus = isPathCached(next);
555 if (cacheStatus != SyncItem::Invalid) {
557 SG_LOG(SG_TERRASYNC, SG_DEBUG,
558 "Cache hit for: '" << next._dir << "'");
559 next._status = cacheStatus;
560 _freshTiles.push_back(next);
565 syncPathExternal(next);
567 if ((_allowed_errors >= 0)&&
568 (_consecutive_errors >= _allowed_errors))
573 } // of thread running loop
576 void SGTerraSync::SvnThread::syncPathExternal(const SyncItem& next)
579 SGPath path( _local_dir );
580 path.append( next._dir );
581 bool isNewDirectory = !path.exists();
584 if (isNewDirectory) {
585 int rc = path.create_dir( 0755 );
587 SG_LOG(SG_TERRASYNC,SG_ALERT,
588 "Cannot create directory '" << path << "', return code = " << rc );
589 throw sg_exception("Cannot create directory for terrasync", path.str());
593 if (!runExternalSyncCommand(next._dir.c_str())) {
594 throw sg_exception("Running external sync command failed");
596 } catch (sg_exception& e) {
602 updated(next, isNewDirectory);
606 void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
608 if (slot.repository.get()) {
609 if (slot.repository->isDoingSync()) {
611 if (slot.stamp.elapsedMSec() > (int)slot.nextWarnTimeout) {
612 SG_LOG(SG_TERRASYNC, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec());
613 SG_LOG(SG_TERRASYNC, SG_INFO, "HTTP request count:" << _http.hasActiveRequests());
614 slot.nextWarnTimeout += 10000;
617 return; // easy, still working
621 SVNRepository::ResultCode res = slot.repository->failure();
622 if (res == AbstractRepository::REPO_ERROR_NOT_FOUND) {
623 notFound(slot.currentItem);
624 } else if (res != AbstractRepository::REPO_NO_ERROR) {
625 fail(slot.currentItem);
627 updated(slot.currentItem, slot.isNewDirectory);
628 SG_LOG(SG_TERRASYNC, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " finished ("
629 << slot.stamp.elapsedMSec() << " msec");
632 // whatever happened, we're done with this repository instance
634 slot.repository.reset();
637 // init and start sync of the next repository
638 if (!slot.queue.empty()) {
639 slot.currentItem = slot.queue.front();
642 SGPath path(_local_dir);
643 path.append(slot.currentItem._dir);
644 slot.isNewDirectory = !path.exists();
645 if (slot.isNewDirectory) {
646 int rc = path.create_dir( 0755 );
648 SG_LOG(SG_TERRASYNC,SG_ALERT,
649 "Cannot create directory '" << path << "', return code = " << rc );
650 fail(slot.currentItem);
653 } // of creating directory step
655 string serverUrl(_svn_server);
656 if (!_httpServer.empty()) {
657 slot.repository.reset(new HTTPRepository(path, &_http));
658 serverUrl = _httpServer;
660 if (slot.currentItem._type == SyncItem::AIData) {
661 serverUrl = _svn_data_server;
663 slot.repository.reset(new SVNRepository(path, &_http));
666 slot.repository->setBaseUrl(serverUrl + "/" + slot.currentItem._dir);
667 slot.repository->update();
669 slot.nextWarnTimeout = 20000;
672 SG_LOG(SG_TERRASYNC, SG_INFO, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size());
676 void SGTerraSync::SvnThread::runInternal()
680 _transfer_rate = _http.transferRateBytesPerSec();
681 // convert from bytes to kbytes
682 _total_kb_downloaded = static_cast<int>(_http.totalBytesDownloaded() / 1024);
687 // drain the waiting tiles queue into the sync slot queues.
688 while (!waitingTiles.empty()) {
689 SyncItem next = waitingTiles.pop_front();
690 SyncItem::Status cacheStatus = isPathCached(next);
691 if (cacheStatus != SyncItem::Invalid) {
693 SG_LOG(SG_TERRASYNC, SG_DEBUG, "\nTerraSync Cache hit for: '" << next._dir << "'");
694 next._status = cacheStatus;
695 _freshTiles.push_back(next);
700 unsigned int slot = syncSlotForType(next._type);
701 _syncSlots[slot].queue.push(next);
704 bool anySlotBusy = false;
705 // update each sync slot in turn
706 for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) {
707 updateSyncSlot(_syncSlots[slot]);
708 anySlotBusy |= _syncSlots[slot].busy;
713 // wait on the blocking deque here, otherwise we spin
714 // the loop very fast, since _http::update with no connections
715 // active returns immediately.
716 waitingTiles.waitOnNotEmpty();
718 } // of thread running loop
721 SyncItem::Status SGTerraSync::SvnThread::isPathCached(const SyncItem& next) const
723 TileAgeCache::const_iterator ii = _completedTiles.find( next._dir );
724 if (ii == _completedTiles.end()) {
725 ii = _notFoundItems.find( next._dir );
726 // Invalid means 'not cached', otherwise we want to return to
727 // higher levels the cache status
728 return (ii == _notFoundItems.end()) ? SyncItem::Invalid : SyncItem::NotFound;
731 // check if the path still physically exists. This is needed to
732 // cope with the user manipulating our cache dir
733 SGPath p(_local_dir);
736 return SyncItem::Invalid;
739 time_t now = time(0);
740 return (ii->second > now) ? SyncItem::Cached : SyncItem::Invalid;
743 void SGTerraSync::SvnThread::fail(SyncItem failedItem)
745 time_t now = time(0);
746 _consecutive_errors++;
748 failedItem._status = SyncItem::Failed;
749 _freshTiles.push_back(failedItem);
750 SG_LOG(SG_TERRASYNC,SG_INFO,
751 "Failed to sync'" << failedItem._dir << "'");
752 _completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt;
756 void SGTerraSync::SvnThread::notFound(SyncItem item)
758 // treat not found as authorative, so use the same cache expiry
759 // as succesful download. Important for MP models and similar so
760 // we don't spam the server with lookups for models that don't
763 time_t now = time(0);
764 item._status = SyncItem::NotFound;
765 _freshTiles.push_back(item);
767 _notFoundItems[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
768 writeCompletedTilesPersistentCache();
771 void SGTerraSync::SvnThread::updated(SyncItem item, bool isNewDirectory)
773 time_t now = time(0);
774 _consecutive_errors = 0;
776 SG_LOG(SG_TERRASYNC,SG_INFO,
777 "Successfully synchronized directory '" << item._dir << "'");
779 item._status = SyncItem::Updated;
780 if (item._type == SyncItem::Tile) {
781 _updated_tile_count++;
784 _freshTiles.push_back(item);
785 _completedTiles[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
787 writeCompletedTilesPersistentCache();
790 void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
792 if (!_persistentCachePath.exists()) {
796 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
797 time_t now = time(0);
800 readProperties(_persistentCachePath.str(), cacheRoot);
801 } catch (sg_exception& e) {
802 SG_LOG(SG_TERRASYNC, SG_INFO, "corrupted persistent cache, discarding");
806 for (int i=0; i<cacheRoot->nChildren(); ++i) {
807 SGPropertyNode* entry = cacheRoot->getChild(i);
808 bool isNotFound = (strcmp(entry->getName(), "not-found") == 0);
809 string tileName = entry->getStringValue("path");
810 time_t stamp = entry->getIntValue("stamp");
816 _completedTiles[tileName] = stamp;
818 _notFoundItems[tileName] = stamp;
823 void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
826 if (_persistentCachePath.isNull()) {
830 std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
835 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
836 TileAgeCache::const_iterator it = _completedTiles.begin();
837 for (; it != _completedTiles.end(); ++it) {
838 SGPropertyNode* entry = cacheRoot->addChild("entry");
839 entry->setStringValue("path", it->first);
840 entry->setIntValue("stamp", it->second);
843 it = _notFoundItems.begin();
844 for (; it != _notFoundItems.end(); ++it) {
845 SGPropertyNode* entry = cacheRoot->addChild("not-found");
846 entry->setStringValue("path", it->first);
847 entry->setIntValue("stamp", it->second);
850 writeProperties(f, cacheRoot, true /* write_all */);
854 ///////////////////////////////////////////////////////////////////////////////
855 // SGTerraSync ////////////////////////////////////////////////////////////////
856 ///////////////////////////////////////////////////////////////////////////////
857 SGTerraSync::SGTerraSync() :
862 _svnThread = new SvnThread();
863 _log = new BufferedLogCallback(SG_TERRASYNC, SG_INFO);
864 _log->truncateAt(255);
866 sglog().addCallback(_log);
869 SGTerraSync::~SGTerraSync()
873 sglog().removeCallback(_log);
875 _tiedProperties.Untie();
878 void SGTerraSync::setRoot(SGPropertyNode_ptr root)
880 _terraRoot = root->getNode("/sim/terrasync",true);
883 void SGTerraSync::init()
892 _terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available);
897 void SGTerraSync::shutdown()
902 void SGTerraSync::reinit()
904 // do not reinit when enabled and we're already up and running
905 if ((_terraRoot->getBoolValue("enabled",false))&&
906 (_svnThread->_active && _svnThread->_running))
913 if (_terraRoot->getBoolValue("enabled",false))
915 _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
916 _svnThread->setHTTPServer(_terraRoot->getStringValue("http-server",""));
917 _svnThread->setSvnDataServer(_terraRoot->getStringValue("svn-data-server",""));
918 _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
919 _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
920 _svnThread->setAllowedErrorCount(_terraRoot->getIntValue("max-errors",5));
921 _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
922 _svnThread->setCachePath(SGPath(_terraRoot->getStringValue("cache-path","")));
923 _svnThread->setCacheHits(_terraRoot->getIntValue("cache-hit", 0));
924 _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
925 _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
927 if (_svnThread->start())
929 syncAirportsModels();
933 _stalledNode->setBoolValue(_svnThread->_stalled);
936 void SGTerraSync::bind()
943 _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
944 _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
945 _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
946 _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
947 _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
948 _tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits );
949 _tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate );
951 // use kbytes here because propety doesn't support 64-bit and we might conceivably
952 // download more than 2G in a single session
953 _tiedProperties.Tie( _terraRoot->getNode("downloaded-kbytes", true), (int*) &_svnThread->_total_kb_downloaded );
955 _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
956 _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
957 _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
958 _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
959 _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
960 _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
961 _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
962 // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
963 _stalledNode = _terraRoot->getNode("stalled", true);
964 _stalledNode->setBoolValue(_svnThread->_stalled);
965 _stalledNode->setAttribute(SGPropertyNode::PRESERVE,true);
968 void SGTerraSync::unbind()
971 _tiedProperties.Untie();
976 _stalledNode.clear();
980 void SGTerraSync::update(double)
982 static SGBucket bucket;
983 if (_svnThread->isDirty())
985 if (!_svnThread->_active)
987 if (_svnThread->_stalled)
989 SG_LOG(SG_TERRASYNC,SG_ALERT,
990 "Automatic scenery download/synchronization stalled. Too many errors.");
994 // not really an alert - just always show this message
995 SG_LOG(SG_TERRASYNC,SG_ALERT,
996 "Automatic scenery download/synchronization has stopped.");
998 _stalledNode->setBoolValue(_svnThread->_stalled);
1001 while (_svnThread->hasNewTiles())
1003 SyncItem next = _svnThread->getNewTile();
1005 if ((next._type == SyncItem::Tile) || (next._type == SyncItem::AIData)) {
1006 _activeTileDirs.erase(next._dir);
1008 } // of freshly synced items
1012 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
1014 void SGTerraSync::syncAirportsModels()
1016 static const char* bounds = "MZAJKL"; // airport sync order: K-L, A-J, M-Z
1017 // note "request" method uses LIFO order, i.e. processes most recent request first
1018 for( unsigned i = 0; i < strlen(bounds)/2; i++ )
1020 for ( char synced_other = bounds[2*i]; synced_other <= bounds[2*i+1]; synced_other++ )
1023 dir << "Airports/" << synced_other;
1024 SyncItem w(dir.str(), SyncItem::AirportData);
1025 _svnThread->request( w );
1029 SyncItem w("Models", SyncItem::SharedModels);
1030 _svnThread->request( w );
1033 void SGTerraSync::syncAreaByPath(const std::string& aPath)
1035 const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 };
1036 for (const char** tree = &terrainobjects[0]; *tree; tree++)
1038 std::string dir = string(*tree) + aPath;
1039 if (_activeTileDirs.find(dir) != _activeTileDirs.end()) {
1043 _activeTileDirs.insert(dir);
1044 SyncItem w(dir, SyncItem::Tile);
1045 _svnThread->request( w );
1049 bool SGTerraSync::scheduleTile(const SGBucket& bucket)
1051 std::string basePath = bucket.gen_base_path();
1052 syncAreaByPath(basePath);
1056 bool SGTerraSync::isTileDirPending(const std::string& sceneryDir) const
1058 if (!_svnThread->_running) {
1062 const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 };
1063 for (const char** tree = &terrainobjects[0]; *tree; tree++) {
1064 string s = *tree + sceneryDir;
1065 if (_activeTileDirs.find(s) != _activeTileDirs.end()) {
1073 void SGTerraSync::scheduleDataDir(const std::string& dataDir)
1075 if (_activeTileDirs.find(dataDir) != _activeTileDirs.end()) {
1079 _activeTileDirs.insert(dataDir);
1080 SyncItem w(dataDir, SyncItem::AIData);
1081 _svnThread->request( w );
1085 bool SGTerraSync::isDataDirPending(const std::string& dataDir) const
1087 if (!_svnThread->_running) {
1091 return (_activeTileDirs.find(dataDir) != _activeTileDirs.end());
1094 void SGTerraSync::reposition()