reduce uses of MOBILEAPP on some files

Reduce the uses of MOBILEAPP conditionals by using the isMobileApp
function.

Signed-off-by: Jaume Pujantell <jaume.pujantell@collabora.com>
Change-Id: If541307fbc457b342674cc560b6c53454f3904cf
pull/8593/head
Jaume Pujantell 2024-03-17 23:11:02 +01:00 committed by JaumePujantell
parent 3ba713aabf
commit 8921e19d84
23 changed files with 268 additions and 324 deletions

View File

@ -500,11 +500,12 @@ namespace FileUtil
{
assert(!path.empty());
#if !MOBILEAPP
bool hookResult = true;
if (UnitBase::get().filterCheckDiskSpace(path, hookResult))
return hookResult;
#endif
if (!Util::isMobileApp())
{
bool hookResult = true;
if (UnitBase::get().filterCheckDiskSpace(path, hookResult))
return hookResult;
}
// we should be able to run just OK with 5GB for production or 1GB for development
#if defined(__linux__) || defined(__FreeBSD__) || defined(IOS)

View File

@ -529,10 +529,8 @@ namespace Log
Static.setName(name);
std::ostringstream oss;
oss << Static.getName();
#if !MOBILEAPP // Just one process in a mobile app, the pid is uninteresting.
oss << '-'
<< std::setw(5) << std::setfill('0') << getpid();
#endif
if (!Util::isMobileApp())
oss << '-' << std::setw(5) << std::setfill('0') << getpid();
Static.setId(oss.str());
// Configure the logger.
@ -599,7 +597,8 @@ namespace Log
void shutdown()
{
#if !MOBILEAPP
if (Util::isMobileApp())
return;
if (!Util::isKitInProcess())
assert(ThreadLocalBufferCount <= 1 &&
"Unstopped threads may have unflushed buffered log entries");
@ -611,7 +610,6 @@ namespace Log
// Flush
fflush(stdout);
fflush(stderr);
#endif
}
void setThreadLocalLogLevel(const std::string& logLevel)

View File

@ -48,14 +48,10 @@ namespace Log
void setThreadLocalLogLevel(const std::string& logLevel);
#if !MOBILEAPP
extern bool IsShutdown;
/// Was static shutdown() called? If so, producing more logs should be avoided.
inline bool isShutdownCalled() { return IsShutdown; }
#else
constexpr bool isShutdownCalled() { return false; }
#endif
inline bool isShutdownCalled() { return IsShutdown && !Util::isMobileApp(); }
/// Generates log entry prefix. Example follows (without the pipes).
/// |wsd-07272-07298 2020-04-25 17:29:28.928697 -0400 [ websrv_poll ] TRC |

View File

@ -182,15 +182,16 @@ inline bool impl_encodeSubBufferToPNG(unsigned char* pixmap, size_t startX, size
return false;
}
#if MOBILEAPP
png_set_compression_level(png_ptr, Z_BEST_SPEED);
#else
// Level 4 gives virtually identical compression
// ratio to level 6, but is between 5-10% faster.
// Level 3 runs almost twice as fast, but the
// output is typically 2-3x larger.
png_set_compression_level(png_ptr, 4);
#endif
if (Util::isMobileApp())
png_set_compression_level(png_ptr, Z_BEST_SPEED);
else
{
// Level 4 gives virtually identical compression
// ratio to level 6, but is between 5-10% faster.
// Level 3 runs almost twice as fast, but the
// output is typically 2-3x larger.
png_set_compression_level(png_ptr, 4);
}
png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

View File

@ -87,10 +87,11 @@ void setTerminationFlag()
// Set the forced-termination flag.
RunStateFlag = RunState::Terminate;
#if !MOBILEAPP
if (!Util::isMobileApp())
{
// And wake-up the thread.
SocketPoll::wakeupWorld();
#endif
}
}
void requestShutdown()

View File

@ -57,7 +57,8 @@ bool EnableExperimental = false;
UnitBase** UnitBase::linkAndCreateUnit([[maybe_unused]] UnitType type,
[[maybe_unused]] const std::string& unitLibPath)
{
#if !MOBILEAPP
if (Util::isMobileApp())
return nullptr;
DlHandle = dlopen(unitLibPath.c_str(), RTLD_GLOBAL|RTLD_NOW);
if (!DlHandle)
{
@ -125,7 +126,6 @@ UnitBase** UnitBase::linkAndCreateUnit([[maybe_unused]] UnitType type,
return new UnitBase* [2] { hooks, nullptr };
LOG_ERR("No wsd unit-tests found in " << unitLibPath);
#endif
return nullptr;
}
@ -205,13 +205,14 @@ void UnitBase::selfTest()
bool UnitBase::init(UnitType type, const std::string &unitLibPath)
{
#if !MOBILEAPP
LOG_ASSERT(!get(type));
#else
// The COOLWSD initialization is called in a loop on mobile, allow reuse
if (get(type))
return true;
#endif
if (!Util::isMobileApp())
LOG_ASSERT(!get(type));
else
{
// The COOLWSD initialization is called in a loop on mobile, allow reuse
if (get(type))
return true;
}
LOG_ASSERT(GlobalArray == nullptr);
LOG_ASSERT(GlobalIndex == -1);
@ -660,12 +661,13 @@ void UnitWSD::onExitTest(TestResult result, const std::string&)
if (result != TestResult::Ok && !GlobalTestOptions.getKeepgoing())
{
LOG_TST("Failing fast per options, even though there are more tests");
#if !MOBILEAPP
LOG_TST("Setting TerminationFlag as the Test Suite failed");
SigUtil::setTerminationFlag(); // and wake-up world.
#else
SocketPoll::wakeupWorld();
#endif
if (!Util::isMobileApp())
{
LOG_TST("Setting TerminationFlag as the Test Suite failed");
SigUtil::setTerminationFlag(); // and wake-up world.
}
else
SocketPoll::wakeupWorld();
return;
}
@ -678,12 +680,13 @@ void UnitWSD::onExitTest(TestResult result, const std::string&)
<< " was the last test. Finishing "
<< (GlobalResult == TestResult::Ok ? "SUCCESS" : "FAILED"));
#if !MOBILEAPP
LOG_TST("Setting TerminationFlag as there are no more tests");
SigUtil::setTerminationFlag(); // and wake-up world.
#else
SocketPoll::wakeupWorld();
#endif
if (!Util::isMobileApp())
{
LOG_TST("Setting TerminationFlag as there are no more tests");
SigUtil::setTerminationFlag(); // and wake-up world.
}
else
SocketPoll::wakeupWorld();
}
UnitKit::UnitKit(const std::string& name)
@ -695,10 +698,6 @@ UnitKit::~UnitKit() {}
UnitKit& UnitKit::get()
{
#if MOBILEAPP
if (!GlobalKit)
GlobalKit = new UnitKit("UnitKit");
#endif
if (Util::isKitInProcess() && !GlobalKit)
GlobalKit = new UnitKit("UnitKit");
@ -716,12 +715,13 @@ void UnitKit::onExitTest(TestResult, const std::string&)
// << " was the last test. Finishing "
// << (GlobalResult == TestResult::Ok ? "SUCCESS" : "FAILED"));
#if !MOBILEAPP
// LOG_TST("Setting TerminationFlag as there are no more tests");
SigUtil::setTerminationFlag(); // and wake-up world.
#else
SocketPoll::wakeupWorld();
#endif
if (!Util::isMobileApp())
{
// LOG_TST("Setting TerminationFlag as there are no more tests");
SigUtil::setTerminationFlag(); // and wake-up world.
}
else
SocketPoll::wakeupWorld();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

View File

@ -213,7 +213,7 @@ namespace Util
bool kitInProcess = false;
void setKitInProcess(bool value) { kitInProcess = value; }
bool isKitInProcess() { return kitInProcess || isFuzzing(); }
bool isKitInProcess() { return kitInProcess || isFuzzing() || isMobileApp(); }
std::string replace(std::string result, const std::string& a, const std::string& b)
{

View File

@ -677,8 +677,6 @@ bool ChildSession::_handleInput(const char *buffer, int length)
return true;
}
#if !MOBILEAPP
std::string getMimeFromFileType(const std::string & fileType)
{
if (fileType == "pdf")
@ -717,8 +715,6 @@ namespace {
}
}
#endif
bool ChildSession::loadDocument(const StringVector& tokens)
{
int part = -1;
@ -794,11 +790,8 @@ bool ChildSession::loadDocument(const StringVector& tokens)
return false;
}
#if !MOBILEAPP
renameForUpload(url);
#endif //!MOBILEAPP
if (!Util::isMobileApp())
renameForUpload(url);
}
getLOKitDocument()->setView(_viewId);
@ -1110,9 +1103,8 @@ bool ChildSession::downloadAs(const StringVector& tokens)
jailDoc = jailDoc.substr(0, jailDoc.find(JAILED_DOCUMENT_ROOT)) + JAILED_DOCUMENT_ROOT;
}
#if !MOBILEAPP
consistencyCheckJail();
#endif
if (!Util::isMobileApp())
consistencyCheckJail();
// The file is removed upon downloading.
const std::string tmpDir = FileUtil::createRandomDir(jailDoc);
@ -1389,27 +1381,26 @@ bool ChildSession::paste(const char* buffer, int length, const StringVector& tok
bool ChildSession::insertFile(const StringVector& tokens)
{
std::string name, type;
std::string name, type, data;
#if !MOBILEAPP
if (tokens.size() != 3 ||
!getTokenString(tokens[1], "name", name) ||
!getTokenString(tokens[2], "type", type))
if (!Util::isMobileApp())
{
sendTextFrameAndLogError("error: cmd=insertfile kind=syntax");
return false;
if (tokens.size() != 3 || !getTokenString(tokens[1], "name", name) ||
!getTokenString(tokens[2], "type", type))
{
sendTextFrameAndLogError("error: cmd=insertfile kind=syntax");
return false;
}
}
#else
std::string data;
if (tokens.size() != 4 ||
!getTokenString(tokens[1], "name", name) ||
!getTokenString(tokens[2], "type", type) ||
!getTokenString(tokens[3], "data", data))
else
{
sendTextFrameAndLogError("error: cmd=insertfile kind=syntax");
return false;
if (tokens.size() != 4 || !getTokenString(tokens[1], "name", name) ||
!getTokenString(tokens[2], "type", type) || !getTokenString(tokens[3], "data", data))
{
sendTextFrameAndLogError("error: cmd=insertfile kind=syntax");
return false;
}
}
#endif
SigUtil::addActivity(getId(), "insertFile " + type);
@ -1417,37 +1408,41 @@ bool ChildSession::insertFile(const StringVector& tokens)
{
std::string url;
#if !MOBILEAPP
if (type == "graphic" || type == "selectbackground")
if (!Util::isMobileApp())
{
std::string jailDoc = JAILED_DOCUMENT_ROOT;
if (NoCapsForKit)
if (type == "graphic" || type == "selectbackground")
{
jailDoc = Poco::URI(getJailedFilePath()).getPath();
jailDoc = jailDoc.substr(0, jailDoc.find(JAILED_DOCUMENT_ROOT)) + JAILED_DOCUMENT_ROOT;
std::string jailDoc = JAILED_DOCUMENT_ROOT;
if (NoCapsForKit)
{
jailDoc = Poco::URI(getJailedFilePath()).getPath();
jailDoc = jailDoc.substr(0, jailDoc.find(JAILED_DOCUMENT_ROOT)) +
JAILED_DOCUMENT_ROOT;
}
url = "file://" + jailDoc + "insertfile/" + name;
}
url = "file://" + jailDoc + "insertfile/" + name;
}
else if (type == "graphicurl")
{
URI::decode(name, url);
if (!Util::toLower(url).starts_with("http"))
else if (type == "graphicurl")
{
// Do not allow arbitrary schemes, especially "file://".
sendTextFrameAndLogError("error: cmd=insertfile kind=syntax");
return false;
URI::decode(name, url);
if (!Util::toLower(url).starts_with("http"))
{
// Do not allow arbitrary schemes, especially "file://".
sendTextFrameAndLogError("error: cmd=insertfile kind=syntax");
return false;
}
}
}
#else
assert(type == "graphic");
auto binaryData = decodeBase64(data);
const std::string tempFile = FileUtil::createRandomTmpDir() + '/' + name;
std::ofstream fileStream;
fileStream.open(tempFile);
fileStream.write(reinterpret_cast<char*>(binaryData.data()), binaryData.size());
fileStream.close();
url = "file://" + tempFile;
#endif
else
{
assert(type == "graphic");
auto binaryData = decodeBase64(data);
const std::string tempFile = FileUtil::createRandomTmpDir() + '/' + name;
std::ofstream fileStream;
fileStream.open(tempFile);
fileStream.write(reinterpret_cast<char*>(binaryData.data()), binaryData.size());
fileStream.close();
url = "file://" + tempFile;
}
const std::string command = (type == "selectbackground" ? ".uno:SelectBackground" : ".uno:InsertGraphic");
const std::string arguments = "{"
@ -2331,9 +2326,8 @@ bool ChildSession::saveAs(const StringVector& tokens)
// url is already encoded
encodedURL = url;
#if !MOBILEAPP
consistencyCheckJail();
#endif
if (!Util::isMobileApp())
consistencyCheckJail();
std::string encodedWopiFilename;
Poco::URI::encode(wopiFilename, "", encodedWopiFilename);
@ -2756,10 +2750,9 @@ void ChildSession::loKitCallback(const int type, const std::string& payload)
LOG_TRC("ChildSession::loKitCallback [" << getName() << "]: " << typeName << " [" << payload
<< ']');
#if !MOBILEAPP
if (UnitKit::get().filterLoKitCallback(type, payload))
if (!Util::isMobileApp() && UnitKit::get().filterLoKitCallback(type, payload))
return;
#endif
if (isCloseFrame())
{
LOG_TRC("Skipping callback [" << typeName << "] on closing session " << getName());
@ -2910,32 +2903,39 @@ void ChildSession::loKitCallback(const int type, const std::string& payload)
if (!commandName.isEmpty() && commandName.toString() == ".uno:Save")
{
#if !MOBILEAPP
consistencyCheckJail();
renameForUpload(getJailedFilePath());
#else // MOBILEAPP
// After the document has been saved (into the temporary copy that we set up in
// -[CODocument loadFromContents:ofType:error:]), save it also using the system API so
// that file provider extensions notice.
if (!success.isEmpty() && success.toString() == "true")
if (!Util::isMobileApp())
{
#if defined(IOS)
CODocument *document = DocumentData::get(_docManager->getMobileAppDocId()).coDocument;
[document saveToURL:[document fileURL]
forSaveOperation:UIDocumentSaveForOverwriting
completionHandler:^(BOOL success) {
LOG_TRC("ChildSession::loKitCallback() save completion handler gets " << (success?"YES":"NO"));
if (![[NSFileManager defaultManager] removeItemAtURL:document->copyFileURL error:nil]) {
LOG_SYS("Could not remove copy of document at " << [[document->copyFileURL path] UTF8String]);
}
}];
#elif defined(__ANDROID__)
postDirectMessage("SAVE " + payload);
#endif
consistencyCheckJail();
renameForUpload(getJailedFilePath());
}
else
{
// After the document has been saved (into the temporary copy that we set up in
// -[CODocument loadFromContents:ofType:error:]), save it also using the system API so
// that file provider extensions notice.
if (!success.isEmpty() && success.toString() == "true")
{
#if defined(IOS)
CODocument* document =
DocumentData::get(_docManager->getMobileAppDocId()).coDocument;
[document saveToURL:[document fileURL]
forSaveOperation:UIDocumentSaveForOverwriting
completionHandler:^(BOOL success) {
LOG_TRC("ChildSession::loKitCallback() save completion handler gets "
<< (success ? "YES" : "NO"));
if (![[NSFileManager defaultManager] removeItemAtURL:document->copyFileURL
error:nil])
{
LOG_SYS("Could not remove copy of document at "
<< [[document->copyFileURL path] UTF8String]);
}
}];
#elif defined(__ANDROID__)
postDirectMessage("SAVE " + payload);
#endif
}
}
}
sendTextFrame("unocommandresult: " + payload);
@ -3095,7 +3095,7 @@ void ChildSession::loKitCallback(const int type, const std::string& payload)
sendTextFrame("printranges: " + payload);
break;
case LOK_CALLBACK_FONTS_MISSING:
#if !MOBILEAPP
if (!Util::isMobileApp())
{
// This environment variable is always set in COOLWSD::innerInitialize().
static std::string fontsMissingHandling = std::string(std::getenv("FONTS_MISSING_HANDLING"));
@ -3116,7 +3116,6 @@ void ChildSession::loKitCallback(const int type, const std::string& payload)
#endif
}
}
#endif
break;
case LOK_CALLBACK_EXPORT_FILE:
{

View File

@ -119,10 +119,9 @@ protected:
{
std::string message(data.data(), data.size());
#if !MOBILEAPP
if (UnitKit::get().filterKitMessage(this, message))
if (!Util::isMobileApp() && UnitKit::get().filterKitMessage(this, message))
return;
#endif
StringVector tokens = StringVector::tokenize(message);
LOG_DBG(_socketName << ": recv [" <<
@ -187,10 +186,10 @@ protected:
void onDisconnect() override
{
#if !MOBILEAPP
if (Util::isMobileApp())
return;
LOG_ERR("ForKit connection lost without exit arriving from wsd. Setting TerminationFlag");
SigUtil::setTerminationFlag();
#endif
}
};
@ -749,7 +748,6 @@ int forkit_main(int argc, char** argv)
// Make dev/[u]random point to the writable devices in tmp/dev/.
JailUtil::SysTemplate::setupRandomDeviceLinks(sysTemplate);
#if !MOBILEAPP
if (!Util::isKitInProcess())
{
// Parse the configuration.
@ -757,7 +755,6 @@ int forkit_main(int argc, char** argv)
config::initialize(std::string(conf ? conf : std::string()));
EnableExperimental = config::getBool("experimental_features", false);
}
#endif
Util::setThreadName("forkit");
@ -786,13 +783,12 @@ int forkit_main(int argc, char** argv)
WSHandler = std::make_shared<ServerWSHandler>("forkit_ws");
#if !MOBILEAPP
if (!ForKitPoll->insertNewUnixSocket(MasterLocation, FORKIT_URI, WSHandler))
if (!Util::isMobileApp() &&
!ForKitPoll->insertNewUnixSocket(MasterLocation, FORKIT_URI, WSHandler))
{
LOG_SFL("Failed to connect to WSD. Will exit.");
Util::forcedExit(EX_SOFTWARE);
}
#endif
SigUtil::setUserSignals();

View File

@ -170,8 +170,6 @@ static int URPfromLoFDs[2] { -1, -1 };
// socket buffer & event processing in a single, thread.
bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char *p, void *data);
#if !MOBILEAPP
static LokHookFunction2* initFunction = nullptr;
namespace
@ -206,7 +204,7 @@ namespace
consistencyCheckJail();
}
#ifndef BUILDING_TESTS
#if !defined(BUILDING_TESTS) && !MOBILEAPP
enum class LinkOrCopyType
{
All,
@ -685,8 +683,6 @@ namespace
#endif // BUILDING_TESTS
} // namespace
#endif // !MOBILEAPP
Document::Document(const std::shared_ptr<lok::Office>& loKit,
const std::string& jailId,
const std::string& docKey,
@ -830,13 +826,11 @@ std::size_t Document::purgeSessions()
}
num_sessions = _sessions.size();
#if !MOBILEAPP
if (num_sessions == 0)
if (!Util::isMobileApp() && num_sessions == 0)
{
LOG_FTL("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
flushAndExit(EX_OK);
}
#endif
}
if (deadSessions.size() > 0 )
@ -1244,13 +1238,11 @@ void Document::onUnload(const ChildSession& session)
int viewCount = _loKitDocument->getViewsCount();
if (viewCount == 1)
{
#if !MOBILEAPP
if (_sessions.empty())
if (!Util::isMobileApp() && _sessions.empty())
{
LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
flushAndExit(EX_OK);
}
#endif
LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, but has " <<
_sessions.size() << " sessions still. Destroying the document.");
#ifdef __ANDROID__
@ -1538,9 +1530,8 @@ std::shared_ptr<lok::Document> Document::load(const std::shared_ptr<ChildSession
const bool accessibilityState = session->getAccessibilityState();
const std::string& userTimezone = session->getTimezone();
#if !MOBILEAPP
consistencyCheckFileExists(uri);
#endif
if (!Util::isMobileApp())
consistencyCheckFileExists(uri);
std::string options;
if (!lang.empty())
@ -2013,16 +2004,14 @@ void Document::drainQueue()
catch (const std::exception& exc)
{
LOG_FTL("drainQueue: Exception: " << exc.what());
#if !MOBILEAPP
flushAndExit(EX_SOFTWARE);
#endif
if (!Util::isMobileApp())
flushAndExit(EX_SOFTWARE);
}
catch (...)
{
LOG_FTL("drainQueue: Unknown exception");
#if !MOBILEAPP
flushAndExit(EX_SOFTWARE);
#endif
if (!Util::isMobileApp())
flushAndExit(EX_SOFTWARE);
}
}
@ -2038,7 +2027,6 @@ std::shared_ptr<lok::Document> Document::getLOKitDocument()
return _loKitDocument;
}
#if !MOBILEAPP
/// Stops theads, flushes buffers, and exits the process.
void Document::flushAndExit(int code)
{
@ -2049,7 +2037,6 @@ void Document::flushAndExit(int code)
else
SigUtil::setTerminationFlag();
}
#endif
void Document::dumpState(std::ostream& oss)
{
@ -2203,7 +2190,7 @@ void TraceEvent::emitOneRecording(const std::string &recording)
addRecording(recording, false);
}
#elif !MOBILEAPP
#else
void flushTraceEventRecordings()
{
@ -2362,16 +2349,17 @@ int KitSocketPoll::kitPoll(int timeoutMicroS)
if (_document)
_document->trimAfterInactivity();
#if !MOBILEAPP
flushTraceEventRecordings();
if (_document && _document->purgeSessions() == 0)
if (!Util::isMobileApp())
{
LOG_INF("Last session discarded. Setting TerminationFlag");
SigUtil::setTerminationFlag();
return -1;
flushTraceEventRecordings();
if (_document && _document->purgeSessions() == 0)
{
LOG_INF("Last session discarded. Setting TerminationFlag");
SigUtil::setTerminationFlag();
return -1;
}
}
#endif
// Report the number of events we processed.
return eventsSignalled;
}
@ -3051,8 +3039,6 @@ void runKitLoopInAThread()
#endif // !BUILDING_TESTS
#if !MOBILEAPP
void consistencyCheckJail()
{
static bool warned = false;
@ -3086,8 +3072,6 @@ void consistencyCheckJail()
}
}
#endif // !MOBILEAPP
/// Fetch the latest montonically incrementing wire-id
TileWireId getCurrentWireId(bool increment)
{

View File

@ -374,10 +374,8 @@ private:
std::string getObfuscatedFileId() override { return _obfuscatedFileId; }
#if !MOBILEAPP
/// Stops theads, flushes buffers, and exits the process.
void flushAndExit(int code);
#endif
private:
std::shared_ptr<lok::Office> _loKit;

View File

@ -35,10 +35,9 @@ void KitWebSocketHandler::handleMessage(const std::vector<char>& data)
std::string message(data.data(), data.size());
#if !MOBILEAPP
if (UnitKit::get().filterKitMessage(this, message))
if (!Util::isMobileApp() && UnitKit::get().filterKitMessage(this, message))
return;
#endif
StringVector tokens = StringVector::tokenize(message);
LOG_DBG(_socketName << ": recv [" << [&](auto& log) {
@ -96,26 +95,29 @@ void KitWebSocketHandler::handleMessage(const std::vector<char>& data)
else if (tokens.equals(0, "exit"))
{
#if !MOBILEAPP
LOG_INF("Terminating immediately due to parent 'exit' command.");
flushTraceEventRecordings();
_document.reset();
if (!Util::isKitInProcess())
Util::forcedExit(EX_OK);
if (!Util::isMobileApp())
{
LOG_INF("Terminating immediately due to parent 'exit' command.");
flushTraceEventRecordings();
_document.reset();
if (!Util::isKitInProcess())
Util::forcedExit(EX_OK);
else
SigUtil::setTerminationFlag();
}
else
SigUtil::setTerminationFlag();
#else
{
#ifdef IOS
LOG_INF("Setting our KitSocketPoll's termination flag due to 'exit' command.");
std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex);
_ksPoll->terminationFlag = true;
_ksPoll->terminationCV.notify_all();
LOG_INF("Setting our KitSocketPoll's termination flag due to 'exit' command.");
std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex);
_ksPoll->terminationFlag = true;
_ksPoll->terminationCV.notify_all();
#else
LOG_INF("Setting TerminationFlag due to 'exit' command.");
SigUtil::setTerminationFlag();
#endif
_document.reset();
LOG_INF("Setting TerminationFlag due to 'exit' command.");
SigUtil::setTerminationFlag();
#endif
_document.reset();
}
}
else if (tokens.equals(0, "tile") || tokens.equals(0, "tilecombine") ||
tokens.equals(0, "paintwindow") || tokens.equals(0, "resizewindow") ||
@ -163,13 +165,14 @@ void KitWebSocketHandler::enableProcessInput(bool enable)
void KitWebSocketHandler::onDisconnect()
{
#if !MOBILEAPP
//FIXME: We could try to recover.
LOG_ERR("Kit for DocBroker ["
<< _docKey
<< "] connection lost without exit arriving from wsd. Setting TerminationFlag");
SigUtil::setTerminationFlag();
#endif
if (!Util::isMobileApp())
{
//FIXME: We could try to recover.
LOG_ERR("Kit for DocBroker ["
<< _docKey
<< "] connection lost without exit arriving from wsd. Setting TerminationFlag");
SigUtil::setTerminationFlag();
}
#ifdef IOS
{
std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex);

View File

@ -39,10 +39,11 @@ inline void setupKitEnvironment(const std::string& userInterface)
::setenv("CONFIGURATION_LAYERS", layers.c_str(),
1 /* override */);
#if !MOBILEAPP
// No-caps tracing can spawn eg. glxinfo & other oddness.
unsetenv("DISPLAY");
#endif
if (!Util::isMobileApp())
{
// No-caps tracing can spawn eg. glxinfo & other oddness.
unsetenv("DISPLAY");
}
// Set various options we need.
std::string options = "unipoll";

View File

@ -307,13 +307,9 @@ int64_t Request::readData(const char* p, const int64_t len)
if (_stage == Stage::Header)
{
// First line is the status line.
#if !MOBILEAPP
if (p == nullptr || len < MinRequestHeaderLen)
#else
// Fix infinite loop on mobile by skipping the minimum request header
// length check
if (p == nullptr)
#endif
if (p == nullptr || (len < MinRequestHeaderLen && !Util::isMobileApp()))
{
LOG_TRC("Request::readData: len < MinRequestHeaderLen");
return 0;

View File

@ -265,14 +265,7 @@ public:
#endif
/// Gets our fast cache of the socket buffer size
int getSendBufferSize() const
{
#if !MOBILEAPP
return _sendBufferSize;
#else
return INT_MAX; // We want to always send a single record in one go
#endif
}
int getSendBufferSize() const { return (Util::isMobileApp() ? INT_MAX : _sendBufferSize); }
#if !MOBILEAPP
/// Sets the receive buffer size in bytes.
@ -617,7 +610,7 @@ public:
{
LOG_DBG("Stopping SocketPoll thread " << _name);
_stop = true;
#if MOBILEAPP
if (!Util::isMobileApp())
{
// We don't want to risk some callbacks in _newCallbacks being invoked when we start
// running a thread for this SocketPoll again.
@ -628,7 +621,6 @@ public:
_newCallbacks.clear();
}
}
#endif
wakeup();
}
@ -1289,12 +1281,10 @@ public:
/// buffer for an optimal transmission.
int getSendBufferCapacity() const
{
#if !MOBILEAPP
if (Util::isMobileApp())
return INT_MAX; // We want to always send a single record in one go
const int capacity = getSendBufferSize();
return std::max<int>(0, capacity - _outBuffer.size());
#else
return INT_MAX; // We want to always send a single record in one go
#endif
}
protected:

View File

@ -204,16 +204,17 @@ protected:
<< ", message: " << statusMessage);
_shuttingDown = true;
#if !MOBILEAPP
const size_t len = statusMessage.size();
std::vector<char> buf(2 + len);
buf[0] = ((((int)statusCode) >> 8) & 0xff);
buf[1] = ((((int)statusCode) >> 0) & 0xff);
std::copy(statusMessage.begin(), statusMessage.end(), buf.begin() + 2);
const unsigned char flags = WSFrameMask::Fin | static_cast<char>(WSOpCode::Close);
if (!Util::isMobileApp())
{
const size_t len = statusMessage.size();
std::vector<char> buf(2 + len);
buf[0] = ((((int)statusCode) >> 8) & 0xff);
buf[1] = ((((int)statusCode) >> 0) & 0xff);
std::copy(statusMessage.begin(), statusMessage.end(), buf.begin() + 2);
const unsigned char flags = WSFrameMask::Fin | static_cast<char>(WSOpCode::Close);
sendFrame(socket, buf.data(), buf.size(), flags);
#endif
sendFrame(socket, buf.data(), buf.size(), flags);
}
}
}
@ -517,11 +518,12 @@ protected:
{
std::shared_ptr<StreamSocket> socket = _socket.lock();
#if MOBILEAPP
// No separate "upgrade" is going on
if (socket && !socket->isWebSocket())
socket->setWebSocket();
#endif
if (Util::isMobileApp())
{
// No separate "upgrade" is going on
if (socket && !socket->isWebSocket())
socket->setWebSocket();
}
if (!socket)
{

View File

@ -376,11 +376,12 @@ void COOLWSD::appendAllowedAliasGroups(LayeredConfiguration& conf, std::vector<s
}
}
#if !MOBILEAPP
/// Internal implementation to alert all clients
/// connected to any document.
void COOLWSD::alertAllUsersInternal(const std::string& msg)
{
if (Util::isMobileApp())
return;
std::lock_guard<std::mutex> docBrokersLock(DocBrokersMutex);
LOG_INF("Alerting all users: [" << msg << ']');
@ -397,6 +398,8 @@ void COOLWSD::alertAllUsersInternal(const std::string& msg)
void COOLWSD::alertUserInternal(const std::string& dockey, const std::string& msg)
{
if (Util::isMobileApp())
return;
std::lock_guard<std::mutex> docBrokersLock(DocBrokersMutex);
LOG_INF("Alerting document users with dockey: [" << dockey << ']' << " msg: [" << msg << ']');
@ -408,7 +411,6 @@ void COOLWSD::alertUserInternal(const std::string& dockey, const std::string& ms
docBroker->addCallback([msg, docBroker](){ docBroker->alertAllUsers(msg); });
}
}
#endif
void COOLWSD::writeTraceEventRecording(const char *data, std::size_t nbytes)
{
@ -1954,12 +1956,10 @@ private:
void COOLWSD::innerInitialize(Application& self)
{
#if !MOBILEAPP
if (geteuid() == 0 && CheckCoolUser)
if (!Util::isMobileApp() && geteuid() == 0 && CheckCoolUser)
{
throw std::runtime_error("Do not run as root. Please run as cool user.");
}
#endif
Util::setApplicationPath(Poco::Path(Application::instance().commandPath()).parent().toString());
@ -2979,7 +2979,8 @@ void COOLWSD::dumpOutgoingTrace(const std::string& id, const std::string& sessio
void COOLWSD::defineOptions(OptionSet& optionSet)
{
#if !MOBILEAPP
if (Util::isMobileApp())
return;
ServerApplication::defineOptions(optionSet);
optionSet.addOption(Option("help", "", "Display help information on command line arguments.")
@ -3069,10 +3070,6 @@ void COOLWSD::defineOptions(OptionSet& optionSet)
.required(false)
.repeatable(false));
#endif
#else
(void) optionSet;
#endif
}
void COOLWSD::handleOption(const std::string& optionName,
@ -3697,9 +3694,8 @@ private:
auto child = std::make_shared<ChildProcess>(pid, jailId, socket, request);
#if !MOBILEAPP
UnitWSD::get().newChild(child);
#endif
if (!Util::isMobileApp())
UnitWSD::get().newChild(child);
_pid = pid;
_socketFD = socket->getFD();

View File

@ -372,13 +372,13 @@ public:
{
std::string lowerCaseExtension = extension;
std::transform(lowerCaseExtension.begin(), lowerCaseExtension.end(), lowerCaseExtension.begin(), ::tolower);
#if MOBILEAPP
if (lowerCaseExtension == "pdf")
return true; // true for only pdf - it is not editable
return false; // mark everything else editable on mobile
#else
return EditFileExtensions.find(lowerCaseExtension) == EditFileExtensions.end();
#endif
if (Util::isMobileApp())
{
if (lowerCaseExtension == "pdf")
return true; // true for only pdf - it is not editable
return false; // mark everything else editable on mobile
}
return EditFileExtensions.find(lowerCaseExtension) == EditFileExtensions.end();
}
/// Return true if extension is marked as view_comment action in discovery.xml.
@ -387,13 +387,14 @@ public:
std::string lowerCaseExtension = extension;
std::transform(lowerCaseExtension.begin(), lowerCaseExtension.end(), lowerCaseExtension.begin(), ::tolower);
#if MOBILEAPP
if (lowerCaseExtension == "pdf")
return true; // true for only pdf - it is not editable
return false; // mark everything else editable on mobile
#else
return ViewWithCommentsFileExtensions.find(lowerCaseExtension) != ViewWithCommentsFileExtensions.end();
#endif
if (Util::isMobileApp())
{
if (lowerCaseExtension == "pdf")
return true; // true for only pdf - it is not editable
return false; // mark everything else editable on mobile
}
return ViewWithCommentsFileExtensions.find(lowerCaseExtension) !=
ViewWithCommentsFileExtensions.end();
}
/// Returns the value of the specified application configuration,
@ -660,8 +661,6 @@ public:
void setKitInProcess();
#if !MOBILEAPP
int createForkit(const std::string& forKitPath, const StringVector& args);
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

View File

@ -557,14 +557,15 @@ bool ClientSession::_handleInput(const char *buffer, int length)
if (COOLWSD::EnableTraceEventLogging)
sendTextFrame("enabletraceeventlogging yes");
#if !MOBILEAPP
if (!Util::isMobileApp())
{
// If it is not mobile, it must be Linux (for now).
std::string osVersionInfo(COOLWSD::getConfigValue<std::string>("per_view.custom_os_info", ""));
if (osVersionInfo.empty())
osVersionInfo = Util::getLinuxVersion();
sendTextFrame(std::string("osinfo ") + osVersionInfo);
#endif
}
// Send clipboard key
rotateClipboardKey(true);
@ -1655,9 +1656,8 @@ bool ClientSession::handleKitToClientMessage(const std::shared_ptr<Message>& pay
const bool isConvertTo = static_cast<bool>(_saveAsSocket);
#if !MOBILEAPP
COOLWSD::dumpOutgoingTrace(docBroker->getJailId(), getId(), firstLine);
#endif
if (!Util::isMobileApp())
COOLWSD::dumpOutgoingTrace(docBroker->getJailId(), getId(), firstLine);
const auto& tokens = payload->tokens();
if (tokens.equals(0, "unocommandresult:"))

View File

@ -190,9 +190,8 @@ DocumentBroker::DocumentBroker(ChildType type, const std::string& uri, const Poc
assert(!_docKey.empty());
assert(!COOLWSD::ChildRoot.empty());
#if !MOBILEAPP
assert(_mobileAppDocId == 0 && "Unexpected to have mobileAppDocId in the non-mobile build");
#endif
if (!Util::isMobileApp())
assert(_mobileAppDocId == 0 && "Unexpected to have mobileAppDocId in the non-mobile build");
#ifdef IOS
assert(_mobileAppDocId > 0 && "Unexpected to have no mobileAppDocId in the iOS build");
#endif
@ -209,13 +208,13 @@ DocumentBroker::DocumentBroker(ChildType type, const std::string& uri, const Poc
void DocumentBroker::setupPriorities()
{
#if !MOBILEAPP
if (Util::isMobileApp())
return;
if (_type == ChildType::Batch)
{
int prio = COOLWSD::getConfigValue<int>("per_document.batch_priority", 5);
Util::setProcessAndThreadPriorities(_childProcess->getPid(), prio);
}
#endif
}
void DocumentBroker::setupTransfer(SocketDisposition &disposition,
@ -1008,8 +1007,7 @@ bool DocumentBroker::download(
// message for "view file extension" document types
session->sendFileMode(session->isReadOnly(), session->isAllowChangeComments());
}
#ifdef MOBILEAPP
else
else if (Util::isMobileApp())
{
// Fix issue #5887 by assuming that documents are writable on iOS and Android
// The iOS and Android app saves directly to local disk so, other than for
@ -1021,7 +1019,6 @@ bool DocumentBroker::download(
session->setReadOnly(false);
session->setAllowChangeComments(true);
}
#endif
}
}
@ -1216,12 +1213,7 @@ bool DocumentBroker::download(
_storageManager.setLastUploadedFileModifiedTime(timepoint); // Used to detect modifications.
}
bool dontUseCache = false;
#if MOBILEAPP
// avoid memory consumption for single-user local bits.
// FIXME: arguably should/could do this for single user documents too.
dontUseCache = true;
#endif
bool dontUseCache = Util::isMobileApp();
_tileCache = std::make_unique<TileCache>(_storage->getUri().toString(),
_saveManager.getLastModifiedTime(), dontUseCache);
@ -2893,8 +2885,7 @@ void DocumentBroker::disconnectSessionInternal(const std::shared_ptr<ClientSessi
LOG_DBG("Disconnecting session [" << id << "] from Kit");
hardDisconnect = session->disconnectFromKit();
#if !MOBILEAPP
if (!isLoaded() && _sessions.empty())
if (!Util::isMobileApp() && !isLoaded() && _sessions.empty())
{
// We aren't even loaded and no other views--kill.
// If we send disconnect, we risk hanging because we flag Core for
@ -2908,7 +2899,6 @@ void DocumentBroker::disconnectSessionInternal(const std::shared_ptr<ClientSessi
if (_childProcess)
_childProcess->terminate();
}
#endif
}
if (hardDisconnect)

View File

@ -72,11 +72,9 @@ RequestDetails::RequestDetails(Poco::Net::HTTPRequest &request, const std::strin
_proxyPrefix = it->second;
it = request.find("Upgrade");
_isWebSocket = it != request.end() && Util::iequal(it->second, "websocket");
#if MOBILEAPP
// request.getHost fires an exception on mobile.
#else
_hostUntrusted = request.getHost();
#endif
if (!Util::isMobileApp())
_hostUntrusted = request.getHost();
processURI();
}
@ -256,11 +254,7 @@ void RequestDetails::processURI()
Poco::URI RequestDetails::sanitizeURI(const std::string& uri)
{
// The URI of the document should be url-encoded.
#if !MOBILEAPP
Poco::URI uriPublic(Util::decodeURIComponent(uri));
#else
Poco::URI uriPublic(uri);
#endif
Poco::URI uriPublic((Util::isMobileApp() ? uri : Util::decodeURIComponent(uri)));
if (uriPublic.isRelative() || uriPublic.getScheme() == "file")
{

View File

@ -525,16 +525,17 @@ std::shared_ptr<http::Session> StorageBase::getHttpSession(const Poco::URI& uri)
void LockContext::initSupportsLocks()
{
#if MOBILEAPP
_supportsLocks = false;
#else
if (_supportsLocks)
return;
if (Util::isMobileApp())
_supportsLocks = false;
else
{
if (_supportsLocks)
return;
// first time token setup
_supportsLocks = true;
_lockToken = "cool-lock" + Util::rng::getHexString(8);
#endif
// first time token setup
_supportsLocks = true;
_lockToken = "cool-lock" + Util::rng::getHexString(8);
}
}
bool LockContext::needsRefresh(const std::chrono::steady_clock::time_point &now) const

View File

@ -16,13 +16,11 @@
void setKitInProcess() { Util::setKitInProcess(false); }
#if !MOBILEAPP
int createForkit(const std::string& forKitPath, const StringVector& args)
{
// create forkit in a process
return Util::spawnProcess(forKitPath, args);
};
#endif
// FIXME: Somewhat idiotically, the parameter to emitOneRecordingIfEnabled() should end with a
// newline, while the paramter to emitOneRecording() should not.