diff --git a/2600.emu/build.mk b/2600.emu/build.mk index 2991d1f16..4ee7e49d8 100644 --- a/2600.emu/build.mk +++ b/2600.emu/build.mk @@ -13,6 +13,8 @@ CPPFLAGS += -I$(projectPath)/src \ -I$(projectPath)/src/stella/common/tv_filters \ -I$(projectPath)/src/stella/gui +CFLAGS_WARN += -Wno-unused-parameter + stellaSrc := AtariVox.cxx \ Bankswitch.cxx \ Booster.cxx \ diff --git a/2600.emu/src/main/SoundEmuEx.cc b/2600.emu/src/main/SoundEmuEx.cc index 52ef01f72..53d45120c 100644 --- a/2600.emu/src/main/SoundEmuEx.cc +++ b/2600.emu/src/main/SoundEmuEx.cc @@ -111,13 +111,13 @@ void SoundEmuEx::setEmuAudio(EmuEx::EmuAudio *audio) [this, audio](AudioQueue &queue, uInt32 fragFrames) { const int samplesPerFrame = 1; //audioQueue->isStereo() ? 2 : 1; - const int fragSamples = fragFrames * samplesPerFrame; - int wroteFrames = 0; + [[maybe_unused]] const int fragSamples = fragFrames * samplesPerFrame; + [[maybe_unused]] int wroteFrames = 0; //logDMsg("%d fragments of %d size ready", audioQueue->size(), fragFrames); while(queue.size()) { float buffF[512]; - assert(fragSamples <= std::size(buffF)); + assert(fragSamples <= std::ssize(buffF)); myResampler->fillFragment(buffF, fragFrames); if(audio) { diff --git a/C64.emu/build.mk b/C64.emu/build.mk index 2b491a3a0..57919653b 100644 --- a/C64.emu/build.mk +++ b/C64.emu/build.mk @@ -6,7 +6,7 @@ include $(IMAGINE_PATH)/make/imagineAppBase.mk viceSrcPath := $(projectPath)/src/vice CFLAGS_LANG += -Werror=implicit-function-declaration -CFLAGS_WARN += -Wno-implicit-fallthrough -Wno-sign-compare +CFLAGS_WARN += -Wno-implicit-fallthrough -Wno-sign-compare -Wno-unused-parameter -Wno-unused-function ifeq ($(ENV),android) LDLIBS += -ldl diff --git a/C64.emu/src/main/input.cc b/C64.emu/src/main/input.cc index cc7e6791d..c46fc28ae 100644 --- a/C64.emu/src/main/input.cc +++ b/C64.emu/src/main/input.cc @@ -542,11 +542,6 @@ AssetDesc C64App::vControllerAssetDesc(KeyInfo key) const } } -static bool isEmuKeyInKeyboardRange(KeyCode emuKey) -{ - return emuKey >= KeyCode(C64Key::KeyboardFirstEnum) && emuKey <= KeyCode(C64Key::KeyboardLastEnum); -} - VController::KbMap C64System::vControllerKeyboardMap(VControllerKbMode mode) { static constexpr VController::KbMap kbToEventMap = @@ -691,7 +686,7 @@ void C64System::handleInputAction(EmuApp *app, InputAction a) if(app) { log.info("pushed restore key"); - app->syncEmulationThread(); + auto emuThreadResumer = app->suspendEmulationThread(); plugin.machine_set_restore_key(a.state == Input::Action::PUSHED); } break; diff --git a/C64.emu/src/main/video.cc b/C64.emu/src/main/video.cc index 1d5cb8ce1..112d2e635 100644 --- a/C64.emu/src/main/video.cc +++ b/C64.emu/src/main/video.cc @@ -140,7 +140,6 @@ void C64System::resetCanvasSourcePixmap(struct video_canvas_s *c) { if(activeCanvas != c) return; - unsigned canvasW = c->w; unsigned canvasH = c->h; if(optionCropNormalBorders && (canvasH == 247 || canvasH == 272)) { @@ -157,7 +156,6 @@ void C64System::resetCanvasSourcePixmap(struct video_canvas_s *c) startX = xBorderSize; startY = xBorderSize; } int width = 320+(xBorderSize*2 - startX*2); - int widthPadding = startX*2; canvasSrcPix = pixmapView(c).subView({startX, startY}, {width, height}); } else diff --git a/EmuFramework/include/emuframework/DataPathSelectView.hh b/EmuFramework/include/emuframework/DataPathSelectView.hh index 3842a3565..fca2b28a0 100644 --- a/EmuFramework/include/emuframework/DataPathSelectView.hh +++ b/EmuFramework/include/emuframework/DataPathSelectView.hh @@ -61,7 +61,7 @@ public: auto &thisView = asThis(view); fPicker->setPath(thisView.searchDir, e); fPicker->setOnSelectPath( - [=](FSPicker &picker, CStringView path, std::string_view displayName, const Input::Event &e) + [=](FSPicker &picker, CStringView path, [[maybe_unused]] std::string_view displayName, const Input::Event&) { if(!onFileChange(path, FS::file_type::directory)) return; @@ -82,7 +82,7 @@ public: archiveMode == ArchivePathSelectMode::include); fPicker->setPath(thisView.searchDir, e); fPicker->setOnSelectPath( - [=](FSPicker &picker, CStringView path, std::string_view displayName, const Input::Event &e) + [=](FSPicker &picker, CStringView path, std::string_view displayName, const Input::Event&) { if(mode == DataPathSelectMode::Folder && !EmuApp::hasArchiveExtension(displayName)) { diff --git a/EmuFramework/include/emuframework/EmuApp.hh b/EmuFramework/include/emuframework/EmuApp.hh index 4533a2305..dfe67a144 100644 --- a/EmuFramework/include/emuframework/EmuApp.hh +++ b/EmuFramework/include/emuframework/EmuApp.hh @@ -198,8 +198,8 @@ public: void readState(std::span buff); size_t writeState(std::span buff, SaveStateFlags = {}); DynArray saveState(); - bool saveState(CStringView path); - bool saveStateWithSlot(int slot); + bool saveState(CStringView path, bool notify); + bool saveStateWithSlot(int slot, bool notify); bool loadState(CStringView path); bool loadStateWithSlot(int slot); bool shouldOverwriteExistingState() const; @@ -218,7 +218,8 @@ public: bool hasSavedSessionOptions(); void resetSessionOptions(); void deleteSessionOptions(); - void syncEmulationThread(); + [[nodiscard]] + EmuSystemTask::SuspendContext suspendEmulationThread(); void startAudio(); EmuViewController &viewController(); const EmuViewController &viewController() const; @@ -242,6 +243,10 @@ public: void skipFrames(EmuSystemTaskContext, int frames, EmuAudio *); bool skipForwardFrames(EmuSystemTaskContext, int frames); void notifyWindowPresented(); + void reportFrameWorkTime(); + void addOnFrameDelayed(); + void addOnFrame(); + void removeOnFrame(); void renderSystemFramebuffer(EmuVideo &); void renderSystemFramebuffer() { renderSystemFramebuffer(video); } bool writeScreenshot(IG::PixmapView, CStringView path); @@ -328,6 +333,7 @@ public: void postMessage(int secs, bool error, UTF16Convertible auto &&msg) { + auto suspendCtx = suspendEmulationThread(); toastView().post(IG_forward(msg), secs, error); } @@ -375,8 +381,9 @@ public: [[no_unique_address]] IG::VibrationManager vibrationManager; protected: EmuSystemTask emuSystemTask{*this}; - mutable Gfx::Texture assetBuffImg[wise_enum::size]; + std::binary_semaphore framePresentedSem{0}; int savedAdvancedFrames{}; + mutable Gfx::Texture assetBuffImg[wise_enum::size]; [[no_unique_address]] IG::Data::PixmapReader pixmapReader; [[no_unique_address]] IG::Data::PixmapWriter pixmapWriter; [[no_unique_address]] PerformanceHintManager perfHintManager; @@ -464,14 +471,10 @@ protected: void saveSystemOptions(FileIO &); bool allWindowsAreFocused() const; void configureSecondaryScreens(); - void addOnFrameDelayed(); - void addOnFrame(); - void removeOnFrame(); IG::OnFrameDelegate onFrameDelayed(int8_t delay); void addOnFrameDelegate(IG::OnFrameDelegate); void onFocusChange(bool in); void configureAppForEmulation(bool running); - void reportFrameWorkTime(); }; // Global instance access if required by the emulated system, valid if EmuApp::needsGlobalInstance initialized to true diff --git a/EmuFramework/include/emuframework/EmuSystemTask.hh b/EmuFramework/include/emuframework/EmuSystemTask.hh index b0767c72f..e874da920 100644 --- a/EmuFramework/include/emuframework/EmuSystemTask.hh +++ b/EmuFramework/include/emuframework/EmuSystemTask.hh @@ -19,6 +19,7 @@ #include #include #include +#include namespace EmuEx { @@ -32,16 +33,14 @@ class EmuApp; class EmuSystemTask { public: - struct FrameParamsCommand + struct SuspendCommand {}; + struct ExitCommand {}; + struct SetWindowCommand { - FrameParams params; + Window* winPtr; }; - struct FramePresentedCommand {}; - struct PauseCommand {}; - struct ExitCommand {}; - - using CommandVariant = std::variant; + using CommandVariant = std::variant; class Command: public CommandVariant, public AddVisit { public: @@ -51,31 +50,58 @@ public: struct CommandMessage { - std::binary_semaphore *semPtr{}; - Command command{PauseCommand{}}; + std::binary_semaphore* semPtr{}; + Command command{SuspendCommand{}}; void setReplySemaphore(std::binary_semaphore *semPtr_) { assert(!semPtr); semPtr = semPtr_; }; }; - EmuSystemTask(EmuApp &); - void start(); - void pause(); + struct SuspendContext + { + SuspendContext() = default; + SuspendContext(EmuSystemTask* taskPtr):taskPtr{taskPtr} {} + SuspendContext(SuspendContext&& rhs) noexcept { *this = std::move(rhs); } + SuspendContext& operator=(SuspendContext&& rhs) + { + taskPtr = std::exchange(rhs.taskPtr, nullptr); + return *this; + } + + void resume() + { + if(taskPtr) + std::exchange(taskPtr, nullptr)->resume(); + } + + ~SuspendContext() { resume(); } + + private: + EmuSystemTask* taskPtr{}; + }; + + EmuSystemTask(EmuApp&); + void start(Window&); + [[nodiscard]] + SuspendContext setWindow(Window&); + [[nodiscard]] + SuspendContext suspend(); void stop(); - void updateFrameParams(FrameParams); - void notifyFramePresented(); - void sendVideoFormatChangedReply(EmuVideo &); - void sendFrameFinishedReply(EmuVideo &); + void sendVideoFormatChangedReply(EmuVideo&); + void sendFrameFinishedReply(EmuVideo&); void sendScreenshotReply(bool success); auto threadId() const { return threadId_; } + Window &window() { return *winPtr; } private: EmuApp &app; + Window *winPtr{}; MessagePort commandPort{"EmuSystemTask Command"}; std::thread taskThread; ThreadId threadId_{}; - FrameParams frameParams; -public: - bool framePending{}; + std::binary_semaphore suspendSem{0}; + bool isSuspended{}; + + void resume(); }; } diff --git a/EmuFramework/include/emuframework/Option.hh b/EmuFramework/include/emuframework/Option.hh index 69b74fe6f..b16f42fdf 100644 --- a/EmuFramework/include/emuframework/Option.hh +++ b/EmuFramework/include/emuframework/Option.hh @@ -170,7 +170,7 @@ inline void writeOptionValueIfNotDefault(Writable auto &io, uint16_t key, const writeOptionValue(io, key, val); } -inline void writeOptionValueIfNotDefault(Writable auto &io, Unused auto const &p) {} +inline void writeOptionValueIfNotDefault(Writable auto&, Unused auto const&) {} inline void writeOptionValueIfNotDefault(Writable auto &io, PropertyOption auto const &p) { diff --git a/EmuFramework/include/emuframework/OutSizeTracker.hh b/EmuFramework/include/emuframework/OutSizeTracker.hh index a0da913de..7410cf0b1 100644 --- a/EmuFramework/include/emuframework/OutSizeTracker.hh +++ b/EmuFramework/include/emuframework/OutSizeTracker.hh @@ -34,7 +34,7 @@ public: using IOUtilsBase::toFileStream; OutSizeTracker(size_t *sizePtr): sizePtr{sizePtr} {} - ssize_t read(void *buff, size_t bytes, std::optional offset = {}) { return 0; } + ssize_t read(void*, size_t, [[maybe_unused]] std::optional offset = {}) { return 0; } off_t seek(off_t offset, SeekMode mode) { @@ -49,7 +49,7 @@ public: std::span map() { return {}; } explicit operator bool() const { return sizePtr; } - ssize_t write(const void *buff, size_t bytes, std::optional offset = {}) + ssize_t write(const void*, size_t bytes, [[maybe_unused]] std::optional offset = {}) { currPos += bytes; if(currPos > *sizePtr) diff --git a/EmuFramework/include/emuframework/OutputTimingManager.hh b/EmuFramework/include/emuframework/OutputTimingManager.hh index f6ae3d8f0..aee5168f4 100644 --- a/EmuFramework/include/emuframework/OutputTimingManager.hh +++ b/EmuFramework/include/emuframework/OutputTimingManager.hh @@ -29,22 +29,16 @@ enum class FrameTimeStatEvent { startOfFrame, startOfEmulation, - aboutToSubmitFrame, - aboutToPostDraw, - startOfDraw, - aboutToPresent, - endOfDraw, + waitForPresent, + endOfFrame, }; struct FrameTimeStats { SteadyClockTimePoint startOfFrame{}; SteadyClockTimePoint startOfEmulation{}; - SteadyClockTimePoint aboutToSubmitFrame{}; - SteadyClockTimePoint aboutToPostDraw{}; - SteadyClockTimePoint startOfDraw{}; - SteadyClockTimePoint aboutToPresent{}; - SteadyClockTimePoint endOfDraw{}; + SteadyClockTimePoint waitForPresent{}; + SteadyClockTimePoint endOfFrame{}; int missedFrameCallbacks{}; }; diff --git a/EmuFramework/include/emuframework/SystemOptionView.hh b/EmuFramework/include/emuframework/SystemOptionView.hh index 72d786fd6..544153c81 100755 --- a/EmuFramework/include/emuframework/SystemOptionView.hh +++ b/EmuFramework/include/emuframework/SystemOptionView.hh @@ -48,7 +48,10 @@ protected: ConditionalMember performanceMode; ConditionalMember noopThread; ConditionalMember cpuAffinity; - StaticArrayList item; + TextHeadingMenuItem autosaveHeading; + TextHeadingMenuItem rewindHeading; + TextHeadingMenuItem otherHeading; + StaticArrayList item; }; } diff --git a/EmuFramework/include/emuframework/UserPathSelectView.hh b/EmuFramework/include/emuframework/UserPathSelectView.hh index d551007ce..1c4f17d3b 100644 --- a/EmuFramework/include/emuframework/UserPathSelectView.hh +++ b/EmuFramework/include/emuframework/UserPathSelectView.hh @@ -39,7 +39,7 @@ public: auto &thisView = asThis(view); fPicker->setPath(thisView.searchDir, e); fPicker->setOnSelectPath( - [=](FSPicker &picker, CStringView path, std::string_view displayName, const Input::Event &e) + [=](FSPicker &picker, CStringView path, [[maybe_unused]] std::string_view displayName, const Input::Event&) { onPathChange(path); picker.popTo(); diff --git a/EmuFramework/include/emuframework/VController.hh b/EmuFramework/include/emuframework/VController.hh index 30bac77e1..a01d7a07a 100755 --- a/EmuFramework/include/emuframework/VController.hh +++ b/EmuFramework/include/emuframework/VController.hh @@ -154,7 +154,7 @@ public: void draw(Gfx::RendererCommands &__restrict__) const; int getInput(WPt c) const; KeyInfo translateInput(int idx) const; - bool keyInput(VController &v, Gfx::Renderer &r, const Input::KeyEvent &e); + bool keyInput(VController&, const Input::KeyEvent&); [[nodiscard]] WindowRect selectKey(int x, int y); void selectKeyRel(int x, int y); void unselectKey(); @@ -162,8 +162,8 @@ public: KeyInfo currentKey() const; KeyInfo currentKey(int x, int y) const; VControllerKbMode mode() const { return mode_; } - void setMode(EmuSystem &, Gfx::Renderer &, VControllerKbMode mode); - void cycleMode(EmuSystem &, Gfx::Renderer &); + void setMode(EmuSystem&, VControllerKbMode mode); + void cycleMode(EmuSystem&); void applyMap(KbMap map); void updateKeyboardMapping(EmuSystem &); void setShiftActive(bool); @@ -440,7 +440,7 @@ public: { [&](VControllerDPad &e){ e.setShowBounds(r, on); }, [&](VControllerButtonGroup &e){ e.setShowBounds(on); }, - [](auto &e){} + [](auto&){} }); } @@ -448,7 +448,7 @@ public: { return visit(overloaded { - [&](const VControllerDPad &e){ return LB2DO; }, + [&](const VControllerDPad&){ return LB2DO; }, [](auto &e){ return e.layout.origin; } }); } diff --git a/EmuFramework/src/AutosaveManager.cc b/EmuFramework/src/AutosaveManager.cc index 5f154bcdc..ed3722f22 100644 --- a/EmuFramework/src/AutosaveManager.cc +++ b/EmuFramework/src/AutosaveManager.cc @@ -33,8 +33,8 @@ AutosaveManager::AutosaveManager(EmuApp &app_): saveTimer { defaultSaveFreq, - "AutosaveManager::autosaveTimer", - [this]() + {.debugLabel = "AutosaveManager::autosaveTimer"}, + [this] { log.debug("running autosave timer"); save(); @@ -151,7 +151,7 @@ bool AutosaveManager::deleteSlot(std::string_view name) return false; auto ctx = appContext(); if(!ctx.forEachInDirectoryUri(system().contentLocalSaveDirectory(name), - [this, ctx](const FS::directory_entry &e) + [ctx](const FS::directory_entry &e) { ctx.removeFileUri(e.path()); return true; diff --git a/EmuFramework/src/EmuApp.cc b/EmuFramework/src/EmuApp.cc index ca315834e..f3b0701c6 100644 --- a/EmuFramework/src/EmuApp.cc +++ b/EmuFramework/src/EmuApp.cc @@ -110,7 +110,7 @@ EmuApp::EmuApp(ApplicationInitParams initParams, ApplicationContext &ctx): if(needsGlobalInstance) gAppPtr = this; ctx.setAcceptIPC(true); - onEvent = [this](ApplicationContext ctx, const ApplicationEvent& appEvent) + onEvent = [this](ApplicationContext, const ApplicationEvent& appEvent) { appEvent.visit(overloaded { @@ -214,8 +214,8 @@ static void suspendEmulation(EmuApp &app) void EmuApp::closeSystem() { - showUI(); emuSystemTask.stop(); + showUI(); system().closeRuntimeSystem(*this); autosaveManager.resetSlot(); rewindManager.clear(); @@ -380,7 +380,7 @@ static SteadyClockTime targetFrameTime(const Screen &s) void EmuApp::mainInitCommon(IG::ApplicationInitParams initParams, IG::ApplicationContext ctx) { - auto appConfig = loadConfigFile(ctx); + loadConfigFile(ctx); system().onOptionsLoaded(); loadSystemOptions(); updateLegacySavePathOnStoragePath(ctx, system()); @@ -391,7 +391,7 @@ void EmuApp::mainInitCommon(IG::ApplicationInitParams initParams, IG::Applicatio applyOSNavStyle(ctx, false); ctx.addOnResume( - [this](IG::ApplicationContext ctx, bool focused) + [this](IG::ApplicationContext, [[maybe_unused]] bool focused) { audio.manager.startSession(); audio.open(); @@ -423,7 +423,7 @@ void EmuApp::mainInitCommon(IG::ApplicationInitParams initParams, IG::Applicatio IG::WindowConfig winConf{ .title = ctx.applicationName }; winConf.setFormat(windowDrawableConfig.pixelFormat); ctx.makeWindow(winConf, - [this, appConfig](IG::ApplicationContext ctx, IG::Window &win) + [this](IG::ApplicationContext ctx, IG::Window &win) { renderer.initMainTask(&win, windowDrawableConfig); textureBufferMode = renderer.validateTextureBufferMode(textureBufferMode); @@ -441,7 +441,6 @@ void EmuApp::mainInitCommon(IG::ApplicationInitParams initParams, IG::Applicatio { vController.setKeyboardImage(asset(AssetID::keyboardOverlay)); } - auto &screen = *win.screen(); winData.viewController.placeElements(); winData.viewController.pushAndShow(makeView(viewAttach, ViewID::MAIN_MENU)); configureSecondaryScreens(); @@ -457,7 +456,19 @@ void EmuApp::mainInitCommon(IG::ApplicationInitParams initParams, IG::Applicatio videoLayer.updateEffect(system(), videoEffectPixelFormat()); system().onFrameUpdate = [this](FrameParams params) { - emuSystemTask.updateFrameParams(params); + bool renderingFrame = advanceFrames(params, &emuSystemTask); + if(params.isFromRenderer() && !renderingFrame) + { + renderingFrame = true; + emuSystemTask.window().drawNow(); + } + if(renderingFrame) + { + record(FrameTimeStatEvent::waitForPresent); + framePresentedSem.acquire(); + reportFrameWorkTime(); + record(FrameTimeStatEvent::endOfFrame); + } return true; }; @@ -468,8 +479,6 @@ void EmuApp::mainInitCommon(IG::ApplicationInitParams initParams, IG::Applicatio [&](const Input::Event& e) { return viewController().inputEvent(e); }, [&](const DrawEvent& e) { - record(FrameTimeStatEvent::startOfDraw); - auto reportTime = scopeGuard([&]{ reportFrameWorkTime(); }); return viewController().drawMainWindow(win, e.params, renderer.task()); }, [&](const WindowSurfaceChangeEvent& e) @@ -534,7 +543,7 @@ void EmuApp::mainInitCommon(IG::ApplicationInitParams initParams, IG::Applicatio perfHintSession.updateTargetWorkTime(targetTime); log.info("updated performance hint session with target time:{}", targetTime); } - syncEmulationThread(); + auto suspendCtx = suspendEmulationThread(); configFrameTime(); } } @@ -645,9 +654,7 @@ bool EmuApp::advanceFrames(FrameParams frameParams, EmuSystemTask *taskPtr) if(enableBlankFrameInsertion) { viewCtrl.drawBlankFrame = true; - if(taskPtr) - taskPtr->framePending = true; - win.postDraw(1); + win.drawNow(); return true; } return false; @@ -665,6 +672,10 @@ bool EmuApp::advanceFrames(FrameParams frameParams, EmuSystemTask *taskPtr) { frameInfo.advanced = 1; } + if(frameInfo.advanced > 1) + { + doIfUsed(frameTimeStats, [&](auto &stats) { stats.missedFrameCallbacks+= frameInfo.advanced - 1; }); + } } assumeExpr(frameInfo.advanced > 0); // cap advanced frames if we're falling behind @@ -679,19 +690,11 @@ bool EmuApp::advanceFrames(FrameParams frameParams, EmuSystemTask *taskPtr) } record(FrameTimeStatEvent::startOfFrame, frameParams.timestamp); record(FrameTimeStatEvent::startOfEmulation); - win.setDrawEventPriority(Window::drawEventPriorityLocked); - if(taskPtr) - taskPtr->framePending = true; } - inputManager.turboActions.update(*this); //log.debug("running {} frame(s), skip:{}", frameInfo.advanced, !videoPtr); runFrames({taskPtr}, videoPtr, audioPtr, frameInfo.advanced); - if(!videoPtr) - { - reportFrameWorkTime(); - return false; - } - return true; + inputManager.turboActions.update(*this); + return videoPtr; } IG::Viewport EmuApp::makeViewport(const IG::Window &win) const @@ -822,15 +825,12 @@ void EmuApp::startEmulation() video.onFrameFinished = [&, &viewController = viewController()](EmuVideo&) { auto &win = viewController.emuWindow(); - record(FrameTimeStatEvent::aboutToPostDraw); - win.setDrawEventPriority(1); - win.postDraw(1); + win.drawNow(); }; frameTimeStats = {}; - emuSystemTask.start(); - setCPUNeedsLowLatency(appContext(), true); system().start(*this); - addOnFrameDelayed(); + emuSystemTask.start(emuWindow()); + setCPUNeedsLowLatency(appContext(), true); } void EmuApp::showUI(bool updateTopView) @@ -845,14 +845,12 @@ void EmuApp::showUI(bool updateTopView) void EmuApp::pauseEmulation() { + emuSystemTask.stop(); setCPUNeedsLowLatency(appContext(), false); - emuSystemTask.pause(); video.onFrameFinished = [](EmuVideo&){}; system().pause(*this); setRunSpeed(1.); videoLayer.setBrightnessScale(pausedVideoBrightnessScale); - emuWindow().setDrawEventPriority(); - removeOnFrame(); } bool EmuApp::hasArchiveExtension(std::string_view name) @@ -885,14 +883,14 @@ void EmuApp::reloadSystem(EmuSystemCreateParams params) { if(!system().hasContent()) return; + pauseEmulation(); viewController().popToSystemActionsMenu(); - emuSystemTask.pause(); auto ctx = appContext(); try { system().createWithMedia({}, system().contentLocation(), ctx.fileUriDisplayName(system().contentLocation()), params, - [](int pos, int max, const char *label){ return true; }); + [](int, int, const char*){ return true; }); onSystemCreated(); if(autosaveManager.slotName() != noAutosaveName) system().loadBackupMemory(*this); @@ -960,7 +958,6 @@ void EmuApp::createSystemWithMedia(IO io, CStringView path, std::string_view dis auto loadProgressView = std::make_unique(attachParams, e, onComplete); auto &msgPort = loadProgressView->messagePort(); pushAndShowModalView(std::move(loadProgressView), e); - auto ctx = attachParams.appContext(); IG::makeDetachedThread( [this, io{std::move(io)}, pathStr = FS::PathString{path}, nameStr = FS::FileString{displayName}, &msgPort, params]() mutable { @@ -1024,7 +1021,7 @@ void EmuApp::setupStaticBackupMemoryFile(FileIO &io, std::string_view ext, size_ void EmuApp::readState(std::span buff) { - syncEmulationThread(); + auto suspendCtx = suspendEmulationThread(); system().readState(*this, buff); system().clearInputBuffers(viewController().inputView); autosaveManager.resetTimer(); @@ -1032,28 +1029,30 @@ void EmuApp::readState(std::span buff) size_t EmuApp::writeState(std::span buff, SaveStateFlags flags) { - syncEmulationThread(); + auto suspendCtx = suspendEmulationThread(); return system().writeState(buff, flags); } DynArray EmuApp::saveState() { - syncEmulationThread(); + auto suspendCtx = suspendEmulationThread(); return system().saveState(); } -bool EmuApp::saveState(CStringView path) +bool EmuApp::saveState(CStringView path, bool notify) { if(!system().hasContent()) { postErrorMessage("System not running"); return false; } - syncEmulationThread(); log.info("saving state {}", path); + auto suspendCtx = suspendEmulationThread(); try { system().saveState(path); + if(notify) + postMessage("State Saved"); return true; } catch(std::exception &err) @@ -1063,9 +1062,9 @@ bool EmuApp::saveState(CStringView path) } } -bool EmuApp::saveStateWithSlot(int slot) +bool EmuApp::saveStateWithSlot(int slot, bool notify) { - return saveState(system().statePath(slot)); + return saveState(system().statePath(slot), notify); } bool EmuApp::loadState(CStringView path) @@ -1076,7 +1075,7 @@ bool EmuApp::loadState(CStringView path) return false; } log.info("loading state {}", path); - syncEmulationThread(); + auto suspendCtx = suspendEmulationThread(); try { system().loadState(*this, path); @@ -1106,7 +1105,6 @@ FS::PathString EmuApp::inContentSearchPath(std::string_view name) const FS::PathString EmuApp::validSearchPath(const FS::PathString &path) const { - auto ctx = appContext(); if(path.empty()) return contentSearchPath; return hasArchiveExtension(path) ? FS::dirnameUri(path) : path; @@ -1116,7 +1114,7 @@ FS::PathString EmuApp::validSearchPath(const FS::PathString &path) const [[gnu::weak]] void EmuApp::onCustomizeNavView(EmuApp::NavView &) {} -[[gnu::weak]] std::unique_ptr EmuApp::makeCustomView(ViewAttachParams attach, EmuApp::ViewID id) +[[gnu::weak]] std::unique_ptr EmuApp::makeCustomView(ViewAttachParams, EmuApp::ViewID) { return nullptr; } @@ -1145,7 +1143,7 @@ void EmuApp::resetInput() void EmuApp::setRunSpeed(double speed) { assumeExpr(speed > 0.); - syncEmulationThread(); + auto suspendCtx = suspendEmulationThread(); system().frameTimeMultiplier = 1. / speed; audio.setSpeedMultiplier(speed); configFrameTime(); @@ -1273,11 +1271,7 @@ void EmuApp::saveSystemOptions(FileIO &configFile) system().writeConfig(ConfigType::CORE, configFile); } -void EmuApp::syncEmulationThread() -{ - renderer.mainTask.awaitPending(); - emuSystemTask.pause(); -} +EmuSystemTask::SuspendContext EmuApp::suspendEmulationThread() { return emuSystemTask.suspend(); } FrameTimeConfig EmuApp::configFrameTime() { @@ -1305,7 +1299,7 @@ void EmuApp::runFrames(EmuSystemTaskContext taskCtx, EmuVideo *video, EmuAudio * void EmuApp::skipFrames(EmuSystemTaskContext taskCtx, int frames, EmuAudio *audio) { assert(system().hasContent()); - for(auto i : iotaCount(frames)) + for([[maybe_unused]] auto i : iotaCount(frames)) { system().runFrame(taskCtx, nullptr, audio); } @@ -1327,7 +1321,7 @@ bool EmuApp::skipForwardFrames(EmuSystemTaskContext taskCtx, int frames) void EmuApp::notifyWindowPresented() { - emuSystemTask.notifyFramePresented(); + framePresentedSem.release(); } bool EmuApp::writeScreenshot(IG::PixmapView pix, CStringView path) @@ -1427,17 +1421,15 @@ void EmuApp::setEmuViewOnExtraWindow(bool on, IG::Screen &screen) winConf.setScreen(screen); winConf.setFormat(windowDrawableConfig.pixelFormat); auto extraWin = ctx.makeWindow(winConf, - [this](IG::ApplicationContext ctx, IG::Window &win) + [this](IG::ApplicationContext, IG::Window &win) { renderer.attachWindow(win, windowDrawableConfig); - auto &mainWinData = windowData(ctx.mainWindow()); auto &extraWinData = win.makeAppData(); extraWinData.hasPopup = false; extraWinData.focused = true; + auto suspendCtx = emuSystemTask.setWindow(win); if(system().isActive()) { - emuSystemTask.pause(); - win.moveOnFrame(ctx.mainWindow(), system().onFrameUpdate, frameTimeSource); setIntendedFrameRate(win, configFrameTime()); } extraWinData.updateWindowViewport(win, makeViewport(win), renderer); @@ -1450,7 +1442,6 @@ void EmuApp::setEmuViewOnExtraWindow(bool on, IG::Screen &screen) [&](const Input::Event& e) { return viewController().extraWindowInputEvent(e); }, [&](const DrawEvent& e) { - auto reportTime = scopeGuard([&]{ reportFrameWorkTime(); }); return viewController().drawExtraWindow(win, e.params, renderer.task()); }, [&](const WindowSurfaceChangeEvent& e) @@ -1474,25 +1465,25 @@ void EmuApp::setEmuViewOnExtraWindow(bool on, IG::Screen &screen) onFocusChange(e.in); return true; }, - [&](const DismissRequestEvent& e) + [&](const DismissRequestEvent&) { win.dismiss(); return true; }, - [&](const DismissEvent& e) + [&](const DismissEvent&) { + auto suspendCtx = emuSystemTask.setWindow(mainWindow()); system().resetFrameTime(); log.info("setting emu view on main window"); viewController().moveEmuViewToWindow(appContext().mainWindow()); viewController().movePopupToWindow(appContext().mainWindow()); viewController().placeEmuViews(); - mainWindow().postDraw(); if(system().isActive()) { - emuSystemTask.pause(); - mainWindow().moveOnFrame(win, system().onFrameUpdate, frameTimeSource); setIntendedFrameRate(mainWindow(), configFrameTime()); } + suspendCtx.resume(); + mainWindow().postDraw(); return true; }, [](auto&){ return false; } @@ -1501,6 +1492,7 @@ void EmuApp::setEmuViewOnExtraWindow(bool on, IG::Screen &screen) win.show(); viewController().placeEmuViews(); + suspendCtx.resume(); mainWindow().postDraw(); }); if(!extraWin) @@ -1537,6 +1529,10 @@ IG::OnFrameDelegate EmuApp::onFrameDelayed(int8_t delay) { return [this, delay](IG::FrameParams params) { + if(params.isFromRenderer() || video.image()) + { + emuSystemTask.window().drawNow(); + } if(delay) { addOnFrameDelegate(onFrameDelayed(delay - 1)); @@ -1545,7 +1541,6 @@ IG::OnFrameDelegate EmuApp::onFrameDelayed(int8_t delay) { if(system().isActive()) { - viewController().emuWindow().setDrawEventPriority(1); // block UI from posting draws addOnFrame(); } } @@ -1591,11 +1586,6 @@ void EmuApp::applyCPUAffinity(bool active) return; auto frameThreadGroup = std::vector{emuSystemTask.threadId(), renderer.task().threadId()}; system().addThreadGroupIds(frameThreadGroup); - for(auto [idx, id] : enumerate(frameThreadGroup)) - { - if(!id) - log.warn("invalid thread group id @ index:{}", idx); - } if(cpuAffinityMode.value() == CPUAffinityMode::Auto && perfHintManager) { if(active) diff --git a/EmuFramework/src/EmuAudio.cc b/EmuFramework/src/EmuAudio.cc index 59ebd251e..4ec91606b 100644 --- a/EmuFramework/src/EmuAudio.cc +++ b/EmuFramework/src/EmuAudio.cc @@ -47,7 +47,7 @@ static AudioStats audioStats{}; static IG::Timer audioStatsTimer{"audioStatsTimer"}; #endif -static void startAudioStats(IG::Audio::Format format) +static void startAudioStats([[maybe_unused]] Audio::Format format) { #ifdef CONFIG_EMUFRAMEWORK_AUDIO_STATS audioStats.reset(); diff --git a/EmuFramework/src/EmuInput.cc b/EmuFramework/src/EmuInput.cc index 22299e032..e89a5a8b8 100644 --- a/EmuFramework/src/EmuInput.cc +++ b/EmuFramework/src/EmuInput.cc @@ -58,8 +58,8 @@ bool InputManager::handleAppActionKeyInput(EmuApp& app, InputAction action, cons case fastForward: { viewController.inputView.setAltSpeedMode(AltSpeedMode::fast, isPushed); - break; } + break; case openContent: { if(!isPushed) @@ -88,16 +88,9 @@ bool InputManager::handleAppActionKeyInput(EmuApp& app, InputAction action, cons { if(!isPushed) break; - static auto doSaveState = [](EmuApp &app, bool notify) - { - if(app.saveStateWithSlot(app.system().stateSlot()) && notify) - { - app.postMessage("State Saved"); - } - }; + static auto doSaveState = [](EmuApp &app, bool notify){ app.saveStateWithSlot(app.system().stateSlot(), notify); }; if(app.shouldOverwriteExistingState()) { - app.syncEmulationThread(); doSaveState(app, app.confirmOverwriteState); } else @@ -119,7 +112,6 @@ bool InputManager::handleAppActionKeyInput(EmuApp& app, InputAction action, cons { if(!isPushed) break; - app.syncEmulationThread(); app.loadStateWithSlot(system.stateSlot()); return true; } @@ -127,6 +119,7 @@ bool InputManager::handleAppActionKeyInput(EmuApp& app, InputAction action, cons { if(!isPushed) break; + auto suspendCtx = app.suspendEmulationThread(); system.decStateSlot(); app.postMessage(1, false, std::format("State Slot: {}", system.stateSlotName())); return true; @@ -135,6 +128,7 @@ bool InputManager::handleAppActionKeyInput(EmuApp& app, InputAction action, cons { if(!isPushed) break; + auto suspendCtx = app.suspendEmulationThread(); system.incStateSlot(); app.postMessage(1, false, std::format("State Slot: {}", system.stateSlotName())); return true; @@ -151,8 +145,8 @@ bool InputManager::handleAppActionKeyInput(EmuApp& app, InputAction action, cons if(!isPushed) break; viewController.inputView.toggleAltSpeedMode(AltSpeedMode::fast); - break; } + break; case openMenu: { if(!isPushed) @@ -166,61 +160,66 @@ bool InputManager::handleAppActionKeyInput(EmuApp& app, InputAction action, cons turboModifierActive = isPushed; if(!isPushed) turboActions = {}; - break; } + break; case exitApp: { if(!isPushed) break; viewController.pushAndShowModal(std::make_unique(app.attachParams(), "Really Exit?", YesNoAlertView::Delegates{.onYes = [&app]{ app.appContext().exit(); }}), srcEvent, false); - break; } + break; case slowMotion: { viewController.inputView.setAltSpeedMode(AltSpeedMode::slow, isPushed); - break; } + break; case toggleSlowMotion: { if(!isPushed) break; viewController.inputView.toggleAltSpeedMode(AltSpeedMode::slow); - break; } + break; case rewind: { if(!isPushed) break; if(app.rewindManager.maxStates) + { app.rewindManager.rewindState(app); + } else + { + auto suspendCtx = app.suspendEmulationThread(); app.postMessage(3, false, "Please set rewind states in Optionsâž”System"); - break; + } } + break; case softReset: { if(!isPushed) break; - app.syncEmulationThread(); + auto suspendCtx = app.suspendEmulationThread(); system.reset(app, EmuSystem::ResetMode::SOFT); - break; } + break; case hardReset: { if(!isPushed) break; - app.syncEmulationThread(); + auto suspendCtx = app.suspendEmulationThread(); system.reset(app, EmuSystem::ResetMode::HARD); - break; } + break; case resetMenu: { if(!isPushed) break; viewController.pushAndShowModal(resetAlertView(app.attachParams(), app), srcEvent, false); - break; } + break; } return false; } @@ -252,7 +251,7 @@ void InputManager::updateInputDevices(ApplicationContext ctx) for(auto &devPtr : ctx.inputDevices()) { log.info("input device:{}, id:{}, map:{}", devPtr->name(), devPtr->enumId(), (int)devPtr->map()); - auto &appData = devPtr->makeAppData(*this, *devPtr); + devPtr->makeAppData(*this, *devPtr); } vController.setPhysicalControlsPresent(ctx.keyInputIsPresent()); onUpdateDevices.callCopySafe(); @@ -404,7 +403,7 @@ bool InputManager::readCustomKeyConfig(MapIO &io) bool InputManager::readSavedInputDevices(MapIO &io) { auto confs = io.get(); - for(auto confIdx : iotaCount(confs)) + for([[maybe_unused]] auto confIdx : iotaCount(confs)) { InputDeviceSavedConfig devConf; auto enumIdWithFlags = io.get(); @@ -428,7 +427,7 @@ bool InputManager::readSavedInputDevices(MapIO &io) log.error("unexpected 0 length device name"); return false; } - auto keyConfMap = Input::validateMap(io.get()); + [[maybe_unused]] auto keyConfMap = Input::validateMap(io.get()); readSizedData(io, devConf.keyConfName); if(!find(savedDevConfigs, [&](const auto &confPtr){ return *confPtr == devConf;})) { @@ -506,7 +505,7 @@ bool InputManager::readInputDeviceSessionConfigs(ApplicationContext ctx, MapIO & { savedSessionDevConfigs.clear(); auto confs = io.get(); - for(auto confIdx : iotaCount(confs)) + for([[maybe_unused]] auto confIdx : iotaCount(confs)) { InputDeviceSavedSessionConfig devConf; devConf.enumId = io.get(); diff --git a/EmuFramework/src/EmuOptions.cc b/EmuFramework/src/EmuOptions.cc index 9156c121b..b6f7f59d6 100644 --- a/EmuFramework/src/EmuOptions.cc +++ b/EmuFramework/src/EmuOptions.cc @@ -36,7 +36,7 @@ namespace EmuEx constexpr SystemLogger log{"App"}; -void EmuApp::initOptions(IG::ApplicationContext ctx) +void EmuApp::initOptions([[maybe_unused]] IG::ApplicationContext ctx) { #ifdef CONFIG_OS_IOS if(ctx.deviceIsIPad()) diff --git a/EmuFramework/src/EmuSystem.cc b/EmuFramework/src/EmuSystem.cc index 76efa6580..a445b3726 100644 --- a/EmuFramework/src/EmuSystem.cc +++ b/EmuFramework/src/EmuSystem.cc @@ -323,7 +323,7 @@ void EmuSystem::start(EmuApp &app) SteadyClockTime EmuSystem::benchmark(EmuVideo &video) { auto before = SteadyClock::now(); - for(auto i : iotaCount(180)) + for([[maybe_unused]] auto i : iotaCount(180)) { runFrame({}, &video, nullptr); } @@ -366,7 +366,7 @@ int EmuSystem::updateAudioFramesPerVideoFrame() return wholeFrames; } -[[gnu::weak]] FS::PathString EmuSystem::willLoadContentFromPath(std::string_view path, std::string_view displayName) +[[gnu::weak]] FS::PathString EmuSystem::willLoadContentFromPath(std::string_view, std::string_view) { return {}; } diff --git a/EmuFramework/src/EmuSystemTask.cc b/EmuFramework/src/EmuSystemTask.cc index 1f912dd28..ae4208ce5 100644 --- a/EmuFramework/src/EmuSystemTask.cc +++ b/EmuFramework/src/EmuSystemTask.cc @@ -27,47 +27,51 @@ constexpr SystemLogger log{"EmuSystemTask"}; EmuSystemTask::EmuSystemTask(EmuApp &app): app{app} {} -using FrameParamsCommand = EmuSystemTask::FrameParamsCommand; -using PauseCommand = EmuSystemTask::PauseCommand; -using ExitCommand = EmuSystemTask::ExitCommand; - -void EmuSystemTask::start() +void EmuSystemTask::start(Window& win) { if(taskThread.joinable()) return; + win.setDrawEventPriority(Window::drawEventPriorityLocked); // block UI from posting draws + winPtr = &win; taskThread = makeThreadSync( [this](auto &sem) { threadId_ = thisThreadId(); auto eventLoop = EventLoop::makeForThread(); + winPtr->setFrameEventsOnThisThread(); + app.addOnFrameDelayed(); bool started = true; commandPort.attach(eventLoop, [this, &started](auto msgs) { - std::binary_semaphore *syncSemPtr{}; for(auto msg : msgs) { bool threadIsRunning = msg.command.visit(overloaded { - [&](FrameParamsCommand &cmd) + [&](SetWindowCommand &cmd) { - frameParams = cmd.params; - return true; - }, - [&](FramePresentedCommand &cmd) - { - framePending = false; - return true; - }, - [&](PauseCommand &) - { - //log.debug("got pause command"); + //log.debug("got set window command"); + cmd.winPtr->moveOnFrame(*winPtr, app.system().onFrameUpdate, app.frameTimeSource); + winPtr = cmd.winPtr; assumeExpr(msg.semPtr); - syncSemPtr = msg.semPtr; + msg.semPtr->release(); + suspendSem.acquire(); + return true; + }, + [&](SuspendCommand &) + { + //log.debug("got suspend command"); + isSuspended = true; + assumeExpr(msg.semPtr); + msg.semPtr->release(); + suspendSem.acquire(); return true; }, [&](ExitCommand &) { started = false; + app.removeOnFrame(); + winPtr->removeFrameEvents(); + threadId_ = 0; EventLoop::forThread().stop(); return false; }, @@ -75,32 +79,6 @@ void EmuSystemTask::start() if(!threadIsRunning) return false; } - if(hasTime(frameParams.timestamp)) - { - if(!framePending) - { - auto params = std::exchange(frameParams, {}); - bool renderingFrame = app.advanceFrames(params, this); - if(params.isFromRenderer()) - { - framePending = false; - if(!renderingFrame) - { - app.emuWindow().postDraw(1); - } - } - } - else - { - log.debug("previous async frame not ready yet"); - doIfUsed(app.frameTimeStats, [&](auto &stats) { stats.missedFrameCallbacks++; }); - } - } - if(syncSemPtr) - { - framePending = false; - syncSemPtr->release(); - } return true; }); sem.release(); @@ -111,44 +89,50 @@ void EmuSystemTask::start() }); } -void EmuSystemTask::pause() +EmuSystemTask::SuspendContext EmuSystemTask::setWindow(Window& win) { + assert(!isSuspended); if(!taskThread.joinable()) - return; - commandPort.send({.command = PauseCommand{}}, MessageReplyMode::wait); + return {}; + auto oldWinPtr = winPtr; + commandPort.send({.command = SetWindowCommand{&win}}, MessageReplyMode::wait); + oldWinPtr->setFrameEventsOnThisThread(); + oldWinPtr->setDrawEventPriority(); // allow UI to post draws again app.flushMainThreadMessages(); + return {this}; +} + +EmuSystemTask::SuspendContext EmuSystemTask::suspend() +{ + if(!taskThread.joinable() || isSuspended) + return {}; + commandPort.send({.command = SuspendCommand{}}, MessageReplyMode::wait); + app.flushMainThreadMessages(); + return {this}; +} + +void EmuSystemTask::resume() +{ + if(!taskThread.joinable() || !isSuspended) + return; + suspendSem.release(); } void EmuSystemTask::stop() { if(!taskThread.joinable()) return; + assert(threadId_ != thisThreadId()); commandPort.send({.command = ExitCommand{}}); taskThread.join(); - threadId_ = 0; + winPtr->setFrameEventsOnThisThread(); + winPtr->setDrawEventPriority(); // allow UI to post draws again app.flushMainThreadMessages(); } -void EmuSystemTask::updateFrameParams(FrameParams params) -{ - if(!taskThread.joinable()) [[unlikely]] - return; - commandPort.send({.command = FrameParamsCommand{params}}); -} - -void EmuSystemTask::notifyFramePresented() -{ - if(!taskThread.joinable()) [[unlikely]] - return; - commandPort.send({.command = FramePresentedCommand{}}); -} - void EmuSystemTask::sendVideoFormatChangedReply(EmuVideo &video) { - app.runOnMainThread([&video](ApplicationContext) - { - video.dispatchFormatChanged(); - }); + video.dispatchFormatChanged(); } void EmuSystemTask::sendFrameFinishedReply(EmuVideo &video) @@ -158,7 +142,7 @@ void EmuSystemTask::sendFrameFinishedReply(EmuVideo &video) void EmuSystemTask::sendScreenshotReply(bool success) { - app.runOnMainThread([&app = app, success](ApplicationContext ctx) + app.runOnMainThread([&app = app, success](ApplicationContext) { app.printScreenshotResult(success); }); diff --git a/EmuFramework/src/EmuTiming.cc b/EmuFramework/src/EmuTiming.cc index 99d782d53..c45975e8c 100644 --- a/EmuFramework/src/EmuTiming.cc +++ b/EmuFramework/src/EmuTiming.cc @@ -28,7 +28,7 @@ EmuFrameTimeInfo EmuTiming::advanceFrames(FrameParams params) { auto frameTimeDiff = params.timestamp - lastFrameTimestamp_; auto framesDiff = params.elapsedFrames(lastFrameTimestamp_); - auto lastTimestamp = std::exchange(lastFrameTimestamp_, params.timestamp); + std::exchange(lastFrameTimestamp_, params.timestamp); if(exactFrameDivisor > 0) { savedAdvancedFrames += framesDiff; @@ -52,7 +52,7 @@ EmuFrameTimeInfo EmuTiming::advanceFrames(FrameParams params) } assumeExpr(timePerVideoFrame.count() > 0); assumeExpr(startFrameTime.time_since_epoch().count() > 0); - assumeExpr(params.timestamp > startFrameTime); + assumeExpr(params.timestamp >= startFrameTime); auto timeTotal = params.timestamp - startFrameTime; auto now = divRoundClosestPositive(timeTotal.count(), timePerVideoFrame.count()); int elapsedFrames = now - lastFrame; diff --git a/EmuFramework/src/EmuVideo.cc b/EmuFramework/src/EmuVideo.cc index b2be43cec..f1b8701b6 100644 --- a/EmuFramework/src/EmuVideo.cc +++ b/EmuFramework/src/EmuVideo.cc @@ -151,7 +151,6 @@ void EmuVideo::finishFrame(EmuSystemTaskContext taskCtx, Gfx::LockedTextureBuffe { doScreenshot(taskCtx, texBuff.pixmap()); } - app().record(FrameTimeStatEvent::aboutToSubmitFrame); vidImg.unlock(texBuff); postFrameFinished(taskCtx); } @@ -162,7 +161,6 @@ void EmuVideo::finishFrame(EmuSystemTaskContext taskCtx, IG::PixmapView pix) { doScreenshot(taskCtx, pix); } - app().record(FrameTimeStatEvent::aboutToSubmitFrame); vidImg.write(pix, {.async = true}); postFrameFinished(taskCtx); } diff --git a/EmuFramework/src/InputDeviceData.hh b/EmuFramework/src/InputDeviceData.hh index c64ddb427..d815df361 100644 --- a/EmuFramework/src/InputDeviceData.hh +++ b/EmuFramework/src/InputDeviceData.hh @@ -46,7 +46,7 @@ struct InputDeviceData bool keysArePushed(MappedKeys); }; -static InputDeviceData& inputDevData(const Input::Device &d) +inline InputDeviceData& inputDevData(const Input::Device& d) { return *d.appData(); } diff --git a/EmuFramework/src/KeyConfig.cc b/EmuFramework/src/KeyConfig.cc index 785d058aa..1351a3aed 100644 --- a/EmuFramework/src/KeyConfig.cc +++ b/EmuFramework/src/KeyConfig.cc @@ -33,7 +33,7 @@ KeyConfig KeyConfig::readConfig(MapIO &io) readSizedData(io, keyConf.name); auto mappings = io.get(); keyConf.keyMap.reserve(mappings); - for(auto mappingIdx : iotaCount(mappings)) + for([[maybe_unused]] auto mappingIdx : iotaCount(mappings)) { KeyMapping m; io.read(m.key.codes.data(), m.key.codes.capacity()); @@ -86,7 +86,7 @@ void KeyConfig::set(KeyInfo key, MappedKeys mapKey) { if(!mapKey[0]) { - std::ranges::remove_if(keyMap, [&](auto &val){ return val.key == key; }); + std::erase_if(keyMap, [&](auto &val){ return val.key == key; }); return; } if(auto it = find(key); diff --git a/EmuFramework/src/RewindManager.cc b/EmuFramework/src/RewindManager.cc index 007693e19..1bc78e663 100644 --- a/EmuFramework/src/RewindManager.cc +++ b/EmuFramework/src/RewindManager.cc @@ -29,8 +29,8 @@ RewindManager::RewindManager(EmuApp &app): saveTimer { defaultSaveFreq, - "RewindManager::saveStateTimer", - [this, &app]() + {.debugLabel = "RewindManager::saveStateTimer"}, + [this, &app] { //log.debug("running rewind save state timer"); saveState(app); diff --git a/EmuFramework/src/VideoImageEffect.cc b/EmuFramework/src/VideoImageEffect.cc index adc1d97fe..b2e6d634a 100644 --- a/EmuFramework/src/VideoImageEffect.cc +++ b/EmuFramework/src/VideoImageEffect.cc @@ -193,7 +193,7 @@ void VideoImageEffect::compileEffect(Gfx::Renderer &r, EffectDesc desc, bool use updateProgramUniforms(r); } -void VideoImageEffect::updateProgramUniforms(Gfx::Renderer &r) +void VideoImageEffect::updateProgramUniforms(Gfx::Renderer&) { if(srcTexelDeltaU != -1) prog.uniform(srcTexelDeltaU, 1.0f / (float)inputImgSize.x, 1.0f / (float)inputImgSize.y); diff --git a/EmuFramework/src/gui/AudioOptionView.cc b/EmuFramework/src/gui/AudioOptionView.cc index ca33acae3..d7ec13dbe 100644 --- a/EmuFramework/src/gui/AudioOptionView.cc +++ b/EmuFramework/src/gui/AudioOptionView.cc @@ -68,7 +68,7 @@ AudioOptionView::AudioOptionView(ViewAttachParams attach, EmuAudio& audio_, bool MenuId{audio_.maxVolume()}, soundVolumeItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}%", audio.maxVolume())); return true; diff --git a/EmuFramework/src/gui/BundledGamesView.cc b/EmuFramework/src/gui/BundledGamesView.cc index 564883dd5..ccde9bec1 100644 --- a/EmuFramework/src/gui/BundledGamesView.cc +++ b/EmuFramework/src/gui/BundledGamesView.cc @@ -54,7 +54,7 @@ BundledGamesView::BundledGamesView(ViewAttachParams attach): } } {} -[[gnu::weak]] const BundledGameInfo &EmuSystem::bundledGameInfo(int idx) const +[[gnu::weak]] const BundledGameInfo &EmuSystem::bundledGameInfo(int) const { static const BundledGameInfo info[] { diff --git a/EmuFramework/src/gui/ButtonConfigView.cc b/EmuFramework/src/gui/ButtonConfigView.cc index dcfd48e19..9f346045f 100644 --- a/EmuFramework/src/gui/ButtonConfigView.cc +++ b/EmuFramework/src/gui/ButtonConfigView.cc @@ -52,8 +52,8 @@ ButtonConfigView::ButtonConfigView(ViewAttachParams attach, InputManagerView &ro { return msg.visit(overloaded { - [&](const ItemsMessage &m) -> ItemReply { return resetItemsSize + cat.keys.size(); }, - [&](const GetItemMessage &m) -> ItemReply + [&](const ItemsMessage&) -> ItemReply { return resetItemsSize + cat.keys.size(); }, + [&](const GetItemMessage& m) -> ItemReply { if(m.idx == 0) return &resetDefaults; diff --git a/EmuFramework/src/gui/Cheats.cc b/EmuFramework/src/gui/Cheats.cc index a2272ead5..eb50c7ebd 100644 --- a/EmuFramework/src/gui/Cheats.cc +++ b/EmuFramework/src/gui/Cheats.cc @@ -29,8 +29,8 @@ BaseCheatsView::BaseCheatsView(ViewAttachParams attach): { return msg.visit(overloaded { - [&](const ItemsMessage &m) -> ItemReply { return 1 + cheat.size(); }, - [&](const GetItemMessage &m) -> ItemReply + [&](const ItemsMessage&) -> ItemReply { return 1 + cheat.size(); }, + [&](const GetItemMessage& m) -> ItemReply { if(m.idx == 0) return &edit; diff --git a/EmuFramework/src/gui/EmuInputView.cc b/EmuFramework/src/gui/EmuInputView.cc index c56333a87..716065515 100644 --- a/EmuFramework/src/gui/EmuInputView.cc +++ b/EmuFramework/src/gui/EmuInputView.cc @@ -88,7 +88,6 @@ bool EmuInputView::inputEvent(const Input::Event& e, ViewInputEventParams) if(vController->keyInput(keyEv)) return true; auto &emuApp = app(); - auto &sys = emuApp.system(); auto &devData = inputDevData(*keyEv.device()); const auto &actionTable = devData.actionTable; if(!actionTable.size()) [[unlikely]] diff --git a/EmuFramework/src/gui/EmuView.cc b/EmuFramework/src/gui/EmuView.cc index b87581856..ca9cf1f8f 100644 --- a/EmuFramework/src/gui/EmuView.cc +++ b/EmuFramework/src/gui/EmuView.cc @@ -33,7 +33,7 @@ EmuView::EmuView(ViewAttachParams attach, EmuVideoLayer *layer, EmuSystem &sys): void EmuView::prepareDraw() { - doIfUsed(frameTimeStats, [&](auto &stats){ stats.text.makeGlyphs(); }); + doIfUsed(frameTimeStats, [&](auto &stats){ stats.text.makeGlyphs(); stats.text.face()->precacheAlphaNum(renderer()); }); #ifdef CONFIG_EMUFRAMEWORK_AUDIO_STATS audioStatsText.makeGlyphs(renderer()); #endif @@ -114,33 +114,27 @@ void EmuView::updateFrameTimeStats(FrameTimeStats stats, SteadyClockTimePoint cu auto deadline = duration_cast(screen()->presentationDeadline()); auto timestampDiff = duration_cast(currentFrameTimestamp - stats.startOfFrame); auto callbackOverhead = duration_cast(stats.startOfEmulation - stats.startOfFrame); - auto emulationTime = duration_cast(stats.aboutToSubmitFrame - stats.startOfEmulation); - auto submitFrameTime = duration_cast(stats.aboutToPostDraw - stats.aboutToSubmitFrame); - auto postDrawTime = duration_cast(stats.startOfDraw - stats.aboutToPostDraw); - auto drawTime = duration_cast(stats.aboutToPresent - stats.startOfDraw); - auto presentTime = duration_cast(stats.endOfDraw - stats.aboutToPresent); - auto frameTime = duration_cast(stats.endOfDraw - stats.startOfFrame); + auto emulationTime = duration_cast(stats.waitForPresent - stats.startOfEmulation); + auto presentTime = duration_cast(stats.endOfFrame - stats.waitForPresent); + auto frameTime = duration_cast(stats.endOfFrame - stats.startOfFrame); doIfUsed(frameTimeStats, [&](auto &statsUI) { statsUI.text.resetString(std::format("Frame Time Stats\n\n" - "Screen Frame Time: {}ms\n" - "Deadline: {}ms\n" - "Timestamp Diff: {}ms\n" - "Frame Callback: {}ms\n" - "Emulate: {}ms\n" - "Submit Frame: {}ms\n" - "Draw Callback: {}ms\n" - "Draw: {}ms\n" - "Present: {}ms\n" - "Total: {}ms\n" + "Screen Frame Time: {}\n" + "Deadline: {}\n" + "Timestamp Diff: {}\n" + "Frame Callback: {}\n" + "Emulate: {}\n" + "Present: {}\n" + "Total: {}\n" "Missed Callbacks: {}", - screenFrameTime.count(), deadline.count(), timestampDiff.count(), callbackOverhead.count(), emulationTime.count(), submitFrameTime.count(), - postDrawTime.count(), drawTime.count(), presentTime.count(), frameTime.count(), stats.missedFrameCallbacks)); + screenFrameTime, deadline, timestampDiff, callbackOverhead, emulationTime, + presentTime, frameTime, stats.missedFrameCallbacks)); placeFrameTimeStats(); }); } -void EmuView::updateAudioStats(int underruns, int overruns, int callbacks, double avgCallbackFrames, int frames) +void EmuView::updateAudioStats([[maybe_unused]] int underruns, [[maybe_unused]] int overruns, [[maybe_unused]] int callbacks, [[maybe_unused]] double avgCallbackFrames, [[maybe_unused]] int frames) { #ifdef CONFIG_EMUFRAMEWORK_AUDIO_STATS audioStatsText.setString(std::format("Underruns:{}\nOverruns:{}\nCallbacks per second:{}\nFrames per callback:{:g}\nTotal frames:{}", diff --git a/EmuFramework/src/gui/EmuViewController.cc b/EmuFramework/src/gui/EmuViewController.cc index 90d11ecd6..6772a3c00 100644 --- a/EmuFramework/src/gui/EmuViewController.cc +++ b/EmuFramework/src/gui/EmuViewController.cc @@ -46,9 +46,7 @@ EmuViewController::EmuViewController(ViewAttachParams viewAttach, viewStack{viewAttach, app()} { inputView.setController(this); - auto &win = viewAttach.window; auto &face = viewAttach.viewManager.defaultFace; - auto &screen = *viewAttach.window.screen(); { auto viewNav = std::make_unique ( @@ -353,9 +351,14 @@ void EmuViewController::prepareDraw() viewStack.prepareDraw(); } +static Gfx::DrawAsyncMode drawAsyncMode(bool showingEmulation) +{ + return showingEmulation ? Gfx::DrawAsyncMode::FULL : Gfx::DrawAsyncMode::AUTO; +} + bool EmuViewController::drawMainWindow(IG::Window &win, IG::WindowDrawParams params, Gfx::RendererTask &task) { - return task.draw(win, params, {}, + return task.draw(win, params, {.asyncMode = drawAsyncMode(showingEmulation)}, [this, isBlankFrame = std::exchange(drawBlankFrame, {})](IG::Window &win, Gfx::RendererCommands &cmds) { auto &winData = windowData(win); @@ -371,9 +374,7 @@ bool EmuViewController::drawMainWindow(IG::Window &win, IG::WindowDrawParams par emuView.drawframeTimeStatsText(cmds); if(winData.hasPopup) popup.draw(cmds); - app().record(FrameTimeStatEvent::aboutToPresent); cmds.present(presentTime); - app().record(FrameTimeStatEvent::endOfDraw); app().notifyWindowPresented(); } else @@ -392,7 +393,7 @@ bool EmuViewController::drawMainWindow(IG::Window &win, IG::WindowDrawParams par bool EmuViewController::drawExtraWindow(IG::Window &win, IG::WindowDrawParams params, Gfx::RendererTask &task) { - return task.draw(win, params, {}, + return task.draw(win, params, {.asyncMode = drawAsyncMode(showingEmulation)}, [this](IG::Window &win, Gfx::RendererCommands &cmds) { auto &winData = windowData(win); diff --git a/EmuFramework/src/gui/FilePathOptionView.cc b/EmuFramework/src/gui/FilePathOptionView.cc index 117d4fb14..371a76acc 100644 --- a/EmuFramework/src/gui/FilePathOptionView.cc +++ b/EmuFramework/src/gui/FilePathOptionView.cc @@ -72,7 +72,7 @@ FilePathOptionView::FilePathOptionView(ViewAttachParams attach, bool customMenu) fPicker->setPath(userSavePath.size() && userSavePath != optionSavePathDefaultToken ? userSavePath : app().contentSearchPath, e); fPicker->setOnSelectPath( - [this](FSPicker &picker, CStringView path, std::string_view displayName, const Input::Event &e) + [this](FSPicker &picker, CStringView path, [[maybe_unused]] std::string_view displayName, const Input::Event&) { if(!hasWriteAccessToDir(path)) { @@ -102,7 +102,7 @@ FilePathOptionView::FilePathOptionView(ViewAttachParams attach, bool customMenu) view.dismiss(); }); multiChoiceView->appendItem("Legacy Game Data Folder", - [this](View &view, const Input::Event &e) + [this](View&, const Input::Event &e) { pushAndShowModal(makeView( std::format("Please select the \"Game Data/{}\" folder from an old version of the app to use its existing saves " @@ -114,7 +114,7 @@ FilePathOptionView::FilePathOptionView(ViewAttachParams attach, bool customMenu) auto fPicker = makeView(FSPicker::Mode::DIR, EmuSystem::NameFilterFunc{}, e); fPicker->setPath(""); fPicker->setOnSelectPath( - [this](FSPicker &picker, CStringView path, std::string_view displayName, const Input::Event &e) + [this](FSPicker &picker, CStringView path, [[maybe_unused]] std::string_view displayName, const Input::Event&) { auto ctx = appContext(); if(!hasWriteAccessToDir(path)) diff --git a/EmuFramework/src/gui/FilePicker.cc b/EmuFramework/src/gui/FilePicker.cc index d485ecf1f..30da8a673 100644 --- a/EmuFramework/src/gui/FilePicker.cc +++ b/EmuFramework/src/gui/FilePicker.cc @@ -33,7 +33,7 @@ FilePicker::FilePicker(ViewAttachParams attach, } {} FilePicker::FilePicker(ViewAttachParams attach, EmuApp &app, - FSPicker::Mode mode, EmuSystem::NameFilterFunc filter, const Input::Event &e, bool includeArchives): + FSPicker::Mode mode, EmuSystem::NameFilterFunc filter, const Input::Event&, bool includeArchives): FSPicker { attach, diff --git a/EmuFramework/src/gui/FrameTimingView.cc b/EmuFramework/src/gui/FrameTimingView.cc index bc01f532e..7dca69aac 100644 --- a/EmuFramework/src/gui/FrameTimingView.cc +++ b/EmuFramework/src/gui/FrameTimingView.cc @@ -148,7 +148,7 @@ public: } } - void onAddedToController(ViewController *, const Input::Event &e) final + void onAddedToController(ViewController*, const Input::Event&) final { lastFrameTimestamp = SteadyClock::now(); detectFrameRate = @@ -270,7 +270,7 @@ FrameTimingView::FrameTimingView(ViewAttachParams attach): app().outputTimingManager.frameTimeOptionAsMenuId(VideoSystem::NATIVE_NTSC), frameRateItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(makeFrameRateStr(VideoSystem::NATIVE_NTSC, app().outputTimingManager)); return true; @@ -288,7 +288,7 @@ FrameTimingView::FrameTimingView(ViewAttachParams attach): app().outputTimingManager.frameTimeOptionAsMenuId(VideoSystem::PAL), frameRateItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(makeFrameRateStr(VideoSystem::PAL, app().outputTimingManager)); return true; @@ -320,7 +320,7 @@ FrameTimingView::FrameTimingView(ViewAttachParams attach): frameClockItems, MultiChoiceMenuItem::Config { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(wise_enum::to_string(app().effectiveFrameTimeSource())); return true; @@ -345,7 +345,7 @@ FrameTimingView::FrameTimingView(ViewAttachParams attach): presentModeItems, MultiChoiceMenuItem::Config { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(renderer().evalPresentMode(app().emuWindow(), app().presentMode) == Gfx::PresentMode::FIFO ? "Queued" : "Immediate"); return true; @@ -387,7 +387,7 @@ FrameTimingView::FrameTimingView(ViewAttachParams attach): presentationTimeItems, MultiChoiceMenuItem::Config { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { if(app().presentationTimeMode == PresentationTimeMode::off) return false; diff --git a/EmuFramework/src/gui/GUIOptionView.cc b/EmuFramework/src/gui/GUIOptionView.cc index c5c36231f..bc3de9510 100644 --- a/EmuFramework/src/gui/GUIOptionView.cc +++ b/EmuFramework/src/gui/GUIOptionView.cc @@ -75,7 +75,7 @@ GUIOptionView::GUIOptionView(ViewAttachParams attach, bool customMenu): MenuId{app().fontSize}, fontSizeItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{:g}", app().fontSize / 1000.)); return true; diff --git a/EmuFramework/src/gui/InputManagerView.cc b/EmuFramework/src/gui/InputManagerView.cc index 679f03e00..c0cdd74dc 100644 --- a/EmuFramework/src/gui/InputManagerView.cc +++ b/EmuFramework/src/gui/InputManagerView.cc @@ -161,7 +161,7 @@ InputManagerView::InputManagerView(ViewAttachParams attach, rescanOSDevices { "Re-scan OS Input Devices", attach, - [this](const Input::Event &e) + [this] { appContext().enumInputDevices(); int devices = 0; @@ -552,7 +552,7 @@ InputManagerDeviceView::InputManagerDeviceView(UTF16String name, ViewAttachParam { "Handle Unbound Keys", attach, inputDevData(dev).devConf.shouldHandleUnboundKeys, - [this](BoolMenuItem &item, const Input::Event &e) + [this](BoolMenuItem& item) { devConf.shouldHandleUnboundKeys = item.flipBoolValue(*this); devConf.save(inputManager); @@ -562,7 +562,7 @@ InputManagerDeviceView::InputManagerDeviceView(UTF16String name, ViewAttachParam { "Stick 1 as D-Pad", attach, inputDevData(dev).devConf.joystickAxesAsKeys(Input::AxisSetId::stick1), - [this](BoolMenuItem &item, const Input::Event &e) + [this](BoolMenuItem& item) { devConf.setJoystickAxesAsKeys(Input::AxisSetId::stick1, item.flipBoolValue(*this)); devConf.save(inputManager); @@ -572,7 +572,7 @@ InputManagerDeviceView::InputManagerDeviceView(UTF16String name, ViewAttachParam { "Stick 2 as D-Pad", attach, inputDevData(dev).devConf.joystickAxesAsKeys(Input::AxisSetId::stick2), - [this](BoolMenuItem &item, const Input::Event &e) + [this](BoolMenuItem& item) { devConf.setJoystickAxesAsKeys(Input::AxisSetId::stick2, item.flipBoolValue(*this)); devConf.save(inputManager); @@ -582,7 +582,7 @@ InputManagerDeviceView::InputManagerDeviceView(UTF16String name, ViewAttachParam { "POV Hat as D-Pad", attach, inputDevData(dev).devConf.joystickAxesAsKeys(Input::AxisSetId::hat), - [this](BoolMenuItem &item, const Input::Event &e) + [this](BoolMenuItem& item) { devConf.setJoystickAxesAsKeys(Input::AxisSetId::hat, item.flipBoolValue(*this)); devConf.save(inputManager); @@ -592,7 +592,7 @@ InputManagerDeviceView::InputManagerDeviceView(UTF16String name, ViewAttachParam { "L/R Triggers as L2/R2", attach, inputDevData(dev).devConf.joystickAxesAsKeys(Input::AxisSetId::triggers), - [this](BoolMenuItem &item, const Input::Event &e) + [this](BoolMenuItem& item) { devConf.setJoystickAxesAsKeys(Input::AxisSetId::triggers, item.flipBoolValue(*this)); devConf.save(inputManager); @@ -602,7 +602,7 @@ InputManagerDeviceView::InputManagerDeviceView(UTF16String name, ViewAttachParam { "Brake/Gas as L2/R2", attach, inputDevData(dev).devConf.joystickAxesAsKeys(Input::AxisSetId::pedals), - [this](BoolMenuItem &item, const Input::Event &e) + [this](BoolMenuItem& item) { devConf.setJoystickAxesAsKeys(Input::AxisSetId::pedals, item.flipBoolValue(*this)); devConf.save(inputManager); diff --git a/EmuFramework/src/gui/MainMenuView.cc b/EmuFramework/src/gui/MainMenuView.cc index f65c601ae..6663f0f63 100644 --- a/EmuFramework/src/gui/MainMenuView.cc +++ b/EmuFramework/src/gui/MainMenuView.cc @@ -49,7 +49,7 @@ protected: static void onScanStatus(EmuApp &app, BluetoothScanState status, int arg); template -static void handledFailedBTAdapterInit(ViewT &view, ViewAttachParams attach, const Input::Event &e) +static void handledFailedBTAdapterInit(ViewT& view, [[maybe_unused]] ViewAttachParams attach, [[maybe_unused]] const Input::Event& e) { view.app().postErrorMessage("Unable to initialize Bluetooth adapter"); #ifdef CONFIG_BLUETOOTH_BTSTACK @@ -186,7 +186,7 @@ MainMenuView::MainMenuView(ViewAttachParams attach, bool customMenu): { app().postMessage(4, "Prepare to push the PS button"); auto startedScan = Bluetooth::listenForDevices(appContext(), app().bluetoothAdapter, - [this](BluetoothAdapter &bta, BluetoothScanState status, int arg) + [this](BluetoothAdapter&, BluetoothScanState status, int arg) { switch(status) { @@ -348,8 +348,8 @@ OptionCategoryView::OptionCategoryView(ViewAttachParams attach): { return msg.visit(overloaded { - [&](const ItemsMessage &m) -> ItemReply { return EmuApp::hasGooglePlayStoreFeatures() ? std::size(subConfig) : std::size(subConfig)-1; }, - [&](const GetItemMessage &m) -> ItemReply { return &subConfig[m.idx]; }, + [&](const ItemsMessage&) -> ItemReply { return EmuApp::hasGooglePlayStoreFeatures() ? std::size(subConfig) : std::size(subConfig)-1; }, + [&](const GetItemMessage& m) -> ItemReply { return &subConfig[m.idx]; }, }); } }, diff --git a/EmuFramework/src/gui/PlaceVControlsView.cc b/EmuFramework/src/gui/PlaceVControlsView.cc index 7018a78ee..5385904de 100644 --- a/EmuFramework/src/gui/PlaceVControlsView.cc +++ b/EmuFramework/src/gui/PlaceVControlsView.cc @@ -22,7 +22,7 @@ namespace EmuEx { -constexpr SystemLogger log{"PlaceVControlsView"}; +[[maybe_unused]] constexpr SystemLogger log{"PlaceVControlsView"}; constexpr std::array snapPxSizes{0, 2, 4, 8, 16, 32, 64}; PlaceVControlsView::PlaceVControlsView(ViewAttachParams attach, VController &vController_): diff --git a/EmuFramework/src/gui/RecentContentView.cc b/EmuFramework/src/gui/RecentContentView.cc index c52d8b11e..b8c6363db 100644 --- a/EmuFramework/src/gui/RecentContentView.cc +++ b/EmuFramework/src/gui/RecentContentView.cc @@ -30,8 +30,8 @@ RecentContentView::RecentContentView(ViewAttachParams attach, RecentContent &rec { return msg.visit(overloaded { - [&](const ItemsMessage &m) -> ItemReply { return 1 + recentItems.size(); }, - [&](const GetItemMessage &m) -> ItemReply { return m.idx < recentItems.size() ? &recentItems[m.idx] : &clear; }, + [&](const ItemsMessage&) -> ItemReply { return 1 + recentItems.size(); }, + [&](const GetItemMessage& m) -> ItemReply { return m.idx < recentItems.size() ? &recentItems[m.idx] : &clear; }, }); } }, @@ -56,7 +56,7 @@ RecentContentView::RecentContentView(ViewAttachParams attach, RecentContent &rec recentItems.reserve(recentContent_.size()); for(auto &entry : recentContent_) { - auto &recentItem = recentItems.emplace_back(entry.name, attach, + recentItems.emplace_back(entry.name, attach, [this, &entry](const Input::Event &e) { app().createSystemWithMedia({}, entry.path, appContext().fileUriDisplayName(entry.path), e, {}, attachParams(), diff --git a/EmuFramework/src/gui/ResetAlertView.hh b/EmuFramework/src/gui/ResetAlertView.hh index 87ac82844..b5018be77 100644 --- a/EmuFramework/src/gui/ResetAlertView.hh +++ b/EmuFramework/src/gui/ResetAlertView.hh @@ -30,7 +30,7 @@ public: TextMenuItem { "Soft Reset", attach, - [this, &app]() + [&app]() { app.system().reset(app, EmuSystem::ResetMode::SOFT); app.showEmulation(); @@ -39,7 +39,7 @@ public: TextMenuItem { "Hard Reset", attach, - [this, &app]() + [&app]() { app.system().reset(app, EmuSystem::ResetMode::HARD); app.showEmulation(); diff --git a/EmuFramework/src/gui/StateSlotView.cc b/EmuFramework/src/gui/StateSlotView.cc index 2f112af5e..0c2b15718 100644 --- a/EmuFramework/src/gui/StateSlotView.cc +++ b/EmuFramework/src/gui/StateSlotView.cc @@ -98,7 +98,7 @@ void StateSlotView::refreshSlot(int slot) return std::format("{}", sys.stateSlotName(slot)); }; auto &s = stateSlot[slot]; - s = {str(), attachParams(), [this, slot](View &view) + s = {str(), attachParams(), [this, slot](View&) { auto &sys = system(); stateSlot[sys.stateSlot()].setHighlighted(false); @@ -125,7 +125,7 @@ void StateSlotView::refreshSlots() void StateSlotView::doSaveState() { auto slot = system().stateSlot(); - if(app().saveStateWithSlot(slot)) + if(app().saveStateWithSlot(slot, false)) app().showEmulation(); refreshSlot(slot); place(); diff --git a/EmuFramework/src/gui/SystemOptionView.cc b/EmuFramework/src/gui/SystemOptionView.cc index 2bf8fbc07..e289d7d24 100644 --- a/EmuFramework/src/gui/SystemOptionView.cc +++ b/EmuFramework/src/gui/SystemOptionView.cc @@ -50,7 +50,7 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): }, autosaveTimer { - "Autosave Timer", attach, + "Timer", attach, MenuId{app().autosaveManager.saveTimer.frequency.count()}, autosaveTimerItem, { @@ -73,7 +73,7 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): }, autosaveLaunch { - "Autosave Launch Mode", attach, + "Launch Mode", attach, MenuId{app().autosaveManager.autosaveLaunchMode}, autosaveLaunchItem, { @@ -82,7 +82,7 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): }, autosaveContent { - "Autosave Content", attach, + "Content", attach, app().autosaveManager.saveOnlyBackupMemory, "State & Backup RAM", "Only Backup RAM", [this](BoolMenuItem &item) @@ -128,7 +128,7 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): MenuId{app().altSpeed(AltSpeedMode::fast)}, fastModeSpeedItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{:g}x", app().altSpeedAsDouble(AltSpeedMode::fast))); return true; @@ -169,7 +169,7 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): MenuId{app().altSpeed(AltSpeedMode::slow)}, slowModeSpeedItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{:g}x", app().altSpeedAsDouble(AltSpeedMode::slow))); return true; @@ -199,11 +199,11 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): }, rewindStates { - "Rewind States", attach, + "States", attach, MenuId{app().rewindManager.maxStates}, rewindStatesItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}", app().rewindManager.maxStates)); return true; @@ -213,7 +213,7 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): }, rewindTimeInterval { - "Rewind State Interval (Seconds)", std::to_string(app().rewindManager.saveTimer.frequency.count()), attach, + "State Interval (Seconds)", std::to_string(app().rewindManager.saveTimer.frequency.count()), attach, [this](const Input::Event &e) { pushAndShowNewCollectValueRangeInputView(attachParams(), e, @@ -252,7 +252,10 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): { pushAndShow(makeView(appContext().cpuCount()), e); } - } + }, + autosaveHeading{"Autosave Options", attach}, + rewindHeading{"Rewind Options", attach}, + otherHeading{"Other Options", attach} { if(!customMenu) { @@ -262,14 +265,17 @@ SystemOptionView::SystemOptionView(ViewAttachParams attach, bool customMenu): void SystemOptionView::loadStockItems() { + item.emplace_back(&autosaveHeading); item.emplace_back(&autosaveLaunch); item.emplace_back(&autosaveTimer); item.emplace_back(&autosaveContent); + item.emplace_back(&rewindHeading); + item.emplace_back(&rewindStates); + item.emplace_back(&rewindTimeInterval); + item.emplace_back(&otherHeading); item.emplace_back(&confirmOverwriteState); item.emplace_back(&fastModeSpeed); item.emplace_back(&slowModeSpeed); - item.emplace_back(&rewindStates); - item.emplace_back(&rewindTimeInterval); if(used(performanceMode) && appContext().hasSustainedPerformanceMode()) item.emplace_back(&performanceMode); if(used(noopThread)) diff --git a/EmuFramework/src/gui/TouchConfigView.cc b/EmuFramework/src/gui/TouchConfigView.cc index 65c3ee110..753ea5e11 100644 --- a/EmuFramework/src/gui/TouchConfigView.cc +++ b/EmuFramework/src/gui/TouchConfigView.cc @@ -33,8 +33,6 @@ namespace EmuEx { -constexpr bool CAN_TURN_OFF_MENU_BTN = !Config::envIsIOS; - constexpr const char *ctrlStateStr[] { "Off", "On", "Hidden" @@ -50,7 +48,7 @@ constexpr int touchCtrlExtraBtnSizeMenuVal[4] 0, 10, 20, 30 }; -static void addCategories(EmuApp &app, VControllerElement &elem, auto &&addCategory) +static void addCategories(EmuApp&, VControllerElement &elem, auto &&addCategory) { if(elem.uiButtonGroup()) { @@ -100,7 +98,7 @@ public: MenuId{elem.dPad()->deadzone()}, deadzoneItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{:g}mm", elem.dPad()->deadzone() / 100.)); return true; @@ -139,7 +137,7 @@ public: MenuId{elem.dPad()->diagonalSensitivity() * 1000.f}, diagonalSensitivityItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{:g}%", 100.f - elem.dPad()->diagonalSensitivity() * 100.f)); return true; @@ -451,7 +449,7 @@ public: MenuId{elem.buttonGroup() ? elem.buttonGroup()->spacing() : 0}, spaceItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}mm", elem.buttonGroup()->spacing())); return true; @@ -590,7 +588,7 @@ public: for(auto &k : cat.keys) { multiChoiceView->appendItem(app.inputManager.toString(k), - [this, k](View &parentView, const Input::Event &e) + [this, k](View &parentView, const Input::Event&) { elem.add(k); vCtrl.update(elem); @@ -709,17 +707,17 @@ public: { buttons.emplace_back( c.name, attach, - [this, &c](const Input::Event &e){ add(c); }); + [this, &c]{ add(c); }); } buttons.emplace_back( rightUIComponents.name, attach, - [this](const Input::Event &e){ add(rightUIComponents); }); + [this]{ add(rightUIComponents); }); buttons.emplace_back( leftUIComponents.name, attach, - [this](const Input::Event &e){ add(leftUIComponents); }); + [this]{ add(leftUIComponents); }); buttons.emplace_back( rewindUIComponents.name, attach, - [this](const Input::Event &e){ add(rewindUIComponents); }); + [this]{ add(rewindUIComponents); }); } private: @@ -837,7 +835,7 @@ TouchConfigView::TouchConfigView(ViewAttachParams attach, VController &vCtrl): MenuId{vController.buttonSize()}, sizeItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{:g}mm", vController.buttonSize() / 100.)); return true; diff --git a/EmuFramework/src/gui/VideoOptionView.cc b/EmuFramework/src/gui/VideoOptionView.cc index 834057075..44f9bf994 100644 --- a/EmuFramework/src/gui/VideoOptionView.cc +++ b/EmuFramework/src/gui/VideoOptionView.cc @@ -28,7 +28,7 @@ namespace EmuEx { -constexpr SystemLogger log{"VideoOptionView"}; +[[maybe_unused]] constexpr SystemLogger log{"VideoOptionView"}; static const char *autoWindowPixelFormatStr(IG::ApplicationContext ctx) { @@ -171,7 +171,7 @@ VideoOptionView::VideoOptionView(ViewAttachParams attach, EmuVideoLayer &videoLa MenuId{videoLayer_.scale}, contentScaleItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { if(videoLayer.scale <= 200) { @@ -209,7 +209,7 @@ VideoOptionView::VideoOptionView(ViewAttachParams attach, EmuVideoLayer &videoLa MenuId{app().menuScale}, menuScaleItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}%", app().menuScale.value())); return true; @@ -329,7 +329,7 @@ VideoOptionView::VideoOptionView(ViewAttachParams attach, EmuVideoLayer &videoLa MenuId{videoLayer_.overlayIntensity() * 100.f}, overlayEffectLevelItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}%", int(videoLayer.overlayIntensity() * 100.f))); return true; @@ -499,7 +499,7 @@ VideoOptionView::VideoOptionView(ViewAttachParams attach, EmuVideoLayer &videoLa MenuId{videoLayer_.channelBrightnessAsInt(ImageChannel::Red)}, redItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}%", videoLayer.channelBrightnessAsInt(ImageChannel::Red))); return true; @@ -512,7 +512,7 @@ VideoOptionView::VideoOptionView(ViewAttachParams attach, EmuVideoLayer &videoLa MenuId{videoLayer_.channelBrightnessAsInt(ImageChannel::Green)}, greenItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}%", videoLayer.channelBrightnessAsInt(ImageChannel::Green))); return true; @@ -525,7 +525,7 @@ VideoOptionView::VideoOptionView(ViewAttachParams attach, EmuVideoLayer &videoLa MenuId{videoLayer_.channelBrightnessAsInt(ImageChannel::Blue)}, blueItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}%", videoLayer.channelBrightnessAsInt(ImageChannel::Blue))); return true; diff --git a/EmuFramework/src/shared/mednafen-emuex/MDFNFILE.cc b/EmuFramework/src/shared/mednafen-emuex/MDFNFILE.cc index 30f5090d0..2c0ce54b2 100644 --- a/EmuFramework/src/shared/mednafen-emuex/MDFNFILE.cc +++ b/EmuFramework/src/shared/mednafen-emuex/MDFNFILE.cc @@ -47,7 +47,7 @@ static bool hasKnownExtension(std::string_view name, const std::vector& known_ext, - const char* purpose, int* monocomp_double_ext) + [[maybe_unused]] const char* purpose, [[maybe_unused]] int* monocomp_double_ext) { if(IG::FS::hasArchiveExtension(path)) { @@ -83,10 +83,10 @@ MDFNFILE::MDFNFILE(VirtualFS* vfs, const std::string& path, const std::vector str): +MDFNFILE::MDFNFILE(VirtualFS*, std::unique_ptr str): str{std::move(str)} {} -extern int openFdHelper(const char *file, int oflag, mode_t mode) +extern int openFdHelper(const char *file, int oflag, mode_t) { auto openFlags = (oflag & O_CREAT) ? IG::OpenFlags::newFile() : IG::OpenFlags{}; return EmuEx::gAppContext().openFileUriFd(file, openFlags | IG::OpenFlags{.test = true}).release(); diff --git a/EmuFramework/src/shared/mednafen-emuex/MDFNUtils.hh b/EmuFramework/src/shared/mednafen-emuex/MDFNUtils.hh index afa206650..f93bcbf4d 100644 --- a/EmuFramework/src/shared/mednafen-emuex/MDFNUtils.hh +++ b/EmuFramework/src/shared/mednafen-emuex/MDFNUtils.hh @@ -92,7 +92,7 @@ inline FS::FileString saveExtMDFN(std::string_view ext, bool skipMD5) return str; } -inline std::string savePathMDFN(const EmuApp &app, int id1, const char *cd1, bool skipMD5) +inline std::string savePathMDFN(const EmuApp &app, [[maybe_unused]] int id1, const char *cd1, bool skipMD5) { assert(cd1); IG::FileString ext{'.'}; @@ -174,7 +174,7 @@ inline size_t stateSizeMDFN() return s.size(); } -inline void readStateMDFN(EmuApp &app, std::span buff) +inline void readStateMDFN(std::span buff) { using namespace Mednafen; if(hasGzipHeader(buff)) diff --git a/EmuFramework/src/shared/mednafen-emuex/StreamImpl.cc b/EmuFramework/src/shared/mednafen-emuex/StreamImpl.cc index 2d828f5ab..8f628c54c 100644 --- a/EmuFramework/src/shared/mednafen-emuex/StreamImpl.cc +++ b/EmuFramework/src/shared/mednafen-emuex/StreamImpl.cc @@ -54,7 +54,7 @@ std::pair modeToAttribs(uint32 mode) } } -FileStream::FileStream(const std::string& path, const uint32 mode, const int do_lock, const uint32 buffer_size) +FileStream::FileStream(const std::string& path, const uint32 mode, const int do_lock, [[maybe_unused]] const uint32 buffer_size) try: io{EmuEx::gAppContext().openFileUri(path, modeToAttribs(mode).first)}, attribs{modeToAttribs(mode).second} @@ -182,12 +182,12 @@ void MemoryStream::setSize(size_t size) data_buffer_size = size; } -uint64 Stream::readAtPos(void *data, uint64 count, uint64 pos) +uint64 Stream::readAtPos(void*, [[maybe_unused]] uint64 count, [[maybe_unused]] uint64 pos) { bug_unreachable("Stream::readAtPos not implemented"); return 0; } -void Stream::advise(off_t offset, size_t bytes, IG::IOAdvice advice) {} +void Stream::advise(off_t, size_t, IG::IOAdvice) {} } diff --git a/EmuFramework/src/shared/mednafen-emuex/VirtualFS.cc b/EmuFramework/src/shared/mednafen-emuex/VirtualFS.cc index 32472821f..dbf302a7d 100644 --- a/EmuFramework/src/shared/mednafen-emuex/VirtualFS.cc +++ b/EmuFramework/src/shared/mednafen-emuex/VirtualFS.cc @@ -61,7 +61,7 @@ void VirtualFS::get_file_path_components(const std::string &file_path, std::stri *file_ext_out = fileExt; } -void VirtualFS::check_firop_safe(const std::string& path) {} +void VirtualFS::check_firop_safe(const std::string&) {} bool VirtualFS::is_path_separator(const char c) { @@ -73,7 +73,7 @@ bool VirtualFS::is_absolute_path(const std::string& path) return true; } -std::string VirtualFS::eval_fip(const std::string& dir_path, const std::string& rel_path, bool skip_safety_check) +std::string VirtualFS::eval_fip(const std::string& dir_path, const std::string& rel_path, [[maybe_unused]] bool skip_safety_check) { if(is_absolute_path(rel_path)) return rel_path; @@ -94,9 +94,9 @@ std::string VirtualFS::get_human_mode(uint32 mode) } } -void VirtualFS::create_missing_dirs(const std::string& file_path) {} +void VirtualFS::create_missing_dirs(const std::string&) {} -bool VirtualFS::is_driverel_path(const std::string& path) { return false; } +bool VirtualFS::is_driverel_path(const std::string&) { return false; } } diff --git a/EmuFramework/src/vcontrols/VController.cc b/EmuFramework/src/vcontrols/VController.cc index 3077d0da9..acbe53f1e 100644 --- a/EmuFramework/src/vcontrols/VController.cc +++ b/EmuFramework/src/vcontrols/VController.cc @@ -177,7 +177,6 @@ void VController::place() { if(!hasWindow()) return; - auto &winData = windowData(); auto &win = window(); applyButtonSize(); auto bounds = layoutBounds(); @@ -220,7 +219,7 @@ std::array VController::findGamepadElements(WPt pos) return {}; return grp.findButtonIndices(pos); }, - [](auto &e) -> std::array { return {}; } + [](auto&) -> std::array { return {}; } }); if(indices != std::array{}) return indices; @@ -251,7 +250,7 @@ KeyInfo VController::keyboardKeyFromPointer(const Input::MotionEvent &e) if(!e.pushed()) return {}; log.info("switch kb mode"); - kb.cycleMode(system(), renderer()); + kb.cycleMode(system()); resetInput(); } else @@ -358,7 +357,7 @@ bool VController::keyInput(const Input::KeyEvent &e) { if(!isInKeyboardMode()) return false; - return kb.keyInput(*this, renderer(), e); + return kb.keyInput(*this, e); } void VController::draw(Gfx::RendererCommands &__restrict__ cmds, bool showHidden) @@ -438,7 +437,7 @@ void VController::setDisabledInputKeys(std::span disabledKeys_) e.visit(overloaded { [&](VControllerButtonGroup &grp) { updateEnabledButtons(grp); }, - [](auto &e){} + [](auto&){} }); } place(); @@ -669,11 +668,11 @@ bool VController::readConfig(EmuApp &app, MapIO &io, unsigned key) case CFGKEY_VCONTROLLER_DEVICE_BUTTONS_V2: { gpElements.clear(); - auto emuDeviceId = io.get(); // reserved for future use - auto configId = io.get(); // reserved for future use + [[maybe_unused]] auto emuDeviceId = io.get(); // reserved for future use + [[maybe_unused]] auto configId = io.get(); // reserved for future use auto elements = io.get(); log.info("read emu device button data ({} bytes) with {} element(s)", io.size(), elements); - for(auto i : iotaCount(elements)) + for([[maybe_unused]] auto i : iotaCount(elements)) { if(!readVControllerElement(app.inputManager, io, gpElements, false)) return false; @@ -683,10 +682,10 @@ bool VController::readConfig(EmuApp &app, MapIO &io, unsigned key) case CFGKEY_VCONTROLLER_UI_BUTTONS_V2: { uiElements.clear(); - auto configId = io.get(); // reserved for future use + [[maybe_unused]] auto configId = io.get(); // reserved for future use auto elements = io.get(); log.info("read UI button data ({} bytes) with {} element(s)", io.size(), elements); - for(auto i : iotaCount(elements)) + for([[maybe_unused]] auto i : iotaCount(elements)) { if(!readVControllerElement(app.inputManager, io, uiElements, true)) return false; @@ -1091,7 +1090,7 @@ void VController::updateSystemKeys(KeyInfo key, bool isPushed) if(didUpdate) dpad.setAlpha(alphaF); }, - [](auto &e){} + [](auto&){} }); } } @@ -1113,7 +1112,7 @@ void VController::resetHighlightedKeys() } } }, - [](auto &e){} + [](auto&){} }); } } diff --git a/EmuFramework/src/vcontrols/VControllerButtonGroup.cc b/EmuFramework/src/vcontrols/VControllerButtonGroup.cc index 929f6e00a..ec823da69 100644 --- a/EmuFramework/src/vcontrols/VControllerButtonGroup.cc +++ b/EmuFramework/src/vcontrols/VControllerButtonGroup.cc @@ -335,9 +335,9 @@ void BaseVControllerButtonGroup::updateSprites() if constexpr(requires {g.boundQuads;}) { g.boundQuads.reset({.size = g.buttons.size()}); - boundQuadsMap = g.boundQuads.map(); + boundQuadsMap = g.boundQuads.map(Gfx::BufferMapMode::indirect); } - auto quadsMap = g.quads.map(); + auto quadsMap = g.quads.map(Gfx::BufferMapMode::indirect); g.enabledBtns = 0; for(auto &b : g.buttons) { diff --git a/EmuFramework/src/vcontrols/VControllerDPad.cc b/EmuFramework/src/vcontrols/VControllerDPad.cc index e0a70f957..25416348e 100644 --- a/EmuFramework/src/vcontrols/VControllerDPad.cc +++ b/EmuFramework/src/vcontrols/VControllerDPad.cc @@ -216,7 +216,7 @@ void VControllerDPad::updateSprite() colors[2] = colors[2].multiplyRGB(2.f); for(auto &&[i, vtx] : enumerate(spr)) { vtx.color = colors[i]; } for(auto &&[i, vtx] : enumerate(mapSpr)) { vtx.color = colors[i]; } - auto map = spriteQuads.map(); + auto map = spriteQuads.map(Gfx::BufferMapMode::indirect); spr.write(map, 0); if(config.visualizeBounds) mapSpr.write(map, 1); diff --git a/EmuFramework/src/vcontrols/VControllerKeyboard.cc b/EmuFramework/src/vcontrols/VControllerKeyboard.cc index 51d78b16d..37a8afdd6 100644 --- a/EmuFramework/src/vcontrols/VControllerKeyboard.cc +++ b/EmuFramework/src/vcontrols/VControllerKeyboard.cc @@ -111,7 +111,7 @@ KeyInfo VControllerKeyboard::translateInput(int idx) const return table[0][idx]; } -bool VControllerKeyboard::keyInput(VController &v, Gfx::Renderer &r, const Input::KeyEvent &e) +bool VControllerKeyboard::keyInput(VController& v, const Input::KeyEvent& e) { if(selected.x == -1) { @@ -140,7 +140,7 @@ bool VControllerKeyboard::keyInput(VController &v, Gfx::Renderer &r, const Input if(!e.pushed() || e.repeated()) return false; log.info("switch kb mode"); - cycleMode(v.system(), r); + cycleMode(v.system()); v.resetInput(); } else if(e.pushed()) @@ -223,14 +223,14 @@ void VControllerKeyboard::unselectKey() IG::WindowRect VControllerKeyboard::extendKeySelection(IG::WindowRect selected) { auto key = currentKey(selected.x, selected.y); - for(auto i : iotaCount(selected.x)) + for([[maybe_unused]] auto i : iotaCount(selected.x)) { if(table[selected.y][selected.x - 1] == key) selected.x--; else break; } - for(auto i : iotaCount((VKEY_COLS - 1) - selected.x2)) + for([[maybe_unused]] auto i : iotaCount((VKEY_COLS - 1) - selected.x2)) { if(table[selected.y][selected.x2 + 1] == key) selected.x2++; @@ -251,16 +251,16 @@ KeyInfo VControllerKeyboard::currentKey() const return currentKey(selected.x, selected.y); } -void VControllerKeyboard::setMode(EmuSystem &sys, Gfx::Renderer &r, VControllerKbMode mode) +void VControllerKeyboard::setMode(EmuSystem& sys, VControllerKbMode mode) { mode_ = mode; updateImg(); updateKeyboardMapping(sys); } -void VControllerKeyboard::cycleMode(EmuSystem &sys, Gfx::Renderer &r) +void VControllerKeyboard::cycleMode(EmuSystem& sys) { - setMode(sys, r, + setMode(sys, mode() == VControllerKbMode::LAYOUT_1 ? VControllerKbMode::LAYOUT_2 : VControllerKbMode::LAYOUT_1); } @@ -271,7 +271,7 @@ void VControllerKeyboard::applyMap(KbMap map) // 1st row auto *__restrict tablePtr = &table[0][0]; auto *__restrict mapPtr = &map[0]; - for(auto i : iotaCount(10)) + for([[maybe_unused]] auto i : iotaCount(10)) { tablePtr[0] = *mapPtr; tablePtr[1] = *mapPtr; @@ -283,7 +283,7 @@ void VControllerKeyboard::applyMap(KbMap map) if(mode_ == VControllerKbMode::LAYOUT_1) { tablePtr = &table[1][1]; - for(auto i : iotaCount(9)) + for([[maybe_unused]] auto i : iotaCount(9)) { tablePtr[0] = *mapPtr; tablePtr[1] = *mapPtr; @@ -294,7 +294,7 @@ void VControllerKeyboard::applyMap(KbMap map) else { tablePtr = &table[1][0]; - for(auto i : iotaCount(10)) + for([[maybe_unused]] auto i : iotaCount(10)) { tablePtr[0] = *mapPtr; tablePtr[1] = *mapPtr; @@ -307,7 +307,7 @@ void VControllerKeyboard::applyMap(KbMap map) table[2][0] = table[2][1] = table[2][2] = *mapPtr; mapPtr++; tablePtr = &table[2][3]; - for(auto i : iotaCount(7)) + for([[maybe_unused]] auto i : iotaCount(7)) { tablePtr[0] = *mapPtr; tablePtr[1] = *mapPtr; @@ -320,7 +320,7 @@ void VControllerKeyboard::applyMap(KbMap map) table[3][3] = table[3][4] = table[3][5] = VController::CHANGE_KEYBOARD_MODE; tablePtr = &table[3][6]; mapPtr = &map[33]; - for(auto i : iotaCount(8)) + for([[maybe_unused]] auto i : iotaCount(8)) { *tablePtr++ = *mapPtr; } diff --git a/GBA.emu/build.mk b/GBA.emu/build.mk index ab5c6b528..97cc1a857 100644 --- a/GBA.emu/build.mk +++ b/GBA.emu/build.mk @@ -11,6 +11,8 @@ CPPFLAGS += -DHAVE_ZLIB_H \ -DNO_DEBUGGER \ -I$(projectPath)/src +CFLAGS_WARN += -Wno-unused-parameter -Wno-unused-function -Wno-unused-but-set-variable + vbamSrc := gba/gbaCpuThumb.cpp \ gba/internal/gbaBios.cpp \ gba/gbaCheats.cpp \ diff --git a/GBA.emu/src/core/gba/gba.cpp b/GBA.emu/src/core/gba/gba.cpp index 8540fb7be..4302cb306 100644 --- a/GBA.emu/src/core/gba/gba.cpp +++ b/GBA.emu/src/core/gba/gba.cpp @@ -2666,7 +2666,6 @@ void CPUUpdateRegister(ARM7TDMI &cpu, uint32_t address, uint16_t value) auto &busPrefetchCount = cpu.busPrefetchCount; auto &busPrefetch = cpu.busPrefetch; auto &busPrefetchEnable = cpu.busPrefetchEnable; - auto &g_ioMem = cpu.gba->mem.ioMem; auto &gba = *cpu.gba; switch (address) { @@ -3227,8 +3226,6 @@ void CPUUpdateRegister(ARM7TDMI &cpu, uint32_t address, uint16_t value) void applyTimer(GBASys &gba, ARM7TDMI &cpu) { - auto &ioMem = gba.mem.ioMem; - if (timerOnOffDelay & 1) { timer0ClockReload = TIMER_TICKS[timer0Value & 3]; if (!timer0On && (timer0Value & 0x80)) { diff --git a/GBA.emu/src/core/gba/gbaGfx.h b/GBA.emu/src/core/gba/gbaGfx.h index d04ff5223..edaeb816c 100644 --- a/GBA.emu/src/core/gba/gbaGfx.h +++ b/GBA.emu/src/core/gba/gbaGfx.h @@ -1179,7 +1179,6 @@ static inline void gfxDrawSprites(GBALCD &lcd, uint32_t* lineOBJ, const uint16_t static inline void gfxDrawOBJWin(GBALCD &lcd, uint32_t* lineOBJWin, const uint16_t VCOUNT, const uint16_t DISPCNT) { - uint8_t (&g_paletteRAM)[0x400] = lcd.paletteRAM; uint8_t (&g_vram)[0x20000] = lcd.vram; uint8_t (&g_oam)[0x400] = lcd.oam; const auto &coreOptions = lcd; diff --git a/GBA.emu/src/core/gba/gbaInline.h b/GBA.emu/src/core/gba/gbaInline.h index 4d8eed161..e8ddc788d 100644 --- a/GBA.emu/src/core/gba/gbaInline.h +++ b/GBA.emu/src/core/gba/gbaInline.h @@ -481,7 +481,6 @@ static inline uint8_t CPUReadByte(ARM7TDMI &cpu, uint32_t address) static inline void CPUWriteMemory(ARM7TDMI &cpu, uint32_t address, uint32_t value) { - auto &g_ioMem = cpu.gba->mem.ioMem.b; #ifdef GBA_LOGGING if (address & 3) { if (systemVerbose & VERBOSE_UNALIGNED_MEMORY) { diff --git a/GBA.emu/src/main/EmuMenuViews.cc b/GBA.emu/src/main/EmuMenuViews.cc index 46f084a80..39fba3675 100644 --- a/GBA.emu/src/main/EmuMenuViews.cc +++ b/GBA.emu/src/main/EmuMenuViews.cc @@ -77,7 +77,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper MenuId{system().optionRtcEmulation.value()}, rtcItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text& t) { if(idx == 0) { @@ -242,13 +242,13 @@ class CustomAudioOptionView : public AudioOptionView, public MainAppHelper TextMenuItem { "Default", attachParams(), - [this, gbVol]() { soundSetVolume(gGba, 1.f, gbVol); }, + [gbVol]() { soundSetVolume(gGba, 1.f, gbVol); }, {.id = 100} }, TextMenuItem { "Off", attachParams(), - [this, gbVol]() { soundSetVolume(gGba, 0, gbVol); }, + [gbVol]() { soundSetVolume(gGba, 0, gbVol); }, {.id = 0} }, TextMenuItem @@ -285,7 +285,7 @@ class CustomAudioOptionView : public AudioOptionView, public MainAppHelper MenuId{soundVolumeAsInt(gGba, gbVol)}, volumeLevelItem[gbVol ? 1 : 0], { - .onSetDisplayString = [this, gbVol](auto idx, Gfx::Text &t) + .onSetDisplayString = [gbVol](auto idx, Gfx::Text& t) { t.resetString(std::format("{}%", soundVolumeAsInt(gGba, gbVol))); return true; @@ -328,7 +328,7 @@ class CustomAudioOptionView : public AudioOptionView, public MainAppHelper TextMenuItem { "Default", attachParams(), - [this]() { soundSetFiltering(gGba, .5f); }, + []() { soundSetFiltering(gGba, .5f); }, {.id = 50} }, TextMenuItem @@ -355,7 +355,7 @@ class CustomAudioOptionView : public AudioOptionView, public MainAppHelper MenuId{soundFilteringAsInt(gGba)}, filteringLevelItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto, Gfx::Text& t) { t.resetString(std::format("{}%", soundFilteringAsInt(gGba))); return true; diff --git a/GBA.emu/src/main/GBASys.hh b/GBA.emu/src/main/GBASys.hh index 396eaee69..820ffcc5c 100644 --- a/GBA.emu/src/main/GBASys.hh +++ b/GBA.emu/src/main/GBASys.hh @@ -678,7 +678,7 @@ static inline uint32_t CPUReadHalfWordQuick(ARM7TDMI &cpu, uint32_t addr) static inline uint32_t CPUReadMemoryQuick(ARM7TDMI &cpu, uint32_t addr) { return READ32LE(((uint32_t*)&cpu.map[addr>>24].address[addr & cpu.map[addr>>24].mask])); } -static void blankLine(MixColorType *lineMix, GBALCD &lcd, const GBAMem::IoMem &ioMem) +inline void blankLine(MixColorType *lineMix, GBALCD &lcd, const GBAMem::IoMem &ioMem) { for (int x = 0; x < 240; x++) lineMix[x] = 0x7fff; diff --git a/GBC.emu/src/main/Cheats.cc b/GBC.emu/src/main/Cheats.cc index 71a318004..b3b6aa6bd 100644 --- a/GBC.emu/src/main/Cheats.cc +++ b/GBC.emu/src/main/Cheats.cc @@ -122,7 +122,7 @@ void readCheatFile(EmuSystem &sys_) return; } auto size = file.get(); - for(auto i : iotaCount(size)) + for([[maybe_unused]] auto i : iotaCount(size)) { if(cheatList.isFull()) { @@ -162,7 +162,7 @@ EmuEditCheatView::EmuEditCheatView(ViewAttachParams attach, GbcCheat &cheat_, Re "Code", cheat_.code, attach, - [this](DualTextMenuItem &item, View &, Input::Event e) + [this](Input::Event e) { pushAndShowNewCollectValueInputView(attachParams(), e, "Input xxxxxxxx (GS) or xxx-xxx-xxx (GG) code", cheat->code, @@ -206,8 +206,8 @@ EmuEditCheatListView::EmuEditCheatListView(ViewAttachParams attach): { return msg.visit(overloaded { - [&](const ItemsMessage &m) -> ItemReply { return 1 + cheat.size(); }, - [&](const GetItemMessage &m) -> ItemReply + [&](const ItemsMessage&) -> ItemReply { return 1 + cheat.size(); }, + [&](const GetItemMessage& m) -> ItemReply { switch(m.idx) { @@ -221,7 +221,7 @@ EmuEditCheatListView::EmuEditCheatListView(ViewAttachParams attach): addGGGS { "Add Game Genie / GameShark Code", attach, - [this](TextMenuItem &item, View &, Input::Event e) + [this](const Input::Event& e) { pushAndShowNewCollectTextInputView(attachParams(), e, "Input xxxxxxxx (GS) or xxx-xxx-xxx (GG) code", "", @@ -310,7 +310,7 @@ void EmuCheatsView::loadCheatItems() { auto &thisCheat = *it; cheat.emplace_back(thisCheat.name, attachParams(), thisCheat.isOn(), - [this, cIdx](BoolMenuItem &item, View &, Input::Event e) + [this, cIdx](BoolMenuItem &item) { item.flipBoolValue(*this); auto &c = cheatList[cIdx]; diff --git a/GBC.emu/src/main/EmuMenuViews.cc b/GBC.emu/src/main/EmuMenuViews.cc index 7103393d2..3c932dfd0 100644 --- a/GBC.emu/src/main/EmuMenuViews.cc +++ b/GBC.emu/src/main/EmuMenuViews.cc @@ -108,7 +108,7 @@ class CustomVideoOptionView : public VideoOptionView, public MainAppHelper { "Saturated GBC Colors", attachParams(), (bool)system().optionFullGbcSaturation, - [this](BoolMenuItem &item, View &, Input::Event e) + [this](BoolMenuItem &item) { system().optionFullGbcSaturation = item.flipBoolValue(*this); if(system().hasContent()) @@ -134,7 +134,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper { "Use Built-in GB Palettes", attachParams(), (bool)system().optionUseBuiltinGBPalette, - [this](BoolMenuItem &item, View &, Input::Event e) + [this](BoolMenuItem &item) { system().sessionOptionSet(); system().optionUseBuiltinGBPalette = item.flipBoolValue(*this); diff --git a/GBC.emu/src/main/Main.cc b/GBC.emu/src/main/Main.cc index a15ec2744..98f101db5 100755 --- a/GBC.emu/src/main/Main.cc +++ b/GBC.emu/src/main/Main.cc @@ -81,7 +81,7 @@ void GbcSystem::applyGBPalette() gbEmu.setDmgPaletteColor(2, i, makeOutputColor(pal.sp2[i])); } -void GbcSystem::reset(EmuApp &app, ResetMode mode) +void GbcSystem::reset(EmuApp& app, ResetMode) { flushBackupMemory(app); gbEmu.reset(); @@ -93,14 +93,14 @@ FS::FileString GbcSystem::stateFilename(int slot, std::string_view name) const return IG::format("{}.0{}.gqs", name, saveSlotCharUpper(slot)); } -void GbcSystem::readState(EmuApp &app, std::span buff) +void GbcSystem::readState(EmuApp&, std::span buff) { IStream stream{buff}; if(!gbEmu.loadState(stream)) throw std::runtime_error("Invalid state data"); } -size_t GbcSystem::writeState(std::span buff, SaveStateFlags flags) +size_t GbcSystem::writeState(std::span buff, SaveStateFlags) { assert(saveStateSize == buff.size()); OStream stream{buff}; diff --git a/GBC.emu/src/main/input.cc b/GBC.emu/src/main/input.cc index 6a1293408..a878ed211 100644 --- a/GBC.emu/src/main/input.cc +++ b/GBC.emu/src/main/input.cc @@ -184,7 +184,7 @@ void GbcSystem::clearInputBuffers(EmuInputView &) gbcInput.bits = 0; } -SystemInputDeviceDesc GbcSystem::inputDeviceDesc(int idx) const +SystemInputDeviceDesc GbcSystem::inputDeviceDesc(int) const { static constexpr std::array gamepadComponents { diff --git a/Lynx.emu/build.mk b/Lynx.emu/build.mk index 5fceeaa20..836b04f32 100644 --- a/Lynx.emu/build.mk +++ b/Lynx.emu/build.mk @@ -9,7 +9,7 @@ VPATH += $(EMUFRAMEWORK_PATH)/src/shared CPPFLAGS += $(MDFN_COMMON_CPPFLAGS) \ -I$(projectPath)/src -CXXFLAGS_WARN += -Wno-missing-field-initializers +CXXFLAGS_WARN += -Wno-missing-field-initializers -Wno-unused-parameter SRC += main/Main.cc \ main/options.cc \ diff --git a/Lynx.emu/metadata/conf.mk b/Lynx.emu/metadata/conf.mk index 30299d89c..92c19642a 100644 --- a/Lynx.emu/metadata/conf.mk +++ b/Lynx.emu/metadata/conf.mk @@ -2,7 +2,7 @@ include $(EMUFRAMEWORK_PATH)/metadata/conf.mk metadata_name = Lynx.emu metadata_exec = lynxemu metadata_pkgName = LynxEmu -metadata_supportedFileExtensions += lnx o +metadata_supportedFileExtensions += lnx lyx o metadata_id = com.explusalpha.LynxEmu metadata_vendor = Robert Broglia pnd_metadata_description = Lynx emulator using components from Mednafen diff --git a/Lynx.emu/src/main/EmuMenuViews.cc b/Lynx.emu/src/main/EmuMenuViews.cc index e77bcdcaa..d2a15722a 100644 --- a/Lynx.emu/src/main/EmuMenuViews.cc +++ b/Lynx.emu/src/main/EmuMenuViews.cc @@ -46,7 +46,7 @@ class CustomFilePathOptionView : public FilePathOptionView, public MainAppHelper { pushAndShow(makeViewWithName>("BIOS", app().validSearchPath(FS::dirnameUri(system().biosPath)), - [this](CStringView path, FS::file_type type) + [this](CStringView path, FS::file_type) { system().biosPath = path; logMsg("set BIOS:%s", system().biosPath.data()); diff --git a/Lynx.emu/src/main/Main.cc b/Lynx.emu/src/main/Main.cc index 45b8463e1..2abb8161b 100755 --- a/Lynx.emu/src/main/Main.cc +++ b/Lynx.emu/src/main/Main.cc @@ -42,7 +42,7 @@ bool EmuApp::needsGlobalInstance = true; EmuSystem::NameFilterFunc EmuSystem::defaultFsFilter = [](std::string_view name) { - return endsWithAnyCaseless(name, ".lnx", ".o"); + return endsWithAnyCaseless(name, ".lnx", ".lyx", ".o"); }; using namespace Mednafen; @@ -53,7 +53,7 @@ LynxApp::LynxApp(ApplicationInitParams initParams, ApplicationContext &ctx): const char *EmuSystem::shortSystemName() const { return "Lynx"; } const char *EmuSystem::systemName() const { return "Lynx"; } -void LynxSystem::reset(EmuApp &, ResetMode mode) +void LynxSystem::reset(EmuApp&, ResetMode) { assert(hasContent()); MDFN_DoSimpleCommand(MDFN_MSC_RESET); @@ -65,7 +65,7 @@ FS::FileString LynxSystem::stateFilename(int slot, std::string_view name) const } size_t LynxSystem::stateSize() { return stateSizeMDFN(); } -void LynxSystem::readState(EmuApp &app, std::span buff) { readStateMDFN(app, buff); } +void LynxSystem::readState(EmuApp&, std::span buff) { readStateMDFN(buff); } size_t LynxSystem::writeState(std::span buff, SaveStateFlags flags) { return writeStateMDFN(buff, flags); } void LynxSystem::closeSystem() diff --git a/Lynx.emu/src/main/options.cc b/Lynx.emu/src/main/options.cc index 374b2fee9..06a79e4fc 100644 --- a/Lynx.emu/src/main/options.cc +++ b/Lynx.emu/src/main/options.cc @@ -119,7 +119,6 @@ uint64 MDFN_GetSettingUI(const char *name_) int64 MDFN_GetSettingI(const char *name_) { std::string_view name{name_}; - auto &sys = static_cast(gSystem()); if("filesys.state_comp_level" == name) return 6; bug_unreachable("unhandled settingI %s", name_); diff --git a/MD.emu/build.mk b/MD.emu/build.mk index 94a350b58..f905662d8 100644 --- a/MD.emu/build.mk +++ b/MD.emu/build.mk @@ -9,7 +9,7 @@ CPPFLAGS += -DLSB_FIRST \ -DNO_SYSTEM_PICO # -DNO_SVP -DNO_SYSTEM_PBC -CFLAGS_WARN += -Wno-missing-field-initializers +CFLAGS_WARN += -Wno-missing-field-initializers -Wno-unused-parameter -Wno-unused-function ifeq ($(config_compiler),clang) # needed for Z80CPU::makeFlagTables() diff --git a/MD.emu/src/genplus-gx/cart_hw/eeprom.cc b/MD.emu/src/genplus-gx/cart_hw/eeprom.cc index 0e4484754..fef981de0 100644 --- a/MD.emu/src/genplus-gx/cart_hw/eeprom.cc +++ b/MD.emu/src/genplus-gx/cart_hw/eeprom.cc @@ -84,8 +84,6 @@ static const T_GAME_ENTRY database[GAME_CNT] = void eeprom_init() { - int i = 0; - /* initialize eeprom */ memset(&eeprom, 0, sizeof(T_EEPROM)); eeprom.sda = eeprom.old_sda = 1; diff --git a/MD.emu/src/main/EmuMenuViews.cc b/MD.emu/src/main/EmuMenuViews.cc index 3ffd96755..0a10a89e6 100644 --- a/MD.emu/src/main/EmuMenuViews.cc +++ b/MD.emu/src/main/EmuMenuViews.cc @@ -115,7 +115,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper system().optionVideoSystem.value(), videoSystemItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text& t) { if(idx == 0) { @@ -148,7 +148,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper std::min((int)config.region_detect, 4), regionItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text& t) { if(idx == 0) { diff --git a/MSX.emu/build.mk b/MSX.emu/build.mk index ab333664a..fb39b0862 100644 --- a/MSX.emu/build.mk +++ b/MSX.emu/build.mk @@ -5,7 +5,7 @@ include $(IMAGINE_PATH)/make/imagineAppBase.mk # TODO: fix pointer type casts CFLAGS_LANG += -Werror=implicit-function-declaration -Wno-incompatible-pointer-types -CFLAGS_WARN += -Wno-sign-compare -Wno-switch -Wno-implicit-fallthrough +CFLAGS_WARN += -Wno-sign-compare -Wno-switch -Wno-implicit-fallthrough -Wno-unused-parameter -Wno-unused-function -Wno-unused-variable BMSX := blueMSX diff --git a/MSX.emu/src/main/EmuMenuViews.cc b/MSX.emu/src/main/EmuMenuViews.cc index 7a9d7f364..ab89fa9f3 100644 --- a/MSX.emu/src/main/EmuMenuViews.cc +++ b/MSX.emu/src/main/EmuMenuViews.cc @@ -123,7 +123,7 @@ class CustomSystemOptionView : public SystemOptionView, public MainAppHelper { return { - .onSetDisplayString = [](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text& t) { if(idx == -1) { @@ -564,7 +564,7 @@ private: 0, machineItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text& t) { if(idx == -1) { diff --git a/NEO.emu/build.mk b/NEO.emu/build.mk index 5acb5143e..e8554437e 100644 --- a/NEO.emu/build.mk +++ b/NEO.emu/build.mk @@ -13,7 +13,7 @@ main/EmuMenuViews.cc CPPFLAGS += -I$(projectPath)/src \ -DHAVE_CONFIG_H -DLSB_FIRST -CFLAGS_WARN += -Wno-sign-compare +CFLAGS_WARN += -Wno-sign-compare -Wno-unused-parameter -Wno-unused-function ifeq ($(config_compiler),clang) # needed for Z80CPU::makeFlagTables() diff --git a/NEO.emu/src/main/EmuMenuViews.cc b/NEO.emu/src/main/EmuMenuViews.cc index 0ac4a49d7..516d07b3e 100644 --- a/NEO.emu/src/main/EmuMenuViews.cc +++ b/NEO.emu/src/main/EmuMenuViews.cc @@ -66,7 +66,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper std::min((int)system().optionTimerInt, 2), timerItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text& t) { if(idx == 2) { diff --git a/NEO.emu/src/main/unzip.cc b/NEO.emu/src/main/unzip.cc index 164c87a07..711d8bde9 100644 --- a/NEO.emu/src/main/unzip.cc +++ b/NEO.emu/src/main/unzip.cc @@ -119,7 +119,6 @@ uint8_t *gn_unzip_file_malloc(PKZIP *archPtr, const char *filename, uint32_t fil struct PKZIP *open_rom_zip(void *contextPtr, char *romPath, char *name) { - auto &ctx = *((IG::ApplicationContext*)contextPtr); auto baseUri = FS::uriString(romPath, name); // Try to open each possible archive type if(auto gz = gn_open_zip(contextPtr, FS::PathString{baseUri + ".zip"}.data()); diff --git a/NES.emu/build.mk b/NES.emu/build.mk index 15667e713..29c6ca5aa 100755 --- a/NES.emu/build.mk +++ b/NES.emu/build.mk @@ -18,7 +18,8 @@ CPPFLAGS += -I$(projectPath)/src \ -DFRAMESKIP \ -I$(projectPath)/src/fceu -CXXFLAGS_WARN += -Wno-register -Wno-sign-compare -Wno-missing-field-initializers -Wno-switch -Wno-bitwise-op-parentheses -Wno-expansion-to-defined +CXXFLAGS_WARN += -Wno-register -Wno-sign-compare -Wno-missing-field-initializers -Wno-switch \ + -Wno-bitwise-op-parentheses -Wno-expansion-to-defined -Wno-unused-local-typedefs -Wno-unused-parameter ifneq ($(config_compiler), clang) CXXFLAGS_WARN += -Wno-volatile diff --git a/NES.emu/src/main/Cheats.cc b/NES.emu/src/main/Cheats.cc index 1902d6e6b..1fd9c605b 100644 --- a/NES.emu/src/main/Cheats.cc +++ b/NES.emu/src/main/Cheats.cc @@ -218,7 +218,7 @@ EmuEditCheatView::EmuEditCheatView(ViewAttachParams attach, unsigned cheatIdx, R int compare; { std::string nameStr{}; - int gotCheat = FCEUI_GetCheat(cheatIdx, &nameStr, &a, &v, &compare, 0, &type); + FCEUI_GetCheat(cheatIdx, &nameStr, &a, &v, &compare, 0, &type); logMsg("got cheat with addr 0x%.4x val 0x%.2x comp %d", a, v, compare); name.setName(std::move(nameStr)); } diff --git a/NES.emu/src/main/EmuFileIO.hh b/NES.emu/src/main/EmuFileIO.hh index 1f4d43fb8..e3522f6ae 100644 --- a/NES.emu/src/main/EmuFileIO.hh +++ b/NES.emu/src/main/EmuFileIO.hh @@ -31,8 +31,8 @@ public: ~EmuFileIO() = default; FILE *get_fp() final { return nullptr; } EMUFILE* memwrap() final { return nullptr; } - void truncate(size_t length) final {} - int fprintf(const char *format, ...) final { return 0; }; + void truncate(size_t) final {} + int fprintf(const char*, ...) final { return 0; }; int fgetc() final; int fputc(int c) final; size_t _fread(const void *ptr, size_t bytes) final; diff --git a/NES.emu/src/main/EmuMenuViews.cc b/NES.emu/src/main/EmuMenuViews.cc index ac2d5e88d..d25488833 100644 --- a/NES.emu/src/main/EmuMenuViews.cc +++ b/NES.emu/src/main/EmuMenuViews.cc @@ -118,7 +118,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper MenuId{system().optionVideoSystem}, videoSystemItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text &t) { if(idx == 0) { @@ -698,7 +698,7 @@ private: TextMenuItem insertEject { "Eject", attachParams(), - [this](View &view, Input::Event e) + [](View& view) { if(FCEU_FDSInserted()) { diff --git a/NES.emu/src/main/input.cc b/NES.emu/src/main/input.cc index ea4542887..03ffa5285 100644 --- a/NES.emu/src/main/input.cc +++ b/NES.emu/src/main/input.cc @@ -88,8 +88,8 @@ std::span NesApp::keyCategories() { KeyCategory{"Gamepad", gpKeyInfo}, KeyCategory{"Gamepad 2", gp2KeyInfo, 1}, - KeyCategory{"Gamepad 3", gp2KeyInfo, 2}, - KeyCategory{"Gamepad 4", gp2KeyInfo, 3}, + KeyCategory{"Gamepad 3", gp3KeyInfo, 2}, + KeyCategory{"Gamepad 4", gp4KeyInfo, 3}, KeyCategory{"Extra Functions", exKeyInfo}, }; return categories; @@ -237,8 +237,9 @@ void NesSystem::handleInputAction(EmuApp *app, InputAction a) { if(!isFDS || !a.isPushed()) return; + EmuSystemTask::SuspendContext suspendCtx; if(app) - app->syncEmulationThread(); + suspendCtx = app->suspendEmulationThread(); if(FCEU_FDSInserted()) { FCEU_FDSInsert(); diff --git a/NGP.emu/build.mk b/NGP.emu/build.mk index 78586aec2..fd2d8ee59 100644 --- a/NGP.emu/build.mk +++ b/NGP.emu/build.mk @@ -9,7 +9,7 @@ VPATH += $(EMUFRAMEWORK_PATH)/src/shared CPPFLAGS += $(MDFN_COMMON_CPPFLAGS) \ -I$(projectPath)/src -CXXFLAGS_WARN += -Wno-missing-field-initializers +CXXFLAGS_WARN += -Wno-missing-field-initializers -Wno-unused-parameter SRC += main/Main.cc \ main/options.cc \ diff --git a/NGP.emu/src/main/Main.cc b/NGP.emu/src/main/Main.cc index f52365252..03c7495c5 100755 --- a/NGP.emu/src/main/Main.cc +++ b/NGP.emu/src/main/Main.cc @@ -71,7 +71,7 @@ FS::FileString NgpSystem::stateFilename(int slot, std::string_view name) const } size_t NgpSystem::stateSize() { return stateSizeMDFN(); } -void NgpSystem::readState(EmuApp &app, std::span buff) { readStateMDFN(app, buff); } +void NgpSystem::readState(EmuApp&, std::span buff) { readStateMDFN(buff); } size_t NgpSystem::writeState(std::span buff, SaveStateFlags flags) { return writeStateMDFN(buff, flags); } static FS::PathString saveFilename(const EmuApp &app) @@ -163,7 +163,7 @@ void system_io_flash_write(uint8_t* buffer, uint32 len) return; auto saveStr = saveFilename(gApp()); logMsg("writing flash %s", saveStr.data()); - IG::FileUtils::writeToUri(gAppContext(), saveStr, {buffer, len}) != -1; + IG::FileUtils::writeToUri(gAppContext(), saveStr, {buffer, len}); } } diff --git a/PCE.emu/build.mk b/PCE.emu/build.mk index f1099f414..59252bf35 100644 --- a/PCE.emu/build.mk +++ b/PCE.emu/build.mk @@ -12,7 +12,7 @@ CPPFLAGS += $(MDFN_COMMON_CPPFLAGS) \ -I$(EMUFRAMEWORK_PATH)/src/shared/mednafen/hw_misc \ -I$(EMUFRAMEWORK_PATH)/src/shared/mednafen/hw_sound -CXXFLAGS_WARN += -Wno-missing-field-initializers +CXXFLAGS_WARN += -Wno-missing-field-initializers -Wno-unused-parameter -Wno-unused-function SRC += main/Main.cc \ main/options.cc \ diff --git a/PCE.emu/src/main/Main.cc b/PCE.emu/src/main/Main.cc index 45859f2e1..1bc687610 100755 --- a/PCE.emu/src/main/Main.cc +++ b/PCE.emu/src/main/Main.cc @@ -211,7 +211,7 @@ void PceSystem::reset(EmuApp &, ResetMode mode) } size_t PceSystem::stateSize() { return stateSizeMDFN(); } -void PceSystem::readState(EmuApp &app, std::span buff) { readStateMDFN(app, buff); } +void PceSystem::readState(EmuApp&, std::span buff) { readStateMDFN(buff); } size_t PceSystem::writeState(std::span buff, SaveStateFlags flags) { return writeStateMDFN(buff, flags); } double PceSystem::videoAspectRatioScale() const @@ -267,7 +267,7 @@ static void renderMultiresOutput(EmulateSpecStruct spec, IG::PixmapView srcPix, bug_unreachable("width == %d", width); case 256: { - for(auto w : IG::iotaCount(256)) + for([[maybe_unused]] auto w : IG::iotaCount(256)) { *destPixAddr++ = *srcPixAddr; *destPixAddr++ = *srcPixAddr; @@ -278,7 +278,7 @@ static void renderMultiresOutput(EmulateSpecStruct spec, IG::PixmapView srcPix, } case 341: { - for(auto w : IG::iotaCount(340)) + for([[maybe_unused]] auto w : IG::iotaCount(340)) { *destPixAddr++ = *srcPixAddr; *destPixAddr++ = *srcPixAddr; @@ -292,7 +292,7 @@ static void renderMultiresOutput(EmulateSpecStruct spec, IG::PixmapView srcPix, } case 512: { - for(auto w : IG::iotaCount(512)) + for([[maybe_unused]] auto w : IG::iotaCount(512)) { *destPixAddr++ = *srcPixAddr; *destPixAddr++ = *srcPixAddr++; @@ -315,7 +315,7 @@ static void renderMultiresOutput(EmulateSpecStruct spec, IG::PixmapView srcPix, bug_unreachable("width == %d", width); case 256: { - for(auto w : IG::iotaCount(256)) + for([[maybe_unused]] auto w : IG::iotaCount(256)) { *destPixAddr++ = *srcPixAddr; *destPixAddr++ = *srcPixAddr++; diff --git a/PCE.emu/src/main/input.cc b/PCE.emu/src/main/input.cc index 8e804e4e1..c96aacd07 100644 --- a/PCE.emu/src/main/input.cc +++ b/PCE.emu/src/main/input.cc @@ -80,7 +80,7 @@ std::span PceApp::keyCategories() KeyCategory{"Gamepad 2", gp2KeyInfo, 1}, KeyCategory{"Gamepad 3", gp3KeyInfo, 2}, KeyCategory{"Gamepad 4", gp4KeyInfo, 3}, - KeyCategory{"Gamepad 5", gp4KeyInfo, 4}, + KeyCategory{"Gamepad 5", gp5KeyInfo, 4}, }; return categories; } diff --git a/Saturn.emu/build.mk b/Saturn.emu/build.mk index a768e551f..e21851023 100644 --- a/Saturn.emu/build.mk +++ b/Saturn.emu/build.mk @@ -10,7 +10,7 @@ CPPFLAGS += $(MDFN_COMMON_CPPFLAGS) \ $(MDFN_CDROM_CPPFLAGS) \ -I$(projectPath)/src -CXXFLAGS_WARN += -Wno-missing-field-initializers -Wno-implicit-fallthrough -Wno-deprecated-enum-enum-conversion +CXXFLAGS_WARN += -Wno-missing-field-initializers -Wno-implicit-fallthrough -Wno-deprecated-enum-enum-conversion -Wno-unused-parameter -Wno-unused-function SRC += main/Main.cc \ main/options.cc \ diff --git a/Saturn.emu/src/main/EmuMenuViews.cc b/Saturn.emu/src/main/EmuMenuViews.cc index 439f1b70a..7924cea63 100644 --- a/Saturn.emu/src/main/EmuMenuViews.cc +++ b/Saturn.emu/src/main/EmuMenuViews.cc @@ -201,7 +201,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper MenuId{system().cartType}, cartTypeItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text &t) { if(idx == 0) { @@ -238,7 +238,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper MenuId{system().region}, regionItems, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [](auto idx, Gfx::Text &t) { if(idx == 0) { diff --git a/Saturn.emu/src/main/Main.cc b/Saturn.emu/src/main/Main.cc index 76a96c24b..f9004bf9e 100755 --- a/Saturn.emu/src/main/Main.cc +++ b/Saturn.emu/src/main/Main.cc @@ -425,7 +425,7 @@ double SaturnSystem::videoAspectRatioScale() const } size_t SaturnSystem::stateSize() { return currStateSize; } -void SaturnSystem::readState(EmuApp &app, std::span buff) { readStateMDFN(app, buff); } +void SaturnSystem::readState(EmuApp&, std::span buff) { readStateMDFN(buff); } size_t SaturnSystem::writeState(std::span buff, SaveStateFlags flags) { return writeStateMDFN(buff, flags); } void EmuApp::onCustomizeNavView(EmuApp::NavView &view) diff --git a/Saturn.emu/src/main/input.cc b/Saturn.emu/src/main/input.cc index 73f45e665..06dcb1e53 100644 --- a/Saturn.emu/src/main/input.cc +++ b/Saturn.emu/src/main/input.cc @@ -33,7 +33,7 @@ namespace EmuEx { -constexpr SystemLogger log{"Saturn.emu"}; +[[maybe_unused]] constexpr SystemLogger log{"Saturn.emu"}; const int EmuSystem::maxPlayers = 12; enum class SaturnKey : KeyCode diff --git a/Snes9x/src/main/Cheats.cc b/Snes9x/src/main/Cheats.cc index 3f7628fbb..546dd8c6f 100644 --- a/Snes9x/src/main/Cheats.cc +++ b/Snes9x/src/main/Cheats.cc @@ -206,7 +206,7 @@ EmuEditCheatView::EmuEditCheatView(ViewAttachParams attach, int cheatIdx, Refres "Address", u"", attach, - [this](DualTextMenuItem &item, View &, Input::Event e) + [this](const Input::Event& e) { pushAndShowNewCollectValueInputView(attachParams(), e, "Input 6-digit hex", addrStr.data(), [this](CollectTextInputView&, auto str) @@ -242,7 +242,7 @@ EmuEditCheatView::EmuEditCheatView(ViewAttachParams attach, int cheatIdx, Refres "Value", u"", attach, - [this](DualTextMenuItem &item, View &, Input::Event e) + [this](const Input::Event& e) { pushAndShowNewCollectValueInputView(attachParams(), e, "Input 2-digit hex", valueStr.data(), [this](CollectTextInputView&, const char *str) @@ -281,7 +281,7 @@ EmuEditCheatView::EmuEditCheatView(ViewAttachParams attach, int cheatIdx, Refres #endif u"", attach, - [this](DualTextMenuItem &item, View &, Input::Event e) + [this](const Input::Event& e) { pushAndShowNewCollectTextInputView(attachParams(), e, "Input 2-digit hex or blank", savedStr.data(), [this](CollectTextInputView &view, const char *str) @@ -383,8 +383,8 @@ EmuEditCheatListView::EmuEditCheatListView(ViewAttachParams attach): { return msg.visit(overloaded { - [&](const ItemsMessage &m) -> ItemReply { return 1 + cheat.size(); }, - [&](const GetItemMessage &m) -> ItemReply + [&](const ItemsMessage&) -> ItemReply { return 1 + cheat.size(); }, + [&](const GetItemMessage& m) -> ItemReply { switch(m.idx) { @@ -398,7 +398,7 @@ EmuEditCheatListView::EmuEditCheatListView(ViewAttachParams attach): addCode { "Add Game Genie/Action Replay/Gold Finger Code", attach, - [this](TextMenuItem &item, View &, Input::Event e) + [this](const Input::Event& e) { if(numCheats() == EmuCheats::MAX) { @@ -464,7 +464,7 @@ void EmuCheatsView::loadCheatItems() for(auto c : iotaCount(cheats)) { cheat.emplace_back(cheatName(c), attachParams(), cheatIsEnabled(c), - [this, c](BoolMenuItem &item, View &, Input::Event e) + [this, c](BoolMenuItem &item) { bool on = item.flipBoolValue(*this); if(on) diff --git a/Snes9x/src/main/EmuMenuViews.cc b/Snes9x/src/main/EmuMenuViews.cc index d0b3de0c3..6614ed99d 100644 --- a/Snes9x/src/main/EmuMenuViews.cc +++ b/Snes9x/src/main/EmuMenuViews.cc @@ -65,7 +65,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper { "5-Player Adapter", attachParams(), (bool)system().optionMultitap, - [this](BoolMenuItem &item, View &, Input::Event e) + [this](BoolMenuItem &item) { system().sessionOptionSet(); system().optionMultitap = item.flipBoolValue(*this); @@ -130,7 +130,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper { "Allow Extended 239/478 Lines", attachParams(), (bool)system().optionAllowExtendedVideoLines, - [this](BoolMenuItem &item, View &, Input::Event e) + [this](BoolMenuItem &item) { system().sessionOptionSet(); system().optionAllowExtendedVideoLines = item.flipBoolValue(*this); @@ -164,7 +164,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper { "Allow Invalid VRAM Access", attachParams(), (bool)!system().optionBlockInvalidVRAMAccess, - [this](BoolMenuItem &item, View &, Input::Event e) + [this](BoolMenuItem &item) { system().sessionOptionSet(); system().optionBlockInvalidVRAMAccess = !item.flipBoolValue(*this); @@ -176,7 +176,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper { "Separate Echo Buffer From Ram", attachParams(), (bool)system().optionSeparateEchoBuffer, - [this](BoolMenuItem &item, View &, Input::Event e) + [this](BoolMenuItem &item) { system().sessionOptionSet(); system().optionSeparateEchoBuffer = item.flipBoolValue(*this); @@ -230,7 +230,7 @@ class ConsoleOptionView : public TableView, public MainAppHelper }(), superFXClockItem, { - .onSetDisplayString = [this](auto idx, Gfx::Text &t) + .onSetDisplayString = [this](auto, Gfx::Text& t) { t.resetString(std::format("{}%", system().optionSuperFXClockMultiplier.value())); return true; @@ -351,7 +351,7 @@ class CustomFilePathOptionView : public FilePathOptionView, public MainAppHelper { pushAndShow(makeViewWithName>("BS-X BIOS", app().validSearchPath(FS::dirnameUri(system().bsxBiosPath)), - [this](CStringView path, FS::file_type type) + [this](CStringView path, FS::file_type) { system().bsxBiosPath = path; logMsg("set BS-X bios:%s", path.data()); @@ -373,7 +373,7 @@ class CustomFilePathOptionView : public FilePathOptionView, public MainAppHelper { pushAndShow(makeViewWithName>("Sufami Turbo BIOS", app().validSearchPath(FS::dirnameUri(system().sufamiBiosPath)), - [this](CStringView path, FS::file_type type) + [this](CStringView path, FS::file_type) { system().sufamiBiosPath = path; logMsg("set Sufami Turbo bios:%s", path.data()); diff --git a/Snes9x/src/main/Main.cc b/Snes9x/src/main/Main.cc index 3842ef8d2..8dbe569f3 100755 --- a/Snes9x/src/main/Main.cc +++ b/Snes9x/src/main/Main.cc @@ -56,7 +56,7 @@ EmuSystem::NameFilterFunc EmuSystem::defaultFsFilter = Snes9xApp::Snes9xApp(ApplicationInitParams initParams, ApplicationContext &ctx): EmuApp{initParams, ctx}, snes9xSystem{ctx} {} -const BundledGameInfo &EmuSystem::bundledGameInfo(int idx) const +const BundledGameInfo &EmuSystem::bundledGameInfo(int) const { static constexpr BundledGameInfo info[] { @@ -86,7 +86,7 @@ MutablePixmapView Snes9xSystem::fbPixmapView(WSize size, bool useInterlaceFields return pix; } -void Snes9xSystem::renderFramebuffer(EmuVideo &video) +void Snes9xSystem::renderFramebuffer(EmuVideo&) { emuSysTask = {}; S9xDeinitUpdate(IPPU.RenderedScreenWidth, IPPU.RenderedScreenHeight); diff --git a/Snes9x/src/main/S9XApi.cc b/Snes9x/src/main/S9XApi.cc index 43b15f0a3..e696d0a42 100755 --- a/Snes9x/src/main/S9XApi.cc +++ b/Snes9x/src/main/S9XApi.cc @@ -170,11 +170,11 @@ const char *S9xBasename(const char *f) #else -void S9xHandlePortCommand(s9xcommand_t cmd, int16 data1, int16 data2) {} +void S9xHandlePortCommand(s9xcommand_t, int16, int16) {} bool8 S9xOpenSoundDevice() { return TRUE; } -const char *S9xGetCrosshair(int idx) { return nullptr; } +const char *S9xGetCrosshair(int) { return nullptr; } -std::string S9xGetFilenameInc(std::string_view, enum s9x_getdirtype dirtype) +std::string S9xGetFilenameInc(std::string_view, enum s9x_getdirtype) { logErr("S9xGetFilenameInc not used yet"); return {}; @@ -195,7 +195,7 @@ std::string S9xGetFilename(std::string_view ex, enum s9x_getdirtype dirtype) return std::string{sys.contentSaveFilePath(ex)}; } -std::string S9xGetFilename(std::string_view filename, std::string_view ex, enum s9x_getdirtype dirtype) +std::string S9xGetFilename(std::string_view, std::string_view ex, enum s9x_getdirtype dirtype) { return S9xGetFilename(ex, dirtype); } @@ -264,12 +264,12 @@ std::string S9xBasename(std::string_view f) #endif -bool S9xPollAxis(uint32 id, int16 *value) +bool S9xPollAxis(uint32, int16*) { return 0; } -bool S9xPollPointer(uint32 id, int16 *x, int16 *y) +bool S9xPollPointer(uint32, int16*, int16*) { return 0; } @@ -291,7 +291,7 @@ void S9xToggleSoundChannel(int c) S9xSetSoundControl(sound_switch); } -const char * S9xStringInput(const char *message) +const char * S9xStringInput(const char*) { bug_unreachable("should not be called"); return 0; diff --git a/Snes9x/src/main/input.cc b/Snes9x/src/main/input.cc index 89f0ed3a7..ad829c5ca 100644 --- a/Snes9x/src/main/input.cc +++ b/Snes9x/src/main/input.cc @@ -83,7 +83,7 @@ std::span Snes9xApp::keyCategories() KeyCategory{"Gamepad 2", gp2KeyInfo, 1}, KeyCategory{"Gamepad 3", gp3KeyInfo, 2}, KeyCategory{"Gamepad 4", gp4KeyInfo, 3}, - KeyCategory{"Gamepad 5", gp4KeyInfo, 4}, + KeyCategory{"Gamepad 5", gp5KeyInfo, 4}, }; return categories; } @@ -239,7 +239,7 @@ void Snes9xSystem::handleInputAction(EmuApp *, InputAction a) padData = setOrClearBits(padData, bit(a.code), a.isPushed()); } -void Snes9xSystem::clearInputBuffers(EmuInputView &view) +void Snes9xSystem::clearInputBuffers(EmuInputView&) { for(auto p : iotaCount(maxPlayers)) { @@ -587,7 +587,7 @@ bool Snes9xSystem::onPointerInputEnd(const Input::MotionEvent &e, Input::DragTra return false; } -SystemInputDeviceDesc Snes9xSystem::inputDeviceDesc(int idx) const +SystemInputDeviceDesc Snes9xSystem::inputDeviceDesc(int) const { static constexpr std::array gamepadComponents { diff --git a/Swan.emu/build.mk b/Swan.emu/build.mk index cff3767ff..749cb80bb 100644 --- a/Swan.emu/build.mk +++ b/Swan.emu/build.mk @@ -9,7 +9,7 @@ VPATH += $(EMUFRAMEWORK_PATH)/src/shared CPPFLAGS += $(MDFN_COMMON_CPPFLAGS) \ -I$(projectPath)/src -CXXFLAGS_WARN += -Wno-missing-field-initializers +CXXFLAGS_WARN += -Wno-missing-field-initializers -Wno-unused-parameter SRC += main/Main.cc \ main/options.cc \ diff --git a/Swan.emu/src/main/Main.cc b/Swan.emu/src/main/Main.cc index 0b362220a..a8c0d45b8 100755 --- a/Swan.emu/src/main/Main.cc +++ b/Swan.emu/src/main/Main.cc @@ -68,7 +68,7 @@ FS::FileString WsSystem::stateFilename(int slot, std::string_view name) const } size_t WsSystem::stateSize() { return stateSizeMDFN(); } -void WsSystem::readState(EmuApp &app, std::span buff) { readStateMDFN(app, buff); } +void WsSystem::readState(EmuApp&, std::span buff) { readStateMDFN(buff); } size_t WsSystem::writeState(std::span buff, SaveStateFlags flags) { return writeStateMDFN(buff, flags); } void WsSystem::loadBackupMemory(EmuApp &app) diff --git a/imagine/include/imagine/audio/OutputStream.hh b/imagine/include/imagine/audio/OutputStream.hh index 44b0944c5..18751f2aa 100755 --- a/imagine/include/imagine/audio/OutputStream.hh +++ b/imagine/include/imagine/audio/OutputStream.hh @@ -56,7 +56,7 @@ public: class NullOutputStream { public: - StreamError open(OutputStreamConfig config) { return {}; } + StreamError open(OutputStreamConfig) { return {}; } void play() {} void pause() {} void close() {} diff --git a/imagine/include/imagine/audio/android/AAudioOutputStream.hh b/imagine/include/imagine/audio/android/AAudioOutputStream.hh index 027057690..ebe9e487d 100644 --- a/imagine/include/imagine/audio/android/AAudioOutputStream.hh +++ b/imagine/include/imagine/audio/android/AAudioOutputStream.hh @@ -46,7 +46,7 @@ private: AAudioStream *stream{}; AAudioStreamBuilder *builder{}; OnSamplesNeededDelegate onSamplesNeeded{}; - CustomEvent disconnectEvent{"AAudioOutputStream::disconnectEvent"}; + CustomEvent disconnectEvent; bool isPlaying_{}; void setBuilderData(AAudioStreamBuilder *builder, Format format, bool lowLatencyMode); diff --git a/imagine/include/imagine/base/BaseWindow.hh b/imagine/include/imagine/base/BaseWindow.hh index a96d44a2f..102fb6ed5 100644 --- a/imagine/include/imagine/base/BaseWindow.hh +++ b/imagine/include/imagine/base/BaseWindow.hh @@ -62,7 +62,7 @@ protected: std::shared_ptr appDataPtr; std::shared_ptr rendererDataPtr; ConditionalMember screen_{}; - CustomEvent drawEvent{"Window::drawEvent"}; + CustomEvent drawEvent; WSize winSizePixels{}; // size of full window surface F2Size winSizeMM{}; // size in millimeter F2Size mmToPixelScaler{}; @@ -77,7 +77,6 @@ protected: ConditionalMemberOr softOrientation_{Rotation::UP}; F2Size smmPixelScaler() const; - void attachDrawEvent(); }; } diff --git a/imagine/include/imagine/base/EventLoop.hh b/imagine/include/imagine/base/EventLoop.hh index 5edf99687..e692c129b 100644 --- a/imagine/include/imagine/base/EventLoop.hh +++ b/imagine/include/imagine/base/EventLoop.hh @@ -39,37 +39,40 @@ public: constexpr EventLoop() = default; static EventLoop forThread(); static EventLoop makeForThread(); - void run(); + void run(const bool& condition); void stop(); explicit operator bool() const; +}; - void run(const auto &condition) - { - while((bool)condition) - { - run(); - } - } +struct FDEventSourceDesc +{ + const char* debugLabel{}; + std::optional eventLoop{}; + PollEventFlags events{pollEventInput}; }; class FDEventSource : public FDEventSourceImpl { public: - using FDEventSourceImpl::FDEventSourceImpl; - FDEventSource(MaybeUniqueFileDescriptor fd, EventLoop loop, PollEventDelegate callback, uint32_t events = POLLEV_IN): - FDEventSource(nullptr, std::move(fd), loop, callback, events) {} - FDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd, EventLoop loop, PollEventDelegate callback, uint32_t events = POLLEV_IN); - bool attach(PollEventDelegate callback, uint32_t events = POLLEV_IN); - bool attach(EventLoop loop, PollEventDelegate callback, uint32_t events = POLLEV_IN); - #if defined CONFIG_BASE_GLIB - bool attach(EventLoop, GSource *, uint32_t events = POLLEV_IN); - #endif + FDEventSource(MaybeUniqueFileDescriptor fd, FDEventSourceDesc desc, PollEventDelegate del): + FDEventSourceImpl{std::move(fd), desc, del}, + debugLabel_{desc.debugLabel ? desc.debugLabel : "unnamed"} + { + if(desc.eventLoop) + attach(*desc.eventLoop, desc.events); + } + FDEventSource(): FDEventSource{-1, {}, {}} {} + bool attach(EventLoop loop = {}, PollEventFlags events = pollEventInput); void detach(); - void setEvents(uint32_t events); - void dispatchEvents(uint32_t events); - void setCallback(PollEventDelegate callback); + void setEvents(PollEventFlags); + void dispatchEvents(PollEventFlags); + void setCallback(PollEventDelegate); bool hasEventLoop() const; int fd() const; + const char* debugLabel() const { return debugLabel_; } + +protected: + ConditionalMember debugLabel_{}; }; } diff --git a/imagine/include/imagine/base/FrameTimerInterface.hh b/imagine/include/imagine/base/FrameTimerInterface.hh index 149de631a..960e05df8 100644 --- a/imagine/include/imagine/base/FrameTimerInterface.hh +++ b/imagine/include/imagine/base/FrameTimerInterface.hh @@ -16,6 +16,7 @@ along with Imagine. If not, see */ #include +#include #include #include @@ -32,6 +33,7 @@ public: void scheduleVSync() { visit([](auto &e){ e.scheduleVSync(); }); } void cancel() { visit([](auto &e){ e.cancel(); }); } void setFrameRate(FrameRate rate) { visit([&](auto &e){ e.setFrameRate(rate); }); } + void setEventsOnThisThread(ApplicationContext ctx) { visit([&](auto &e){ e.setEventsOnThisThread(ctx); }); } }; } diff --git a/imagine/include/imagine/base/MessagePort.hh b/imagine/include/imagine/base/MessagePort.hh index 83be057ee..84efeeb27 100644 --- a/imagine/include/imagine/base/MessagePort.hh +++ b/imagine/include/imagine/base/MessagePort.hh @@ -104,13 +104,9 @@ public: static constexpr size_t MSG_SIZE = sizeof(MsgType); static_assert(MSG_SIZE < PIPE_BUF, "size of message too big for atomic writes"); - struct NullInit{}; - PipeMessagePort(const char *debugLabel = nullptr, int capacity = 0): pipe{debugLabel, (int)MSG_SIZE * capacity} {} - explicit constexpr PipeMessagePort(NullInit) {} - void attach(auto &&f) { attach(EventLoop::forThread(), IG_forward(f)); @@ -191,8 +187,7 @@ public: { if(span.empty()) return send(msg); - const auto bufferSize = MSG_SIZE + span.size_bytes(); - assert(bufferSize < PIPE_BUF); + assert(span.size_bytes() < PIPE_BUF); OutVector buffs[2]{std::span{&msg, 1}, span}; return pipe.sink().writeVector(buffs) != -1; } @@ -214,7 +209,7 @@ public: explicit operator bool() const { return (bool)pipe; } protected: - Pipe pipe{Pipe::NullInit{}}; + Pipe pipe; }; template diff --git a/imagine/include/imagine/base/PausableTimer.hh b/imagine/include/imagine/base/PausableTimer.hh index 0313bb8f5..5ac340b5d 100644 --- a/imagine/include/imagine/base/PausableTimer.hh +++ b/imagine/include/imagine/base/PausableTimer.hh @@ -24,16 +24,7 @@ template class PausableTimer { public: - struct NullInit{}; - - explicit constexpr PausableTimer(NullInit) {} - PausableTimer(Frequency f) : timer{CallbackDelegate{}} {} - PausableTimer(Frequency f, CallbackDelegate c): - timer{nullptr, c}, frequency{f} {} - PausableTimer(Frequency f, const char *debugLabel): - timer{debugLabel, CallbackDelegate{}}, frequency{f} {} - PausableTimer(Frequency f, const char *debugLabel, CallbackDelegate c): - timer{debugLabel, c}, frequency{f} {} + PausableTimer(Frequency f, TimerDesc desc, CallbackDelegate del):timer{desc, del}, frequency{f} {} void start() { diff --git a/imagine/include/imagine/base/Pipe.hh b/imagine/include/imagine/base/Pipe.hh index 600032bbe..713f09700 100644 --- a/imagine/include/imagine/base/Pipe.hh +++ b/imagine/include/imagine/base/Pipe.hh @@ -29,14 +29,11 @@ namespace IG class Pipe { public: - struct NullInit{}; - Pipe(int preferredSize = 0): Pipe(nullptr, preferredSize) {} Pipe(const char *debugLabel, int preferredSize = 0); - explicit constexpr Pipe(NullInit) {} PosixIO &source(); PosixIO &sink(); - void attach(EventLoop loop, PollEventDelegate del); + void attach(EventLoop loop); void detach(); bool hasData(); void dispatchSourceEvents(); @@ -44,6 +41,7 @@ public: void setReadNonBlocking(bool on); bool isReadNonBlocking() const; explicit operator bool() const; + const char* debugLabel() const { return fdSrc.debugLabel(); } void attach(auto &&f) { @@ -52,8 +50,7 @@ public: void attach(EventLoop loop, Callable auto &&f) { - attach(loop, - PollEventDelegate + fdSrc.setCallback(PollEventDelegate { [=](int fd, int) { @@ -63,10 +60,10 @@ public: return keep; } }); + attach(loop); } protected: - ConditionalMember debugLabel{}; std::array io; FDEventSource fdSrc; }; diff --git a/imagine/include/imagine/base/Screen.hh b/imagine/include/imagine/base/Screen.hh index 796fd6f84..a82d54544 100644 --- a/imagine/include/imagine/base/Screen.hh +++ b/imagine/include/imagine/base/Screen.hh @@ -50,6 +50,8 @@ public: bool containsOnFrame(OnFrameDelegate) const; size_t onFrameDelegates() const; void setVariableFrameTime(bool); + void setFrameEventsOnThisThread(); + void removeFrameEvents(); FrameParams makeFrameParams(SteadyClockTimePoint timestamp) const; bool frameRateIsReliable() const; FrameRate frameRate() const; diff --git a/imagine/include/imagine/base/SimpleFrameTimer.hh b/imagine/include/imagine/base/SimpleFrameTimer.hh index ddb98e16a..a3e501952 100644 --- a/imagine/include/imagine/base/SimpleFrameTimer.hh +++ b/imagine/include/imagine/base/SimpleFrameTimer.hh @@ -24,24 +24,32 @@ namespace IG class Screen; +class NullFrameTimer +{ +public: + void scheduleVSync() {} + void cancel() {} + void setFrameRate(FrameRate) {} + void setEventsOnThisThread(ApplicationContext); +}; + class SimpleFrameTimer final { public: - constexpr SimpleFrameTimer() = default; SimpleFrameTimer(Screen &screen, EventLoop loop = {}); void scheduleVSync(); void cancel(); void setFrameRate(FrameRate); + void setEventsOnThisThread(ApplicationContext); explicit operator bool() const { - return (bool)eventLoop; + return (bool)timer; } protected: - Timer timer{Timer::NullInit{}}; + Timer timer; Nanoseconds interval{}; - EventLoop eventLoop{}; bool requested{}; bool keepTimer{}; }; diff --git a/imagine/include/imagine/base/Timer.hh b/imagine/include/imagine/base/Timer.hh index a3fdfc6c7..c5583c648 100644 --- a/imagine/include/imagine/base/Timer.hh +++ b/imagine/include/imagine/base/Timer.hh @@ -31,46 +31,49 @@ namespace IG { +struct TimerDesc +{ + const char* debugLabel{}; + EventLoop eventLoop{}; +}; + struct Timer : public TimerImpl { public: using Time = TimePoint::duration; - struct NullInit{}; - using TimerImpl::TimerImpl; - explicit constexpr Timer(NullInit) {} - Timer() : Timer{CallbackDelegate{}} {} - Timer(const char *debugLabel): Timer{debugLabel, CallbackDelegate{}} {} - void run(Time time, Time repeatTime, bool isAbsoluteTime = false, EventLoop loop = {}, CallbackDelegate c = {}); + Timer(TimerDesc desc, CallbackDelegate del): TimerImpl{desc, del} {} + void run(Time time, Time repeatTime, bool isAbsoluteTime = false, CallbackDelegate c = {}); void cancel(); - void setCallback(CallbackDelegate c); + void setCallback(CallbackDelegate); + void setEventLoop(EventLoop); void dispatchEarly(); bool isArmed(); explicit operator bool() const; void runIn(ChronoDuration auto time, ChronoDuration auto repeatTime, - EventLoop loop = {}, CallbackDelegate f = {}) + CallbackDelegate f = {}) { - run(time, repeatTime, false, loop, f); + run(time, repeatTime, false, f); } void runAt(TimePoint time, ChronoDuration auto repeatTime, - EventLoop loop = {}, CallbackDelegate f = {}) + CallbackDelegate f = {}) { - run(time.time_since_epoch(), repeatTime, true, loop, f); + run(time.time_since_epoch(), repeatTime, true, f); } // non-repeating timer - void runIn(ChronoDuration auto time, EventLoop loop = {}, CallbackDelegate f = {}) + void runIn(ChronoDuration auto time, CallbackDelegate f = {}) { - run(time, Time{}, false, loop, f); + run(time, Time{}, false, f); } - void runAt(TimePoint time, EventLoop loop = {}, CallbackDelegate f = {}) + void runAt(TimePoint time, CallbackDelegate f = {}) { - run(time.time_since_epoch(), Time{}, true, loop, f); + run(time.time_since_epoch(), Time{}, true, f); } }; diff --git a/imagine/include/imagine/base/Window.hh b/imagine/include/imagine/base/Window.hh index d85dc6c05..07f142d09 100644 --- a/imagine/include/imagine/base/Window.hh +++ b/imagine/include/imagine/base/Window.hh @@ -46,6 +46,8 @@ public: void postFrameReady(); void postDrawToMainThread(int8_t priority = 0); void postFrameReadyToMainThread(); + void setFrameEventsOnThisThread(); + void removeFrameEvents(); static constexpr int8_t drawEventPriorityLocked = 127; // max value passed to setDrawEventPriority() also blocks implicit drawing int8_t setDrawEventPriority(int8_t = 0); int8_t drawEventPriority() const; diff --git a/imagine/include/imagine/base/android/AndroidApplication.hh b/imagine/include/imagine/base/android/AndroidApplication.hh index 42dda85d6..20fe87580 100644 --- a/imagine/include/imagine/base/android/AndroidApplication.hh +++ b/imagine/include/imagine/base/android/AndroidApplication.hh @@ -169,14 +169,13 @@ private: JNI::ClassMethod jFormatDateTime; std::variant inputDeviceChangeImpl; SystemOrientationChangedDelegate onSystemOrientationChanged; - Timer userActivityCallback{"userActivityCallback"}; + Timer userActivityCallback; using ProcessInputFunc = void (AndroidApplication::*)(AInputQueue *); ConditionalMember processInput_{&AndroidApplication::processInputWithHasEvents}; AInputQueue *inputQueue{}; Input::Device *builtinKeyboardDev{}; Input::Device *virtualDev{}; Choreographer choreographer{}; - pthread_key_t jEnvKey{}; uint32_t uiVisibilityFlags{}; int aHardKeyboardState{}; int aKeyboardType{}; diff --git a/imagine/include/imagine/base/android/AndroidInputDevice.hh b/imagine/include/imagine/base/android/AndroidInputDevice.hh index 3fa2f733e..39edff556 100644 --- a/imagine/include/imagine/base/android/AndroidInputDevice.hh +++ b/imagine/include/imagine/base/android/AndroidInputDevice.hh @@ -25,9 +25,8 @@ class AndroidInputDevice : public BaseDevice { public: AndroidInputDevice(int osId, InputDeviceTypeFlags, std::string name); - AndroidInputDevice(JNIEnv* env, jobject aDev, int osId, int src, - std::string name, int kbType, AxisFlags, - uint32_t vendorProductId, bool isPowerButton); + AndroidInputDevice(int osId, int src, std::string name, + int kbType, AxisFlags, uint32_t vendorProductId, bool isPowerButton); bool operator ==(AndroidInputDevice const& rhs) const; void setTypeFlags(InputDeviceTypeFlags f) { typeFlags_ = f; } std::span motionAxes() { return axis; } diff --git a/imagine/include/imagine/base/android/Choreographer.hh b/imagine/include/imagine/base/android/Choreographer.hh index dbfccbad5..5f4545c69 100644 --- a/imagine/include/imagine/base/android/Choreographer.hh +++ b/imagine/include/imagine/base/android/Choreographer.hh @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -31,17 +32,20 @@ class NativeChoreographer { public: constexpr NativeChoreographer() = default; - NativeChoreographer(AndroidApplication &); + NativeChoreographer(AndroidApplication&); void scheduleVSync(); + void cancel() { requested = false; } + void setEventsOnThisThread(ApplicationContext); explicit constexpr operator bool() const { return choreographer; } protected: using AChoreographerFrameCallback = void (*)(long frameTimeNanos, void* data); using PostFrameCallbackFunc = void (*)(AChoreographer*, AChoreographerFrameCallback, void* data); - AndroidApplication *appPtr{}; - AChoreographer *choreographer{}; + AndroidApplication* appPtr{}; + AChoreographer* choreographer{}; PostFrameCallbackFunc postFrameCallback{}; + AChoreographer* (*getInstance)(){}; bool requested{}; }; @@ -51,12 +55,16 @@ public: constexpr JavaChoreographer() = default; JavaChoreographer(AndroidApplication &, JNIEnv *, jobject baseActivity, jclass baseActivityClass); void scheduleVSync(); + void cancel() { requested = false; } + void setEventsOnThisThread(ApplicationContext); explicit constexpr operator bool() const { return frameHelper; } protected: - AndroidApplication *appPtr{}; - JNI::UniqueGlobalRef frameHelper{}; - JNI::InstMethod jPostFrame{}; + AndroidApplication* appPtr{}; + JNIEnv* jniEnv{}; + JNI::UniqueGlobalRef frameHelper; + JNI::InstMethod jPostFrame; + JNI::InstMethod jSetInstance; bool requested{}; }; @@ -68,8 +76,9 @@ public: ChoreographerFrameTimer(ChoreographerBase &choreographer): choreographerPtr{&choreographer} {} void scheduleVSync() { choreographerPtr->scheduleVSync(); } - void cancel() {} + void cancel() { choreographerPtr->cancel(); } void setFrameRate(FrameRate) {} + void setEventsOnThisThread(ApplicationContext ctx) { choreographerPtr->setEventsOnThisThread(ctx); } protected: ChoreographerBase *choreographerPtr{}; diff --git a/imagine/include/imagine/base/baseDefs.hh b/imagine/include/imagine/base/baseDefs.hh index 42b79d976..fa46f1189 100644 --- a/imagine/include/imagine/base/baseDefs.hh +++ b/imagine/include/imagine/base/baseDefs.hh @@ -250,7 +250,10 @@ class ApplicationContext; class Application; struct ApplicationInitParams; class FrameTimer; +struct FDEventSourceDesc; class FDEventSource; +class EventLoop; +struct TimerDesc; using WindowContainer = std::vector>; using ScreenContainer = std::vector>; @@ -320,14 +323,15 @@ class WindowEvent; using OnWindowEvent = DelegateFunc; using WindowInitDelegate = DelegateFunc; -using PollEventDelegate = DelegateFunc; +using PollEventFlags = int; +using PollEventDelegate = DelegateFunc; class CallbackDelegate : public DelegateFunc { public: using DelegateFuncBase::DelegateFuncBase; - constexpr CallbackDelegate(Callable auto &&f): + constexpr CallbackDelegate(Callable auto&& f): DelegateFuncBase { [=]() diff --git a/imagine/include/imagine/base/eventloop/ALooperEventLoop.hh b/imagine/include/imagine/base/eventloop/ALooperEventLoop.hh index c37696a63..347f3e8cb 100644 --- a/imagine/include/imagine/base/eventloop/ALooperEventLoop.hh +++ b/imagine/include/imagine/base/eventloop/ALooperEventLoop.hh @@ -25,27 +25,24 @@ namespace IG { -static const int POLLEV_IN = ALOOPER_EVENT_INPUT, POLLEV_OUT = ALOOPER_EVENT_OUTPUT, - POLLEV_ERR = ALOOPER_EVENT_ERROR, POLLEV_HUP = ALOOPER_EVENT_HANGUP; +constexpr int pollEventInput = ALOOPER_EVENT_INPUT, pollEventOutput = ALOOPER_EVENT_OUTPUT, + pollEventError = ALOOPER_EVENT_ERROR, pollEventHangUp = ALOOPER_EVENT_HANGUP; struct ALooperFDEventSourceInfo { PollEventDelegate callback{}; - ALooper *looper{}; + ALooper* looper{}; }; class ALooperFDEventSource { public: - constexpr ALooperFDEventSource() = default; - ALooperFDEventSource(MaybeUniqueFileDescriptor fd) : ALooperFDEventSource{nullptr, std::move(fd)} {} - ALooperFDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd); - ALooperFDEventSource(ALooperFDEventSource &&o) noexcept; - ALooperFDEventSource &operator=(ALooperFDEventSource &&o) noexcept; + ALooperFDEventSource(MaybeUniqueFileDescriptor, FDEventSourceDesc, PollEventDelegate); + ALooperFDEventSource(ALooperFDEventSource&&) noexcept; + ALooperFDEventSource &operator=(ALooperFDEventSource&&) noexcept; ~ALooperFDEventSource(); protected: - ConditionalMember debugLabel{}; std::unique_ptr info; MaybeUniqueFileDescriptor fd_; @@ -58,11 +55,11 @@ class ALooperEventLoop { public: constexpr ALooperEventLoop() = default; - constexpr ALooperEventLoop(ALooper *looper): looper{looper} {} - ALooper *nativeObject() const { return looper; } + constexpr ALooperEventLoop(ALooper* looper): looper{looper} {} + ALooper* nativeObject() const { return looper; } protected: - ALooper *looper{}; + ALooper* looper{}; }; using EventLoopImpl = ALooperEventLoop; diff --git a/imagine/include/imagine/base/eventloop/CFEventLoop.hh b/imagine/include/imagine/base/eventloop/CFEventLoop.hh index c44ac8add..6fbc44621 100644 --- a/imagine/include/imagine/base/eventloop/CFEventLoop.hh +++ b/imagine/include/imagine/base/eventloop/CFEventLoop.hh @@ -25,8 +25,8 @@ namespace IG { -static constexpr int UNUSED_EVENT = 0; -static constexpr int POLLEV_IN = kCFFileDescriptorReadCallBack, POLLEV_OUT = kCFFileDescriptorWriteCallBack, POLLEV_ERR = UNUSED_EVENT, POLLEV_HUP = UNUSED_EVENT; +constexpr int pollEventInput = kCFFileDescriptorReadCallBack, pollEventOutput = kCFFileDescriptorWriteCallBack, + pollEventError = 0, pollEventHangUp = 0; struct CFFDEventSourceInfo { @@ -41,15 +41,12 @@ struct CFFDEventSourceInfo class CFFDEventSource { public: - constexpr CFFDEventSource() = default; - CFFDEventSource(MaybeUniqueFileDescriptor fd) : CFFDEventSource{nullptr, std::move(fd)} {} - CFFDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd); - CFFDEventSource(CFFDEventSource &&o) noexcept; - CFFDEventSource &operator=(CFFDEventSource &&o) noexcept; + CFFDEventSource(MaybeUniqueFileDescriptor, FDEventSourceDesc, PollEventDelegate); + CFFDEventSource(CFFDEventSource&&) noexcept; + CFFDEventSource &operator=(CFFDEventSource&&) noexcept; ~CFFDEventSource(); protected: - ConditionalMember debugLabel{}; std::unique_ptr info; void deinit(); diff --git a/imagine/include/imagine/base/eventloop/FDCustomEvent.hh b/imagine/include/imagine/base/eventloop/FDCustomEvent.hh index a7da511cf..49b30e7ec 100644 --- a/imagine/include/imagine/base/eventloop/FDCustomEvent.hh +++ b/imagine/include/imagine/base/eventloop/FDCustomEvent.hh @@ -19,51 +19,44 @@ #include #include #include +#include namespace IG { +struct FDCustomEventDesc +{ + const char* debugLabel{}; + std::optional eventLoop; +}; + class FDCustomEvent { public: - struct NullInit{}; - - explicit constexpr FDCustomEvent(NullInit) {} - FDCustomEvent() : FDCustomEvent{nullptr} {} - FDCustomEvent(const char *debugLabel); - - FDCustomEvent(const char *debugLabel, EventLoop loop): - FDCustomEvent{debugLabel} - { - attach(loop); - } - - void attach(EventLoop loop, PollEventDelegate del); - - static constexpr PollEventDelegate makeDelegate(std::invocable auto &&f) + static constexpr PollEventDelegate wrapDelegate(std::invocable auto&& del) { return [=](int fd, int) { if(shouldPerformCallback(fd)) - f(); + del(); return true; }; } - void attach(EventLoop loop) { attach(loop, makeDelegate([](){})); } + FDCustomEvent(FDEventSourceDesc, PollEventDelegate); + FDCustomEvent(FDEventSourceDesc desc, std::invocable auto&& del):FDCustomEvent{desc, wrapDelegate(IG_forward(del))} {} - void attach(auto &&f) { attach({}, IG_forward(f)); } + void attach(EventLoop loop = {}) { fdSrc.attach(loop); } - void attach(EventLoop loop, std::invocable auto &&f) { attach(loop, makeDelegate(IG_forward(f))); } - - void setCallback(std::invocable auto &&f) + void setCallback(std::invocable auto&& del) { - fdSrc.setCallback(makeDelegate(IG_forward(f))); + fdSrc.setCallback(wrapDelegate(IG_forward(del))); } + const char* debugLabel() const { return fdSrc.debugLabel(); } + protected: - ConditionalMember debugLabel{}; - FDEventSource fdSrc{}; + FDEventSource fdSrc; static bool shouldPerformCallback(int fd); }; diff --git a/imagine/include/imagine/base/eventloop/GlibEventLoop.hh b/imagine/include/imagine/base/eventloop/GlibEventLoop.hh index 9146e6dd0..599125016 100644 --- a/imagine/include/imagine/base/eventloop/GlibEventLoop.hh +++ b/imagine/include/imagine/base/eventloop/GlibEventLoop.hh @@ -25,7 +25,8 @@ namespace IG { -static const int POLLEV_IN = G_IO_IN, POLLEV_OUT = G_IO_OUT, POLLEV_ERR = G_IO_ERR, POLLEV_HUP = G_IO_HUP; +constexpr int pollEventInput = G_IO_IN, pollEventOutput = G_IO_OUT, + pollEventError = G_IO_ERR, pollEventHangUp = G_IO_HUP; struct PollEventGSource : public GSource { @@ -46,16 +47,15 @@ using UniqueGSource = std::unique_ptr; class GlibFDEventSource { public: - constexpr GlibFDEventSource() = default; - GlibFDEventSource(MaybeUniqueFileDescriptor fd) : GlibFDEventSource{nullptr, std::move(fd)} {} - GlibFDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd); + GlibFDEventSource(MaybeUniqueFileDescriptor, FDEventSourceDesc, PollEventDelegate); protected: - ConditionalMember debugLabel{}; - UniqueGSource fdSource{}; + UniqueGSource source{}; gpointer tag{}; MaybeUniqueFileDescriptor fd_{}; - ConditionalMemberOr usingGlibSource{}; + + static PollEventDelegate& getDelegate(GSource*); + static UniqueGSource makeSource(PollEventDelegate); }; using FDEventSourceImpl = GlibFDEventSource; diff --git a/imagine/include/imagine/base/iphone/IOSScreen.hh b/imagine/include/imagine/base/iphone/IOSScreen.hh index 63f87630d..6c6966198 100644 --- a/imagine/include/imagine/base/iphone/IOSScreen.hh +++ b/imagine/include/imagine/base/iphone/IOSScreen.hh @@ -70,17 +70,21 @@ public: } #ifdef __OBJC__ - IOSScreen(UIScreen *screen); - UIScreen *uiScreen() const { return (__bridge UIScreen*)uiScreen_; } - CADisplayLink *displayLink() const { return (__bridge CADisplayLink*)displayLink_; } + IOSScreen(UIScreen*); + UIScreen* uiScreen() const { return (__bridge UIScreen*)uiScreen_; } + CADisplayLink* displayLink() const { return (__bridge CADisplayLink*)displayLink_; } + NSRunLoop* displayLinkRunLoop() const { return (__bridge NSRunLoop*)displayLinkRunLoop_; } #endif protected: void *uiScreen_{}; // UIScreen in ObjC void *displayLink_{}; // CADisplayLink in ObjC + void *displayLinkRunLoop_{}; // NSRunLoop in ObjC SteadyClockTime frameTime_{}; float frameRate_{}; bool displayLinkActive{}; + + void updateDisplayLinkRunLoop(); }; using ScreenImpl = IOSScreen; diff --git a/imagine/include/imagine/base/linux/DRMFrameTimer.hh b/imagine/include/imagine/base/linux/DRMFrameTimer.hh index 668cf165c..7a725541b 100644 --- a/imagine/include/imagine/base/linux/DRMFrameTimer.hh +++ b/imagine/include/imagine/base/linux/DRMFrameTimer.hh @@ -26,11 +26,11 @@ class Screen; class DRMFrameTimer { public: - constexpr DRMFrameTimer() = default; DRMFrameTimer(Screen &screen, EventLoop loop = {}); void scheduleVSync(); void cancel(); void setFrameRate(FrameRate) {} + void setEventsOnThisThread(ApplicationContext); static bool testSupport(); explicit operator bool() const @@ -39,7 +39,7 @@ public: } protected: - FDEventSource fdSrc{}; + FDEventSource fdSrc; Nanoseconds timestamp{}; bool requested{}; bool cancelled{}; diff --git a/imagine/include/imagine/base/linux/FBDevFrameTimer.hh b/imagine/include/imagine/base/linux/FBDevFrameTimer.hh index 9bf5ab43c..c989c9888 100644 --- a/imagine/include/imagine/base/linux/FBDevFrameTimer.hh +++ b/imagine/include/imagine/base/linux/FBDevFrameTimer.hh @@ -32,6 +32,7 @@ public: void scheduleVSync(); void cancel(); void setFrameRate(FrameRate) {} + void setEventsOnThisThread(ApplicationContext); static bool testSupport(); explicit operator bool() const @@ -40,7 +41,7 @@ public: } private: - FDEventSource fdSrc{}; + FDEventSource fdSrc; std::thread thread{}; std::binary_semaphore sem{0}; bool requested{}; diff --git a/imagine/include/imagine/base/linux/LinuxApplication.hh b/imagine/include/imagine/base/linux/LinuxApplication.hh index 371335870..76fb5e59c 100644 --- a/imagine/include/imagine/base/linux/LinuxApplication.hh +++ b/imagine/include/imagine/base/linux/LinuxApplication.hh @@ -58,7 +58,7 @@ public: void setAppPath(FS::PathString); protected: - FDEventSource evdevSrc{}; + FDEventSource evdevSrc; #if CONFIG_PACKAGE_DBUS GDBusConnection *gbus{}; unsigned openPathSub{}; diff --git a/imagine/include/imagine/base/timer/CFTimer.hh b/imagine/include/imagine/base/timer/CFTimer.hh index 6b860d168..0c5d27e3c 100644 --- a/imagine/include/imagine/base/timer/CFTimer.hh +++ b/imagine/include/imagine/base/timer/CFTimer.hh @@ -28,6 +28,7 @@ struct CFTimerInfo { CallbackDelegate callback{}; CFRunLoopRef loop{}; + CFRunLoopRef setLoop{}; }; class CFTimer @@ -35,15 +36,14 @@ class CFTimer public: using TimePoint = SteadyClockTimePoint; - constexpr CFTimer() = default; - CFTimer(CallbackDelegate c) : CFTimer{nullptr, c} {} - CFTimer(const char *debugLabel, CallbackDelegate c); - CFTimer(CFTimer &&o) noexcept; - CFTimer &operator=(CFTimer &&o) noexcept; + CFTimer(TimerDesc, CallbackDelegate); + CFTimer(CFTimer&&) noexcept; + CFTimer &operator=(CFTimer&&) noexcept; ~CFTimer(); + const char* debugLabel() const { return debugLabel_; } protected: - ConditionalMember debugLabel{}; + ConditionalMember debugLabel_{}; CFRunLoopTimerRef timer{}; std::unique_ptr info; diff --git a/imagine/include/imagine/base/timer/TimerFD.hh b/imagine/include/imagine/base/timer/TimerFD.hh index 96a0d146a..61492caab 100644 --- a/imagine/include/imagine/base/timer/TimerFD.hh +++ b/imagine/include/imagine/base/timer/TimerFD.hh @@ -30,16 +30,14 @@ class TimerFD public: using TimePoint = SteadyClockTimePoint; - constexpr TimerFD() = default; - TimerFD(CallbackDelegate c) : TimerFD{nullptr, c} {} - TimerFD(const char *debugLabel, CallbackDelegate c); + TimerFD(TimerDesc, CallbackDelegate); + const char* debugLabel() const { return fdSrc.debugLabel(); } protected: - ConditionalMember debugLabel{}; std::unique_ptr callback_; FDEventSource fdSrc; - bool arm(timespec ms, timespec repeatInterval, int flags, EventLoop loop); + bool arm(timespec ms, timespec repeatInterval, int flags); }; using TimerImpl = TimerFD; diff --git a/imagine/include/imagine/base/x11/XApplication.hh b/imagine/include/imagine/base/x11/XApplication.hh index 8f45be1b4..07360b8b6 100644 --- a/imagine/include/imagine/base/x11/XApplication.hh +++ b/imagine/include/imagine/base/x11/XApplication.hh @@ -68,8 +68,8 @@ public: private: xcb_connection_t* xConn{}; xcb_screen_t* xScr{}; - FDEventSource xEventSrc{}; SupportedFrameTimer supportedFrameTimer{}; + FDEventSource xEventSrc; XdndAtoms xdndAtom{}; // Input state diff --git a/imagine/include/imagine/base/x11/XScreen.hh b/imagine/include/imagine/base/x11/XScreen.hh index c816acaa5..6ec7b7087 100644 --- a/imagine/include/imagine/base/x11/XScreen.hh +++ b/imagine/include/imagine/base/x11/XScreen.hh @@ -34,6 +34,7 @@ namespace IG class ApplicationContext; using FrameTimerVariant = std::variant< + NullFrameTimer, SimpleFrameTimer, #if CONFIG_PACKAGE_LIBDRM DRMFrameTimer, diff --git a/imagine/include/imagine/bluetooth/BluezBluetoothAdapter.hh b/imagine/include/imagine/bluetooth/BluezBluetoothAdapter.hh index 5c4bf247d..3540c36cf 100644 --- a/imagine/include/imagine/bluetooth/BluezBluetoothAdapter.hh +++ b/imagine/include/imagine/bluetooth/BluezBluetoothAdapter.hh @@ -55,11 +55,11 @@ protected: #ifdef CONFIG_BLUETOOTH_SERVER struct L2CapServer { - constexpr L2CapServer() = default; - constexpr L2CapServer(uint32_t psm, int fd): psm(psm), fd(fd) {} + L2CapServer() = default; + L2CapServer(uint32_t psm, int fd): psm(psm), fd(fd) {} uint32_t psm = 0; int fd = -1; - FDEventSource connectSrc; + FDEventSource connectSrc{}; }; StaticArrayList serverList; #endif @@ -73,16 +73,15 @@ using BluetoothAdapterImpl = BluezBluetoothAdapter; class BluezBluetoothSocket { public: - constexpr BluezBluetoothSocket() = default; BluezBluetoothSocket(ApplicationContext) {} ~BluezBluetoothSocket(); void close(); - bool readPendingData(int events); + bool readPendingData(PollEventFlags); protected: FDEventSource fdSrc{}; int fd = -1; - void setupFDEvents(int events); + void setupFDEvents(PollEventFlags); }; using BluetoothSocketImpl = BluezBluetoothSocket; diff --git a/imagine/include/imagine/bluetooth/BtstackBluetoothAdapter.hh b/imagine/include/imagine/bluetooth/BtstackBluetoothAdapter.hh index 930ccfe68..9aee5d9e3 100644 --- a/imagine/include/imagine/bluetooth/BtstackBluetoothAdapter.hh +++ b/imagine/include/imagine/bluetooth/BtstackBluetoothAdapter.hh @@ -65,7 +65,7 @@ class BtstackBluetoothSocket { public: constexpr BtstackBluetoothSocket() = default; - BtstackBluetoothSocket(ApplicationContext ctx) {} + BtstackBluetoothSocket(ApplicationContext) {} ~BtstackBluetoothSocket(); void close(); const void *pin(uint32_t &size); diff --git a/imagine/include/imagine/bluetooth/IControlPad.hh b/imagine/include/imagine/bluetooth/IControlPad.hh index b100ceacc..6024f0604 100644 --- a/imagine/include/imagine/bluetooth/IControlPad.hh +++ b/imagine/include/imagine/bluetooth/IControlPad.hh @@ -51,10 +51,10 @@ private: char prevBtnData[2]{}; Input::Axis axis[4] { - {Input::Map::ICONTROLPAD, Input::AxisId::X, axisScaler}, // Left X Axis - {Input::Map::ICONTROLPAD, Input::AxisId::Y, axisScaler}, // Left Y Axis - {Input::Map::ICONTROLPAD, Input::AxisId::Z, axisScaler}, // Right X Axis - {Input::Map::ICONTROLPAD, Input::AxisId::RZ, axisScaler} // Right Y Axis + {Input::AxisId::X, axisScaler}, // Left X Axis + {Input::AxisId::Y, axisScaler}, // Left Y Axis + {Input::AxisId::Z, axisScaler}, // Right X Axis + {Input::AxisId::RZ, axisScaler} // Right Y Axis }; BluetoothAddr addr; diff --git a/imagine/include/imagine/bluetooth/PS3Controller.hh b/imagine/include/imagine/bluetooth/PS3Controller.hh index 592a0715c..28286c8c5 100644 --- a/imagine/include/imagine/bluetooth/PS3Controller.hh +++ b/imagine/include/imagine/bluetooth/PS3Controller.hh @@ -42,10 +42,10 @@ private: bool didSetLEDs = false; Input::Axis axis[4] { - {Input::Map::PS3PAD, Input::AxisId::X, axisScaler}, // Left X Axis - {Input::Map::PS3PAD, Input::AxisId::Y, axisScaler}, // Left Y Axis - {Input::Map::PS3PAD, Input::AxisId::Z, axisScaler}, // Right X Axis - {Input::Map::PS3PAD, Input::AxisId::RZ, axisScaler} // Right Y Axis + {Input::AxisId::X, axisScaler}, // Left X Axis + {Input::AxisId::Y, axisScaler}, // Left Y Axis + {Input::AxisId::Z, axisScaler}, // Right X Axis + {Input::AxisId::RZ, axisScaler} // Right Y Axis }; BluetoothSocket ctlSock, intSock; BluetoothAddr addr; diff --git a/imagine/include/imagine/bluetooth/Zeemote.hh b/imagine/include/imagine/bluetooth/Zeemote.hh index 9a16e6cb1..c6ba9fe6c 100644 --- a/imagine/include/imagine/bluetooth/Zeemote.hh +++ b/imagine/include/imagine/bluetooth/Zeemote.hh @@ -45,8 +45,8 @@ private: uint32_t packetSize = 0; Input::Axis axis[2] { - {Input::Map::ZEEMOTE, Input::AxisId::X, axisScaler}, - {Input::Map::ZEEMOTE, Input::AxisId::Y, axisScaler} + {Input::AxisId::X, axisScaler}, + {Input::AxisId::Y, axisScaler} }; BluetoothAddr addr; diff --git a/imagine/include/imagine/data-type/image/LibPNG.hh b/imagine/include/imagine/data-type/image/LibPNG.hh index 8a38529de..62ecad52c 100755 --- a/imagine/include/imagine/data-type/image/LibPNG.hh +++ b/imagine/include/imagine/data-type/image/LibPNG.hh @@ -53,7 +53,7 @@ protected: png_struct_def *png{}; png_info_def *info{}; bool premultiplyAlpha{}; - void setTransforms(PixelFormat outFormat, png_info_def *transInfo); + void setTransforms(PixelFormat outFormat); static bool supportUncommonConv; }; diff --git a/imagine/include/imagine/fs/AAssetFS.hh b/imagine/include/imagine/fs/AAssetFS.hh index be5aa1a0e..016105d12 100644 --- a/imagine/include/imagine/fs/AAssetFS.hh +++ b/imagine/include/imagine/fs/AAssetFS.hh @@ -75,12 +75,12 @@ protected: std::shared_ptr impl; }; -static const AAssetIterator &begin(const AAssetIterator &iter) +inline const AAssetIterator &begin(const AAssetIterator &iter) { return iter; } -static AAssetIterator end(const AAssetIterator &) +inline AAssetIterator end(const AAssetIterator &) { return {}; } diff --git a/imagine/include/imagine/fs/ArchiveFS.hh b/imagine/include/imagine/fs/ArchiveFS.hh index c66e695f8..c34e74442 100644 --- a/imagine/include/imagine/fs/ArchiveFS.hh +++ b/imagine/include/imagine/fs/ArchiveFS.hh @@ -57,12 +57,12 @@ private: std::shared_ptr impl; }; -static const auto &begin(const ArchiveIterator &iter) +inline const auto &begin(const ArchiveIterator &iter) { return iter; } -static auto end(const ArchiveIterator &) +inline auto end(const ArchiveIterator &) { return ArchiveIterator::Sentinel{}; } diff --git a/imagine/include/imagine/fs/FS.hh b/imagine/include/imagine/fs/FS.hh index 17af6d674..0d2c5f872 100644 --- a/imagine/include/imagine/fs/FS.hh +++ b/imagine/include/imagine/fs/FS.hh @@ -52,12 +52,12 @@ protected: std::shared_ptr impl; }; -static const directory_iterator &begin(const directory_iterator &iter) +inline const directory_iterator &begin(const directory_iterator& iter) { return iter; } -static directory_iterator end(const directory_iterator &) +inline directory_iterator end(const directory_iterator&) { return {}; } diff --git a/imagine/include/imagine/gfx/Buffer.hh b/imagine/include/imagine/gfx/Buffer.hh index 7d379f587..0211f64b3 100644 --- a/imagine/include/imagine/gfx/Buffer.hh +++ b/imagine/include/imagine/gfx/Buffer.hh @@ -66,7 +66,8 @@ public: bool hasTask() const { return BaseBuffer::taskPtr(); } void reset(BufferConfig config) { BaseBuffer::reset(config.toByteConfig()); } size_t size() const { return BaseBuffer::sizeBytes() / elemSize; } - MappedBuffer map(ssize_t offset, size_t size) { return {BaseBuffer::map(offset * elemSize, size * elemSize)}; } + MappedBuffer map(ssize_t offset, size_t size, BufferMapMode mode = BufferMapMode::unset) { return {BaseBuffer::map(offset * elemSize, size * elemSize, mode)}; } + MappedBuffer map(BufferMapMode mode) { return map(0, 0, mode); } MappedBuffer map() { return map(0, 0); } }; @@ -107,7 +108,7 @@ public: ObjectVertexBuffer(RendererTask &rTask, ObjectBufferConfig config): VertexBuffer{rTask, config.toBufferConfig()} {} void reset(ObjectBufferConfig config) { VertexBuffer::reset(config.toBufferConfig()); } size_t size() const { return BaseBuffer::size() / T::vertexCount; } - MappedBuffer map(ssize_t offset, size_t size) { return BaseBuffer::map(offset * T::vertexCount, size * T::vertexCount); } + MappedBuffer map(ssize_t offset, size_t size, BufferMapMode mode = BufferMapMode::unset) { return BaseBuffer::map(offset * T::vertexCount, size * T::vertexCount, mode); } void write(ssize_t offset, T obj) { obj.write(*this, offset); } void write(ssize_t offset, T::InitParams params) { write(offset, T{params}); } }; diff --git a/imagine/include/imagine/gfx/RendererCommands.hh b/imagine/include/imagine/gfx/RendererCommands.hh index 61fb16f2d..cc3aa896e 100644 --- a/imagine/include/imagine/gfx/RendererCommands.hh +++ b/imagine/include/imagine/gfx/RendererCommands.hh @@ -84,7 +84,6 @@ public: void setColor(float i) { setColor({i, i, i}); } void setColor(ColorName name) { setColor(Color4F{name}); } Color4F color() const; - void setImgMode(EnvMode); void setDither(bool on); void setSrgbFramebufferWrite(bool on); void setVisibleGeomFace(Faces); diff --git a/imagine/include/imagine/gfx/defs.hh b/imagine/include/imagine/gfx/defs.hh index 1974afbf2..9059ee463 100644 --- a/imagine/include/imagine/gfx/defs.hh +++ b/imagine/include/imagine/gfx/defs.hh @@ -248,4 +248,9 @@ enum class BufferType : uint8_t index, }; +enum class BufferMapMode +{ + unset, direct, indirect +}; + } diff --git a/imagine/include/imagine/gfx/opengl/GLBuffer.hh b/imagine/include/imagine/gfx/opengl/GLBuffer.hh index 95c9a086a..d4a47b1a3 100644 --- a/imagine/include/imagine/gfx/opengl/GLBuffer.hh +++ b/imagine/include/imagine/gfx/opengl/GLBuffer.hh @@ -53,7 +53,7 @@ public: GLBufferRef name() const { return buffer.get(); } void reset(ByteBufferConfig); size_t sizeBytes() const { return sizeBytes_; } - MappedByteBuffer map(ssize_t offset, size_t size); + MappedByteBuffer map(ssize_t offset, size_t size, BufferMapMode); void writeSubData(ssize_t offset, size_t size, const void *data); static void writeSubData(GLuint name, ssize_t offset, size_t size, const void *data); @@ -94,7 +94,7 @@ public: template void reset(const Buffer &buff, NativeBuffer idxs) { - initArray(buff.name(), idxs, sizeof(V), vertexLayoutEnableMask(), vertexLayoutDesc()); + initArray(buff.name(), idxs, sizeof(V), vertexLayoutDesc()); } RendererTask *taskPtr() const { return arr.get_deleter().rTaskPtr; } @@ -105,7 +105,7 @@ public: protected: UniqueGLVertexArrayRef arr; - void initArray(GLBufferRef vbo, GLBufferRef ibo, int stride, VertexLayoutFlags enabledLayout, VertexLayoutDesc layoutDesc); + void initArray(GLBufferRef vbo, GLBufferRef ibo, int stride, VertexLayoutDesc layoutDesc); }; using VertexArrayImpl = GLVertexArray; diff --git a/imagine/include/imagine/gfx/opengl/GLRenderer.hh b/imagine/include/imagine/gfx/opengl/GLRenderer.hh index 94f5847c1..f51006ec6 100644 --- a/imagine/include/imagine/gfx/opengl/GLRenderer.hh +++ b/imagine/include/imagine/gfx/opengl/GLRenderer.hh @@ -170,7 +170,7 @@ public: RendererTask mainTask; BasicEffect basicEffect_{}; Gfx::QuadIndexArray quadIndices; - CustomEvent releaseShaderCompilerEvent{CustomEvent::NullInit{}}; + CustomEvent releaseShaderCompilerEvent; GLRenderer(ApplicationContext); GLDisplay glDisplay() const; diff --git a/imagine/include/imagine/gfx/opengl/GLTask.hh b/imagine/include/imagine/gfx/opengl/GLTask.hh index 235dc7937..26fdbcb2e 100644 --- a/imagine/include/imagine/gfx/opengl/GLTask.hh +++ b/imagine/include/imagine/gfx/opengl/GLTask.hh @@ -127,7 +127,7 @@ protected: GLContext context{}; GLBufferConfig bufferConfig{}; OnExit onExit; - CommandMessagePort commandPort{CommandMessagePort::NullInit{}}; + CommandMessagePort commandPort; ThreadId threadId_{}; GLContext makeGLContext(GLManager &, GLBufferConfig bufferConf); diff --git a/imagine/include/imagine/gfx/opengl/GLTexture.hh b/imagine/include/imagine/gfx/opengl/GLTexture.hh index 4357f1e26..912c048bc 100644 --- a/imagine/include/imagine/gfx/opengl/GLTexture.hh +++ b/imagine/include/imagine/gfx/opengl/GLTexture.hh @@ -93,7 +93,7 @@ protected: bool canUseMipmaps(const Renderer &r) const; void updateFormatInfo(PixmapDesc, int8_t levels, GLenum target = GL_TEXTURE_2D); static void setSwizzleForFormatInGL(const Renderer &r, PixelFormatId format, GLuint tex); - static void setSamplerParamsInGL(const Renderer &r, SamplerParams params, GLenum target = GL_TEXTURE_2D); + static void setSamplerParamsInGL(SamplerParams params, GLenum target = GL_TEXTURE_2D); void updateLevelsForMipmapGeneration(); #ifdef __ANDROID__ void initWithEGLImage(EGLImageKHR, PixmapDesc, SamplerParams, bool isMutable); diff --git a/imagine/include/imagine/gui/FSPicker.hh b/imagine/include/imagine/gui/FSPicker.hh index 38fb51486..1da916c89 100644 --- a/imagine/include/imagine/gui/FSPicker.hh +++ b/imagine/include/imagine/gui/FSPicker.hh @@ -96,7 +96,7 @@ protected: std::vector fileUIStates; FS::RootedPath root; Gfx::Text msgText; - CustomEvent dirListEvent{"FSPicker::dirListEvent", {}}; + CustomEvent dirListEvent; TableUIState newFileUIState{}; Mode mode_{}; bool showHiddenFiles_{}; diff --git a/imagine/include/imagine/gui/MenuItem.hh b/imagine/include/imagine/gui/MenuItem.hh index 350d783d2..7a0fa1c60 100644 --- a/imagine/include/imagine/gui/MenuItem.hh +++ b/imagine/include/imagine/gui/MenuItem.hh @@ -62,43 +62,43 @@ public: constexpr MenuItemSelectDelegate(Callable auto &&f): DelegateFuncBase { - [=](Item &i, View &v, const Input::Event &e) { return callAndAutoReturnTrue(f, i, v, e); } + [=](Item& i, View& v, const Input::Event& e) { return callAndAutoReturnTrue(f, i, v, e); } } {} constexpr MenuItemSelectDelegate(std::invocable auto &&f): DelegateFuncBase { - [=](Item &i, View &v, const Input::Event &e) { return callAndAutoReturnTrue(f, i, e); } + [=](Item& i, View&, const Input::Event& e) { return callAndAutoReturnTrue(f, i, e); } } {} constexpr MenuItemSelectDelegate(std::invocable auto &&f): DelegateFuncBase { - [=](Item &i, View &v, const Input::Event &e) { return callAndAutoReturnTrue(f, v, e); } + [=](Item&, View& v, const Input::Event& e) { return callAndAutoReturnTrue(f, v, e); } } {} constexpr MenuItemSelectDelegate(std::invocable auto &&f): DelegateFuncBase { - [=](Item &i, View &v, const Input::Event &e) { return callAndAutoReturnTrue(f, i); } + [=](Item& i, View&, const Input::Event&) { return callAndAutoReturnTrue(f, i); } } {} constexpr MenuItemSelectDelegate(std::invocable auto &&f): DelegateFuncBase { - [=](Item &i, View &v, const Input::Event &e) { return callAndAutoReturnTrue(f, v); } + [=](Item&, View& v, const Input::Event&) { return callAndAutoReturnTrue(f, v); } } {} constexpr MenuItemSelectDelegate(std::invocable auto &&f): DelegateFuncBase { - [=](Item &i, View &v, const Input::Event &e) { return callAndAutoReturnTrue(f, e); } + [=](Item&, View&, const Input::Event& e) { return callAndAutoReturnTrue(f, e); } } {} constexpr MenuItemSelectDelegate(std::invocable auto &&f): DelegateFuncBase { - [=](Item &i, View &v, const Input::Event &e) { return callAndAutoReturnTrue(f); } + [=](Item&, View&, const Input::Event&) { return callAndAutoReturnTrue(f); } } {} }; @@ -359,7 +359,7 @@ public: onSelect { conf.onSelect ? conf.onSelect : - [this](MultiChoiceMenuItem &item, View &view, const Input::Event &e) + [](MultiChoiceMenuItem &item, View &view, const Input::Event &e) { item.defaultOnSelect(view, e); } diff --git a/imagine/include/imagine/gui/TextEntry.hh b/imagine/include/imagine/gui/TextEntry.hh index 74721001c..ca791f6e2 100644 --- a/imagine/include/imagine/gui/TextEntry.hh +++ b/imagine/include/imagine/gui/TextEntry.hh @@ -35,10 +35,10 @@ public: void setAcceptingInput(bool on); bool isAcceptingInput() const; bool inputEvent(View &parentView, const Input::Event &); - void prepareDraw(Gfx::Renderer &r); + void prepareDraw(); void draw(Gfx::RendererCommands &__restrict__) const; - void place(Gfx::Renderer &r); - void place(Gfx::Renderer &r, WRect rect); + void place(); + void place(WRect rect); const char *textStr() const; WRect bgRect() const; diff --git a/imagine/include/imagine/gui/ToastView.hh b/imagine/include/imagine/gui/ToastView.hh index 173c54347..edb2539e7 100644 --- a/imagine/include/imagine/gui/ToastView.hh +++ b/imagine/include/imagine/gui/ToastView.hh @@ -48,7 +48,7 @@ public: private: Gfx::Text text; - Timer unpostTimer{Timer::NullInit{}}; + Timer unpostTimer; Gfx::IQuads msgFrameQuads; WRect msgFrame{}; bool error = false; diff --git a/imagine/include/imagine/gui/viewDefs.hh b/imagine/include/imagine/gui/viewDefs.hh index 9cb1f37ed..2d6c67f79 100644 --- a/imagine/include/imagine/gui/viewDefs.hh +++ b/imagine/include/imagine/gui/viewDefs.hh @@ -71,7 +71,7 @@ public: { return visit(overloaded { - [&](const ItemsMessage& m) -> ItemReply { return std::size(items); }, + [&](const ItemsMessage&) -> ItemReply { return std::size(items); }, [&](const GetItemMessage& m) -> ItemReply { auto itemPtr = &indirect(std::data(items)[m.idx]); diff --git a/imagine/include/imagine/input/Axis.hh b/imagine/include/imagine/input/Axis.hh index 491fda6e5..621e87a0f 100644 --- a/imagine/include/imagine/input/Axis.hh +++ b/imagine/include/imagine/input/Axis.hh @@ -48,7 +48,7 @@ class Axis { public: constexpr Axis() = default; - Axis(Map, AxisId, float scaler = 1.f); + Axis(AxisId, float scaler = 1.f); void setEmulatesKeys(Map, bool); bool emulatesKeys() const; constexpr AxisId id() const { return id_; } diff --git a/imagine/include/imagine/input/Event.hh b/imagine/include/imagine/input/Event.hh index 5be441532..5028ffa49 100755 --- a/imagine/include/imagine/input/Event.hh +++ b/imagine/include/imagine/input/Event.hh @@ -180,6 +180,6 @@ struct DirectionKeys Key up{}, right{}, down{}, left{}; }; -DirectionKeys directionKeys(Map map = Map::SYSTEM); +DirectionKeys directionKeys(); } diff --git a/imagine/include/imagine/input/TextField.hh b/imagine/include/imagine/input/TextField.hh index b945850e8..ed2a71f0c 100644 --- a/imagine/include/imagine/input/TextField.hh +++ b/imagine/include/imagine/input/TextField.hh @@ -28,7 +28,7 @@ namespace IG::Input class TextFieldImpl { public: - constexpr TextFieldImpl(ApplicationContext, TextFieldDelegate, const char *initialText, const char *promptText, int fontSizePixels) {} + constexpr TextFieldImpl(ApplicationContext, TextFieldDelegate, const char*, const char*, int) {} }; } #endif diff --git a/imagine/include/imagine/input/evdev/EvdevInputDevice.hh b/imagine/include/imagine/input/evdev/EvdevInputDevice.hh index f72de0c00..be1e2b0a9 100644 --- a/imagine/include/imagine/input/evdev/EvdevInputDevice.hh +++ b/imagine/include/imagine/input/evdev/EvdevInputDevice.hh @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -32,22 +33,19 @@ namespace IG::Input class EvdevInputDevice : public BaseDevice { public: - EvdevInputDevice(); - EvdevInputDevice(int id, int fd, DeviceTypeFlags, std::string name, uint32_t vendorProductId); - ~EvdevInputDevice(); - bool setupJoystickBits(); + EvdevInputDevice(int id, UniqueFileDescriptor fd, DeviceTypeFlags, std::string name, uint32_t vendorProductId); std::span motionAxes() { return axis; }; - int fileDesc() const { return fd; } - static void addPollEvent(Device &, LinuxApplication &); + int fd() const { return fdSrc.fd(); } + static void addPollEvent(Device&, LinuxApplication&); protected: static constexpr unsigned AXIS_SIZE = 24; - int fd{-1}; StaticArrayList axis; std::array axisRangeOffset{}; - FDEventSource fdSrc{-1}; + FDEventSource fdSrc; - static void processInputEvents(Device &, LinuxApplication &, std::span events); + static void processInputEvents(Device&, LinuxApplication&, std::span); + bool setupJoystickBits(); }; } diff --git a/imagine/include/imagine/io/IOUtils-impl.hh b/imagine/include/imagine/io/IOUtils-impl.hh index 8f5164004..24b97c31a 100644 --- a/imagine/include/imagine/io/IOUtils-impl.hh +++ b/imagine/include/imagine/io/IOUtils-impl.hh @@ -97,7 +97,7 @@ ssize_t IOUtils::writeAtPosGeneric(const void *buff, size_t bytes, off_t off } template -FILE *IOUtils::toFileStream(const char *opentype) +FILE *IOUtils::toFileStream([[maybe_unused]] const char* opentype) { auto &io = *static_cast(this); if(!io) diff --git a/imagine/include/imagine/pixmap/Pixmap.hh b/imagine/include/imagine/pixmap/Pixmap.hh index 23fe8cb57..5bc6e7f42 100644 --- a/imagine/include/imagine/pixmap/Pixmap.hh +++ b/imagine/include/imagine/pixmap/Pixmap.hh @@ -168,7 +168,7 @@ public: auto destData = data(); auto destPitch = pitchBytes(); auto lineBytes = format().pixelBytes(pixmap.w()); - for(auto i : iotaCount(pixmap.h())) + for([[maybe_unused]] auto i : iotaCount(pixmap.h())) { memcpy(destData, srcData, lineBytes); srcData += pixmap.pitchBytes(); @@ -245,7 +245,7 @@ public: { auto lineBytes = format().pixelBytes(size.x); auto pitch = pitchBytes(); - for(auto i : iotaCount(size.y)) + for([[maybe_unused]] auto i : iotaCount(size.y)) { std::fill_n(destData, lineBytes, 0); destData += pitch; @@ -284,7 +284,7 @@ public: { auto dataPitchPixels = pitchPx(); auto width = w(); - for(auto y : iotaCount(h())) + for([[maybe_unused]] auto y : iotaCount(h())) { auto lineData = data; transformNOverlapped(lineData, width, lineData, @@ -352,7 +352,7 @@ protected: { auto srcPitchPixels = pixmap.pitchPx(); auto destPitchPixels = pitchPx(); - for(auto h : iotaCount(pixmap.h())) + for([[maybe_unused]] auto h : iotaCount(pixmap.h())) { auto destLineData = destData; auto srcLineData = srcData; @@ -367,7 +367,7 @@ protected: } } - static void invalidFormatConversion(auto dest, auto src) + static void invalidFormatConversion([[maybe_unused]] auto dest, [[maybe_unused]] auto src) { bug_unreachable("unimplemented conversion:%s -> %s", src.format().name(), dest.format().name()); } diff --git a/imagine/include/imagine/util/DelegateFunc.hh b/imagine/include/imagine/util/DelegateFunc.hh index 4f2dbeb0e..e82f62e92 100644 --- a/imagine/include/imagine/util/DelegateFunc.hh +++ b/imagine/include/imagine/util/DelegateFunc.hh @@ -40,7 +40,7 @@ public: constexpr DelegateFuncBase(std::nullptr_t) {} constexpr DelegateFuncBase(DelegateFuncDefaultInit): - DelegateFuncBase{[](Args ...args){ return R(); }} {} + DelegateFuncBase{[](Args...){ return R(); }} {} template F> requires (sizeof(F) <= StorageSize && Align >= std::alignment_of_v) diff --git a/imagine/include/imagine/util/container/RingBuffer.hh b/imagine/include/imagine/util/container/RingBuffer.hh index e4d97e27e..0b49b32b1 100644 --- a/imagine/include/imagine/util/container/RingBuffer.hh +++ b/imagine/include/imagine/util/container/RingBuffer.hh @@ -265,7 +265,7 @@ private: size_t bufferCapacity() const requires(!isFixedSize) { return buff.get_deleter().size; } size_t bufferCapacity() const requires isFixedSize { return buff.size(); } - void assertAddrRange(std::span span) const + void assertAddrRange([[maybe_unused]] std::span span) const { if(!conf.mirrored) { diff --git a/imagine/include/imagine/util/egl.hh b/imagine/include/imagine/util/egl.hh index ea9dc9f85..e1d18b46f 100644 --- a/imagine/include/imagine/util/egl.hh +++ b/imagine/include/imagine/util/egl.hh @@ -117,7 +117,7 @@ static void printEGLConf(EGLDisplay display, EGLConfig config) minSwap, maxSwap); } -static void printEGLConfs(EGLDisplay display) +inline void printEGLConfs(EGLDisplay display) { EGLConfig conf[96]; EGLint num = 0; @@ -129,7 +129,7 @@ static void printEGLConfs(EGLDisplay display) } } -static void printEGLConfsWithAttr(EGLDisplay display, const EGLint *attr) +inline void printEGLConfsWithAttr(EGLDisplay display, const EGLint *attr) { EGLConfig conf[96]; EGLint num = 0; @@ -141,13 +141,13 @@ static void printEGLConfsWithAttr(EGLDisplay display, const EGLint *attr) } } -static EGLBoolean eglSurfaceIsValid(EGLDisplay display, EGLSurface surface) +inline EGLBoolean eglSurfaceIsValid(EGLDisplay display, EGLSurface surface) { EGLint dummy; return eglQuerySurface(display, surface, EGL_CONFIG_ID, &dummy); } -static EGLSurface makeDummyPbuffer(EGLDisplay display, EGLConfig config) +inline EGLSurface makeDummyPbuffer(EGLDisplay display, EGLConfig config) { const EGLint attribs[]{EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; return eglCreatePbufferSurface(display, config, attribs); diff --git a/imagine/include/imagine/util/format.hh b/imagine/include/imagine/util/format.hh index 45dacc187..453d7542c 100644 --- a/imagine/include/imagine/util/format.hh +++ b/imagine/include/imagine/util/format.hh @@ -79,5 +79,5 @@ template struct std::formatter> { constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); } - constexpr auto format(const IG::UnusedType &obj, auto &ctx) const { return ctx.out(); } + constexpr auto format(const IG::UnusedType&, auto &ctx) const { return ctx.out(); } }; diff --git a/imagine/include/imagine/util/used.hh b/imagine/include/imagine/util/used.hh index 78bcb8992..37d1e7bc5 100644 --- a/imagine/include/imagine/util/used.hh +++ b/imagine/include/imagine/util/used.hh @@ -107,24 +107,24 @@ constexpr bool used(Unused auto &) { return false; } // invoke func if v's type doesn't satisfy the Unused concept template -constexpr auto doIfUsed(auto &v, auto &&func, R &&defaultReturn = 0) +constexpr auto doIfUsed(auto& v, auto&& func, [[maybe_unused]] R &&defaultReturn = 0) { return func(v); } template -constexpr auto doIfUsed(Unused auto &v, auto &&func, R &&defaultReturn = 0) +constexpr auto doIfUsed(Unused auto&, auto&&, R &&defaultReturn = 0) { return defaultReturn; } // same as above, but invoke defaultFunc if v's type is unused -constexpr auto doIfUsedOr(auto &v, auto &&func, auto &&defaultFunc) +constexpr auto doIfUsedOr(auto& v, auto&& func, auto&&) { return func(v); } -constexpr auto doIfUsedOr(Unused auto &v, auto &&func, auto &&defaultFunc) +constexpr auto doIfUsedOr(Unused auto&, auto&&, auto &&defaultFunc) { return defaultFunc(); } diff --git a/imagine/make/gcc-common.mk b/imagine/make/gcc-common.mk index 18bd9f9b1..fadca9ba2 100644 --- a/imagine/make/gcc-common.mk +++ b/imagine/make/gcc-common.mk @@ -18,7 +18,7 @@ endif # setup warnings -CFLAGS_WARN ?= -Wall -Wextra -Werror=return-type -Wno-comment -Wno-unused -Wno-unused-parameter +CFLAGS_WARN ?= -Wall -Wextra -Werror=return-type -Wno-comment CXXFLAGS_WARN ?= $(CFLAGS_WARN) -Woverloaded-virtual # setup optimizations diff --git a/imagine/make/gradle/app/build.gradle b/imagine/make/gradle/app/build.gradle index c9e6b661d..88de92d61 100644 --- a/imagine/make/gradle/app/build.gradle +++ b/imagine/make/gradle/app/build.gradle @@ -4,7 +4,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:8.3.0' + classpath 'com.android.tools.build:gradle:8.5.0' } } diff --git a/imagine/make/gradle/gradle/wrapper/gradle-wrapper.properties b/imagine/make/gradle/gradle/wrapper/gradle-wrapper.properties index 17655d0ef..19cfad969 100644 --- a/imagine/make/gradle/gradle/wrapper/gradle-wrapper.properties +++ b/imagine/make/gradle/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/imagine/make/linux-armv7-pandora-gcc.mk b/imagine/make/linux-armv7-pandora-gcc.mk index 9f4349444..b69c53a52 100644 --- a/imagine/make/linux-armv7-pandora-gcc.mk +++ b/imagine/make/linux-armv7-pandora-gcc.mk @@ -26,7 +26,7 @@ openGLAPI := gles staticLibcxx := 1 include $(buildSysPath)/linux-gcc.mk -CFLAGS_WARN += -Wno-psabi +CFLAGS_WARN += -Wno-psabi -Wno-unused-value CXXFLAGS_WARN += -Wno-register CFLAGS_CODEGEN += -mcpu=cortex-a8 -mfpu=neon -fno-stack-protector diff --git a/imagine/src/audio/alsa/alsa.cc b/imagine/src/audio/alsa/alsa.cc index e87bd7d2a..7da71068a 100644 --- a/imagine/src/audio/alsa/alsa.cc +++ b/imagine/src/audio/alsa/alsa.cc @@ -29,7 +29,7 @@ namespace IG::Audio constexpr SystemLogger log{"ALSA"}; -static const SampleFormat &alsaFormatToPcm(snd_pcm_format_t format) +constexpr const SampleFormat& alsaFormatToPcm(snd_pcm_format_t format) { switch(format) { @@ -42,7 +42,7 @@ static const SampleFormat &alsaFormatToPcm(snd_pcm_format_t format) } } -static snd_pcm_format_t pcmFormatToAlsa(const SampleFormat &format) +constexpr snd_pcm_format_t pcmFormatToAlsa(const SampleFormat& format) { switch(format.bytes()) { diff --git a/imagine/src/audio/alsa/alsautils.h b/imagine/src/audio/alsa/alsautils.h index f1e1d4cb3..ddfb8703c 100644 --- a/imagine/src/audio/alsa/alsautils.h +++ b/imagine/src/audio/alsa/alsautils.h @@ -2,7 +2,7 @@ #include -static const char *alsaPcmStateToString(snd_pcm_state_t state) +constexpr const char *alsaPcmStateToString(snd_pcm_state_t state) { switch(state) { @@ -19,7 +19,7 @@ static const char *alsaPcmStateToString(snd_pcm_state_t state) } } -static const char *alsaPcmWriteErrorToString(int error) +constexpr const char *alsaPcmWriteErrorToString(int error) { switch(error) { diff --git a/imagine/src/audio/android/AndroidManager.cc b/imagine/src/audio/android/AndroidManager.cc index d5d095f8c..ff765bafb 100644 --- a/imagine/src/audio/android/AndroidManager.cc +++ b/imagine/src/audio/android/AndroidManager.cc @@ -190,7 +190,7 @@ int AndroidManager::audioManagerIntProperty(JNIEnv* env, const char *propStr) co void AndroidManager::requestAudioFocus(JNIEnv* env, jobject baseActivity) const { - auto res = jRequestAudioFocus(env, audioManager, baseActivity, STREAM_MUSIC, AUDIOFOCUS_GAIN); + [[maybe_unused]] auto res = jRequestAudioFocus(env, audioManager, baseActivity, STREAM_MUSIC, AUDIOFOCUS_GAIN); //logMsg("%d from requestAudioFocus()", (int)res); } diff --git a/imagine/src/audio/android/aaudio.cc b/imagine/src/audio/android/aaudio.cc index 9a4b3f06f..41da7d958 100755 --- a/imagine/src/audio/android/aaudio.cc +++ b/imagine/src/audio/android/aaudio.cc @@ -127,12 +127,11 @@ static const char *streamStateStr(aaudio_stream_state_t state) } } -AAudioOutputStream::AAudioOutputStream(const Manager &manager) -{ - loadAAudioLib(manager); - AAudio_createStreamBuilder(&builder); - disconnectEvent.attach( - [this]() +AAudioOutputStream::AAudioOutputStream(const Manager &manager): + disconnectEvent + { + {.debugLabel = "AAudioOutputStream::disconnectEvent", .eventLoop = EventLoop::forThread()}, + [this] { if(!stream) return; @@ -145,7 +144,11 @@ AAudioOutputStream::AAudioOutputStream(const Manager &manager) return; } play(); - }); + } + } +{ + loadAAudioLib(manager); + AAudio_createStreamBuilder(&builder); } AAudioOutputStream::~AAudioOutputStream() @@ -270,14 +273,14 @@ void AAudioOutputStream::setBuilderData(AAudioStreamBuilder *builder, Format for if(AAudioStreamBuilder_setUsage) // present in API level 28+ AAudioStreamBuilder_setUsage(builder, AAUDIO_USAGE_GAME); AAudioStreamBuilder_setDataCallback(builder, - [](AAudioStream *stream, void *userData, void *audioData, int32_t numFrames) -> aaudio_data_callback_result_t + [](AAudioStream*, void* userData, void* audioData, int32_t numFrames) -> aaudio_data_callback_result_t { auto thisPtr = (AAudioOutputStream*)userData; thisPtr->onSamplesNeeded(audioData, numFrames); return AAUDIO_CALLBACK_RESULT_CONTINUE; }, this); AAudioStreamBuilder_setErrorCallback(builder, - [](AAudioStream *stream, void *userData, aaudio_result_t error) + [](AAudioStream*, void* userData, aaudio_result_t error) { //log.error("got error:{} callback", streamResultStr(error)); if(error == AAUDIO_ERROR_DISCONNECTED) diff --git a/imagine/src/audio/coreaudio/AvfManager.mm b/imagine/src/audio/coreaudio/AvfManager.mm index f057fe79a..2c7cef00c 100644 --- a/imagine/src/audio/coreaudio/AvfManager.mm +++ b/imagine/src/audio/coreaudio/AvfManager.mm @@ -28,7 +28,7 @@ static void handleEndInterruption() namespace IG::Audio { -AvfManager::AvfManager(ApplicationContext ctx_) {} +AvfManager::AvfManager(ApplicationContext) {} SampleFormat Manager::nativeSampleFormat() const { @@ -105,7 +105,7 @@ std::vector Manager::audioAPIs() const return {{"Core Audio", Api::COREAUDIO}}; } -Api Manager::makeValidAPI(Api api) const +Api Manager::makeValidAPI(Api) const { return Api::COREAUDIO; } diff --git a/imagine/src/audio/coreaudio/coreaudio.cc b/imagine/src/audio/coreaudio/coreaudio.cc index d20aa4c30..9830935f6 100644 --- a/imagine/src/audio/coreaudio/coreaudio.cc +++ b/imagine/src/audio/coreaudio/coreaudio.cc @@ -50,7 +50,7 @@ CAOutputStream::CAOutputStream() AURenderCallbackStruct renderCallbackProp { [](void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) -> OSStatus + [[maybe_unused]] const AudioTimeStamp *inTimeStamp, [[maybe_unused]] UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) -> OSStatus { auto thisPtr = static_cast(inRefCon); auto *buff = ioData->mBuffers[0].mData; diff --git a/imagine/src/base/android/ALooperEventLoop.cc b/imagine/src/base/android/ALooperEventLoop.cc index 6fe03cfb2..f9aabd684 100644 --- a/imagine/src/base/android/ALooperEventLoop.cc +++ b/imagine/src/base/android/ALooperEventLoop.cc @@ -15,6 +15,7 @@ #include #include +#include #include #include @@ -22,6 +23,7 @@ namespace IG { constexpr SystemLogger log{"EventLoop"}; +extern pthread_key_t jEnvPThreadKey; static int eventCallback(int fd, int events, void *data) { @@ -34,11 +36,9 @@ static int eventCallback(int fd, int events, void *data) return keep; } -ALooperFDEventSource::ALooperFDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd): - debugLabel{debugLabel ? debugLabel : "unnamed"}, - info{std::make_unique()}, - fd_{std::move(fd)} -{} +ALooperFDEventSource::ALooperFDEventSource(MaybeUniqueFileDescriptor fd, FDEventSourceDesc, PollEventDelegate del): + info{fd.get() != -1 ? std::make_unique(del) : std::unique_ptr{}}, + fd_{std::move(fd)} {} ALooperFDEventSource::ALooperFDEventSource(ALooperFDEventSource &&o) noexcept { @@ -50,7 +50,6 @@ ALooperFDEventSource &ALooperFDEventSource::operator=(ALooperFDEventSource &&o) deinit(); info = std::move(o.info); fd_ = std::move(o.fd_); - debugLabel = o.debugLabel; return *this; } @@ -59,61 +58,60 @@ ALooperFDEventSource::~ALooperFDEventSource() deinit(); } -bool FDEventSource::attach(EventLoop loop, PollEventDelegate callback, uint32_t events) +bool FDEventSource::attach(EventLoop loop, PollEventFlags events) { - log.info("adding fd:{} to looper:{} ({})", fd_.get(), (void*)loop.nativeObject(), debugLabel); - assumeExpr(info); + if(fd_.get() == -1) [[unlikely]] + { + log.error("trying to attach without valid fd"); + return false; + } detach(); + log.info("adding fd:{} to looper:{} ({})", fd_.get(), (void*)loop.nativeObject(), debugLabel()); if(!loop) loop = EventLoop::forThread(); + assumeExpr(info); + info->looper = loop.nativeObject(); if(auto res = ALooper_addFd(loop.nativeObject(), fd_, ALOOPER_POLL_CALLBACK, events, eventCallback, info.get()); res != 1) { return false; } - info->callback = callback; - info->looper = loop.nativeObject(); return true; } void FDEventSource::detach() { - if(!info || !info->looper) + if(!hasEventLoop()) return; - log.info("removing fd:{} from looper ({})", fd_.get(), debugLabel); + log.info("removing fd:{} from looper ({})", fd_.get(), debugLabel()); ALooper_removeFd(info->looper, fd_); info->looper = {}; } -void FDEventSource::setEvents(uint32_t events) +void FDEventSource::setEvents(PollEventFlags events) { if(!hasEventLoop()) { - log.error("trying to set events while not attached to event loop"); + log.error("trying to set events without event loop"); return; } ALooper_addFd(info->looper, fd_, ALOOPER_POLL_CALLBACK, events, eventCallback, info.get()); } -void FDEventSource::dispatchEvents(uint32_t events) +void FDEventSource::dispatchEvents(PollEventFlags events) { eventCallback(fd(), events, info.get()); } void FDEventSource::setCallback(PollEventDelegate callback) { - if(!hasEventLoop()) - { - log.error("trying to set callback while not attached to event loop"); - return; - } + assumeExpr(info); info->callback = callback; } bool FDEventSource::hasEventLoop() const { - assumeExpr(info); - return info->looper; + return info && info->looper; } int FDEventSource::fd() const @@ -148,20 +146,56 @@ static const char *aLooperPollResultStr(int res) return "Unknown"; } -void EventLoop::run() +struct JavaLooperContext { - int res; - do + JNIEnv* env{}; + jclass cls{}; + jobject looper{}; +}; + +static JavaLooperContext javaLooperContext() +{ + auto env = static_cast(pthread_getspecific(jEnvPThreadKey)); + if(!env) + return {}; + auto looperClass = env->FindClass("android/os/Looper"); + assert(looperClass); + JNI::ClassMethod myLooper{env, looperClass, "myLooper", "()Landroid/os/Looper;"}; + return {env, looperClass, myLooper(env, looperClass)}; +} + +void EventLoop::run(const bool& condition) +{ + if(auto jLooperCtx = javaLooperContext(); jLooperCtx.looper) { - res = ALooper_pollOnce(-1, nullptr, nullptr, nullptr); - } while(res == ALOOPER_POLL_CALLBACK); - if(res != ALOOPER_POLL_WAKE) - log.debug("ALooper_pollAll returned:{}", aLooperPollResultStr(res)); + JNI::ClassMethod loop{jLooperCtx.env, jLooperCtx.cls, "loop", "()V"}; + while(condition) + { + loop(jLooperCtx.env, jLooperCtx.cls); + } + } + else + { + while(condition) + { + int res = ALooper_pollOnce(-1, nullptr, nullptr, nullptr); + if(res != ALOOPER_POLL_CALLBACK && res != ALOOPER_POLL_WAKE) + log.error("ALooper_pollOnce returned:{}", aLooperPollResultStr(res)); + } + } } void EventLoop::stop() { - ALooper_wake(looper); + if(auto jLooperCtx = javaLooperContext(); jLooperCtx.looper) + { + JNI::InstMethod quit{jLooperCtx.env, jLooperCtx.cls, "quit", "()V"}; + quit(jLooperCtx.env, jLooperCtx.looper); + } + else + { + ALooper_wake(looper); + } } EventLoop::operator bool() const diff --git a/imagine/src/base/android/AndroidScreen.cc b/imagine/src/base/android/AndroidScreen.cc index 7b23b69eb..adc479bb2 100644 --- a/imagine/src/base/android/AndroidScreen.cc +++ b/imagine/src/base/android/AndroidScreen.cc @@ -13,7 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "Screen" #include #include #include @@ -28,6 +27,7 @@ namespace IG { +constexpr SystemLogger log{"Screen"}; static JNI::InstMethod jSetListener{}; static JNI::InstMethod jEnumDisplays{}; @@ -44,13 +44,13 @@ void AndroidApplication::initScreens(JNIEnv *env, jobject baseActivity, jclass b { "displayAdd", "(JILandroid/view/Display;FJLandroid/util/DisplayMetrics;)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong nActivityAddr, jint id, jobject disp, jfloat refreshRate, jlong presentationDeadline, jobject metrics) + +[](JNIEnv* env, jobject, jlong nActivityAddr, jint id, jobject disp, jfloat refreshRate, jlong presentationDeadline, jobject metrics) { ApplicationContext ctx{(ANativeActivity*)nActivityAddr}; auto &app = ctx.application(); if(app.findScreen(id)) { - logMsg("screen id:%d already in device list", id); + log.info("screen id:{} already in device list", id); return; } app.addScreen(ctx, std::make_unique(ctx, @@ -60,14 +60,14 @@ void AndroidApplication::initScreens(JNIEnv *env, jobject baseActivity, jclass b { "displayChange", "(JIF)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong nActivityAddr, jint id, jfloat refreshRate) + +[](JNIEnv*, jobject, jlong nActivityAddr, jint id, jfloat refreshRate) { ApplicationContext ctx{(ANativeActivity*)nActivityAddr}; auto &app = ctx.application(); auto screen = app.findScreen(id); if(!screen) { - logWarn("screen id:%d changed but isn't in device list", id); + log.warn("screen id:{} changed but isn't in device list", id); return; } screen->updateFrameRate(refreshRate); @@ -77,11 +77,11 @@ void AndroidApplication::initScreens(JNIEnv *env, jobject baseActivity, jclass b { "displayRemove", "(JI)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong nActivityAddr, jint id) + +[](JNIEnv*, jobject, jlong nActivityAddr, jint id) { ApplicationContext ctx{(ANativeActivity*)nActivityAddr}; auto &app = ctx.application(); - logMsg("screen id:%d removed", id); + log.info("screen id:{} removed", id); app.removeScreen(ctx, id, true); } } @@ -92,13 +92,13 @@ void AndroidApplication::initScreens(JNIEnv *env, jobject baseActivity, jclass b addOnExit([env, &displayListenerHelper = displayListenerHelper](ApplicationContext ctx, bool backgrounded) { ctx.application().removeSecondaryScreens(); - logMsg("unregistering display listener"); + log.info("unregistering display listener"); jSetListener(env, displayListenerHelper, false); if(backgrounded) { ctx.addOnResume([env, &displayListenerHelper](ApplicationContext ctx, bool) { - logMsg("registering display listener"); + log.info("registering display listener"); jSetListener(env, displayListenerHelper, true); jEnumDisplays(env, ctx.baseActivityObject(), (jlong)ctx.aNativeActivityPtr()); return false; @@ -121,14 +121,14 @@ AndroidScreen::AndroidScreen(ApplicationContext ctx, InitParams params) if(id == 0) { id_ = 0; - logMsg("init main display with starting rotation:%d", (int)rotation); + log.info("init main display with starting rotation:{}", (int)rotation); ctx.application().setCurrentRotation(ctx, rotation); isStraightRotation = !isSideways(rotation); } else { id_ = id; - logMsg("init display with id:%d", id_); + log.info("init display with id:{}", id_); } presentationDeadline_ = presentationDeadline; updateFrameRate(refreshRate); @@ -164,8 +164,8 @@ AndroidScreen::AndroidScreen(ApplicationContext ctx, InitParams params) assert(densityDPI_); scaledDensityDPI_ = 160.*env->GetFloatField(metrics, jScaledDensity); assert(scaledDensityDPI_); - logMsg("screen with size %dx%d, density DPI:%f, scaled density DPI:%f", - widthPixels, heightPixels, (double)densityDPI_, (double)scaledDensityDPI_); + log.info("screen with size:{}x{}, density DPI:{}, scaled density DPI:{}", + widthPixels, heightPixels, densityDPI_, scaledDensityDPI_); if(Config::DEBUG_BUILD) { auto jXDPI = env->GetFieldID(jDisplayMetricsCls, "xdpi", "F"); @@ -176,9 +176,9 @@ AndroidScreen::AndroidScreen(ApplicationContext ctx, InitParams params) if(!isStraightRotation) std::swap(metricsXDPI, metricsYDPI); auto jDensityDPI = env->GetFieldID(jDisplayMetricsCls, "densityDpi", "I"); - logMsg("DPI:%fx%f, densityDPI:%d, refresh rate:%.2fHz", + log.info("DPI:{}x{}, densityDPI:{}, refresh rate:{}Hz", metricsXDPI, metricsYDPI, env->GetIntField(metrics, jDensityDPI), - (double)frameRate_); + frameRate_); } if(!isStraightRotation) std::swap(widthPixels, heightPixels); @@ -190,11 +190,11 @@ void AndroidScreen::updateFrameRate(float rate) { if(frameRate_ && rate != frameRate_) { - logMsg("refresh rate updated to:%.2f on screen:%d", rate, id()); + log.info("refresh rate updated to:{} on screen:{}", rate, id()); } if(rate < 20.f || rate > 250.f) // sanity check in case device has a junk value { - logWarn("ignoring unusual refresh rate:%f", rate); + log.warn("ignoring unusual refresh rate:{}", rate); rate = 60; reliableFrameRate = false; } @@ -215,8 +215,8 @@ void AndroidScreen::updateSupportedFrameRates(ApplicationContext ctx, JNIEnv *en supportedFrameRates_.assign(rates.begin(), rates.end()); if constexpr(Config::DEBUG_BUILD) { - logDMsg("screen %d supports %zu rate(s):", id_, rates.size()); - for(auto r : rates) { logDMsg("%f", r); } + log.debug("screen {} supports {} rate(s):", id_, rates.size()); + for(auto r : rates) { log.debug("{}", r); } } env->ReleaseFloatArrayElements(jRates, rates.data(), 0); } @@ -245,10 +245,21 @@ void Screen::setVariableFrameTime(bool useVariableTime) application().emplaceFrameTimer(frameTimer, *static_cast(this), useVariableTime); } -void Screen::setFrameInterval(int interval) +void Screen::setFrameEventsOnThisThread() +{ + unpostFrame(); + frameTimer.setEventsOnThisThread(appContext()); +} + +void Screen::removeFrameEvents() +{ + unpostFrame(); +} + +void Screen::setFrameInterval([[maybe_unused]] int interval) { // TODO - //logMsg("setting frame interval %d", (int)interval); + //log,info("setting frame interval:{}", interval); assert(interval >= 1); } diff --git a/imagine/src/base/android/AndroidWindow.cc b/imagine/src/base/android/AndroidWindow.cc index cc58e180c..b8b776ae4 100644 --- a/imagine/src/base/android/AndroidWindow.cc +++ b/imagine/src/base/android/AndroidWindow.cc @@ -44,7 +44,7 @@ static void initPresentationJNI(JNIEnv* env, jobject presentation) { "onSurfaceCreated", "(JLandroid/view/Surface;)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong windowAddr, jobject surface) + +[](JNIEnv* env, jobject, jlong windowAddr, jobject surface) { auto nWin = ANativeWindow_fromSurface(env, surface); auto &win = *((Window*)windowAddr); @@ -54,7 +54,7 @@ static void initPresentationJNI(JNIEnv* env, jobject presentation) { "onSurfaceRedrawNeeded", "(J)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong windowAddr) + +[](JNIEnv*, jobject, jlong windowAddr) { auto &win = *((Window*)windowAddr); win.systemRequestsRedraw(true); @@ -63,7 +63,7 @@ static void initPresentationJNI(JNIEnv* env, jobject presentation) { "onSurfaceDestroyed", "(J)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong windowAddr) + +[](JNIEnv*, jobject, jlong windowAddr) { auto &win = *((Window*)windowAddr); ANativeWindow_release(win.nativeObject()); @@ -73,7 +73,7 @@ static void initPresentationJNI(JNIEnv* env, jobject presentation) { "onWindowDismiss", "(J)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong windowAddr) + +[](JNIEnv*, jobject, jlong windowAddr) { auto &win = *((Window*)windowAddr); win.dismiss(); @@ -119,7 +119,7 @@ bool Window::setValidOrientations(Orientations o) return true; } -bool Window::requestOrientationChange(Rotation o) +bool Window::requestOrientationChange(Rotation) { // no-op, OS manages orientation changes return false; @@ -334,7 +334,7 @@ void AndroidWindow::setContentRect(WindowRect rect, WSize winSize) else { contentRect.start(*static_cast(this), contentRect.value(), rect, Milliseconds{165}, - [](auto &win, auto newRect) + [](auto &win, [[maybe_unused]] auto newRect) { win.surfaceChangeFlags.contentRectResized = true; win.setNeedsDraw(true); @@ -343,9 +343,9 @@ void AndroidWindow::setContentRect(WindowRect rect, WSize winSize) win.postDraw(); } -void Window::setTitle(const char *name) {} +void Window::setTitle(const char*) {} -void Window::setAcceptDnd(bool on) {} +void Window::setAcceptDnd(bool) {} void WindowConfig::setFormat(PixelFormat fmt) { diff --git a/imagine/src/base/android/Application.cc b/imagine/src/base/android/Application.cc index 852cefe7c..9d8dbc6fa 100644 --- a/imagine/src/base/android/Application.cc +++ b/imagine/src/base/android/Application.cc @@ -44,13 +44,25 @@ namespace IG constexpr SystemLogger log{"App"}; static JavaVM* jVM{}; static void *mainLibHandle{}; -static constexpr bool unloadNativeLibOnDestroy{}; +[[maybe_unused]] constexpr bool unloadNativeLibOnDestroy{}; pid_t mainThreadId{}; +pthread_key_t jEnvPThreadKey{}; static void setNativeActivityCallbacks(ANativeActivity *nActivity); AndroidApplication::AndroidApplication(ApplicationInitParams initParams): - BaseApplication{({initParams.nActivity->instance = this; initParams.nActivity;})} + BaseApplication{({initParams.nActivity->instance = this; initParams.nActivity;})}, + userActivityCallback + { + {.debugLabel = "userActivityCallback"}, + [this, ctx = ApplicationContext{initParams.nActivity}] + { + if(!keepScreenOn) + { + jSetWinFlags(ctx.mainThreadJniEnv(), ctx.baseActivityObject(), 0, AWINDOW_FLAG_KEEP_SCREEN_ON); + } + } + } { ApplicationContext ctx{initParams.nActivity}; auto env = ctx.mainThreadJniEnv(); @@ -113,7 +125,7 @@ MutablePixmapView makePixmapView(JNIEnv *env, jobject bitmap, void *pixels, Pixe return {{{(int)info.width, (int)info.height}, format}, pixels, {(int)info.stride, MutablePixmapView::Units::BYTE}}; } -void ApplicationContext::exit(int returnVal) +void ApplicationContext::exit(int) { // TODO: return exit value as activity result application().setExitingActivityState(); @@ -213,7 +225,7 @@ bool AndroidApplication::forEachInDirectoryUri(JNIEnv *env, jobject baseActivity return true; } -static FS::PathString mainSOPath(ApplicationContext ctx) +inline FS::PathString mainSOPath(ApplicationContext ctx) { if(ctx.androidSDK() < 24) { @@ -307,7 +319,7 @@ const char *aHardwareBufferFormatStr(uint32_t format) void AndroidApplication::initActivity(JNIEnv *env, jobject baseActivity, jclass baseActivityClass, int32_t androidSDK) { - pthread_key_create(&jEnvKey, + pthread_key_create(&jEnvPThreadKey, [](void *) { if(!jVM) @@ -318,7 +330,7 @@ void AndroidApplication::initActivity(JNIEnv *env, jobject baseActivity, jclass } jVM->DetachCurrentThread(); }); - pthread_setspecific(jEnvKey, env); + pthread_setspecific(jEnvPThreadKey, env); // BaseActivity JNI functions jSetRequestedOrientation = {env, baseActivityClass, "setRequestedOrientation", "(I)V"}; @@ -356,7 +368,7 @@ void AndroidApplication::initActivity(JNIEnv *env, jobject baseActivity, jclass { "onContentRectChanged", "(JIIIIII)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong windowAddr, jint x, jint y, jint x2, jint y2, jint winWidth, jint winHeight) + +[](JNIEnv*, jobject, jlong windowAddr, jint x, jint y, jint x2, jint y2, jint winWidth, jint winHeight) { assumeExpr(windowAddr); auto win = (Window*)windowAddr; @@ -387,13 +399,13 @@ void AndroidApplication::initActivity(JNIEnv *env, jobject baseActivity, jclass { "inputDeviceEnumerated", "(JILandroid/view/InputDevice;Ljava/lang/String;IIIIZ)V", (void*) - +[](JNIEnv* env, jobject, jlong nUserData, jint devID, jobject jDev, jstring jName, jint src, + +[](JNIEnv* env, jobject, jlong nUserData, jint devID, [[maybe_unused]] jobject jDev, jstring jName, jint src, jint kbType, jint jsAxisFlags, jint vendorProductId, jboolean isPowerButton) { ApplicationContext ctx{reinterpret_cast(nUserData)}; auto &app = ctx.application(); const char *name = env->GetStringUTFChars(jName, nullptr); - auto sysDev = std::make_unique(std::in_place_type, env, jDev, devID, src, + auto sysDev = std::make_unique(std::in_place_type, devID, src, name, kbType, std::bit_cast(jsAxisFlags), (uint32_t)vendorProductId, (bool)isPowerButton); env->ReleaseStringUTFChars(jName, name); auto devPtr = app.updateAndroidInputDevice(ctx, std::move(sysDev), false); @@ -425,7 +437,7 @@ void AndroidApplication::initActivity(JNIEnv *env, jobject baseActivity, jclass { "uriFileListed", "(JLjava/lang/String;Ljava/lang/String;Z)Z", (void*) - +[](JNIEnv* env, jobject thiz, jlong userData, jstring jUri, jstring name, jboolean isDir) + +[](JNIEnv* env, jobject, jlong userData, jstring jUri, jstring name, jboolean isDir) { auto &del = *((DirectoryEntryDelegate*)userData); auto type = isDir ? FS::file_type::directory : FS::file_type::regular; @@ -470,7 +482,7 @@ void AndroidApplication::initActivity(JNIEnv *env, jobject baseActivity, jclass JNIEnv* AndroidApplication::thisThreadJniEnv() const { - auto env = (JNIEnv*)pthread_getspecific(jEnvKey); + auto env = (JNIEnv*)pthread_getspecific(jEnvPThreadKey); if(!env) [[unlikely]] { if(Config::DEBUG_BUILD) @@ -483,7 +495,7 @@ JNIEnv* AndroidApplication::thisThreadJniEnv() const log.error("error attaching JNI thread"); return nullptr; } - pthread_setspecific(jEnvKey, env); + pthread_setspecific(jEnvPThreadKey, env); } return env; } @@ -509,14 +521,7 @@ void AndroidApplication::endIdleByUserActivity(ApplicationContext ctx) // quickly toggle KEEP_SCREEN_ON flag to brighten screen, // waiting about 20ms before toggling it back off triggers the screen to brighten if it was already dim jSetWinFlags(ctx.mainThreadJniEnv(), ctx.baseActivityObject(), AWINDOW_FLAG_KEEP_SCREEN_ON, AWINDOW_FLAG_KEEP_SCREEN_ON); - userActivityCallback.runIn(Milliseconds(20), {}, - [this, ctx]() - { - if(!keepScreenOn) - { - jSetWinFlags(ctx.mainThreadJniEnv(), ctx.baseActivityObject(), 0, AWINDOW_FLAG_KEEP_SCREEN_ON); - } - }); + userActivityCallback.runIn(Milliseconds(20)); } } @@ -583,7 +588,7 @@ void AndroidApplication::onWindowFocusChanged(ApplicationContext ctx, int focuse deinitKeyRepeatTimer(); } -void AndroidApplication::onInputQueueCreated(ApplicationContext ctx, AInputQueue *queue) +void AndroidApplication::onInputQueueCreated(ApplicationContext, AInputQueue* queue) { assert(!inputQueue); inputQueue = queue; @@ -676,7 +681,7 @@ void AndroidApplication::handleDocumentIntentResult(ApplicationContext ctx, cons { // wait until after app resumes before handling result addOnResume( - [uriCopy = strdup(uri), nameCopy = strdup(name)](ApplicationContext ctx, bool focused) + [uriCopy = strdup(uri), nameCopy = strdup(name)](ApplicationContext ctx, [[maybe_unused]] bool focused) { ctx.application().onEvent(ctx, DocumentPickerEvent{uriCopy, nameCopy}); ::free(nameCopy); @@ -840,7 +845,7 @@ static void setNativeActivityCallbacks(ANativeActivity *nActivity) } -CLINK void LVISIBLE ANativeActivity_onCreate(ANativeActivity *nActivity, void* savedState, size_t savedStateSize) +CLINK void LVISIBLE ANativeActivity_onCreate(ANativeActivity* nActivity, [[maybe_unused]] void* savedState, [[maybe_unused]] size_t savedStateSize) { using namespace IG; if(Config::DEBUG_BUILD) diff --git a/imagine/src/base/android/ApplicationContext.cc b/imagine/src/base/android/ApplicationContext.cc index c0f85067d..37e4c5873 100644 --- a/imagine/src/base/android/ApplicationContext.cc +++ b/imagine/src/base/android/ApplicationContext.cc @@ -13,11 +13,11 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "AppCtx" #include #include #include #include +#include #include #include "android.hh" #include @@ -25,6 +25,7 @@ namespace IG { +constexpr SystemLogger log{"AppCtx"}; static NoopThread noopThread; FS::PathString ApplicationContext::assetPath(const char *) const { return {}; } @@ -33,7 +34,7 @@ FS::PathString ApplicationContext::supportPath(const char *) const { if(androidSDK() < 11) // bug in pre-3.0 Android causes paths in ANativeActivity to be null { - //logMsg("ignoring paths from ANativeActivity due to Android 2.3 bug"); + //log.info("ignoring paths from ANativeActivity due to Android 2.3 bug"); auto env = thisThreadJniEnv(); auto baseActivity = baseActivityObject(); JNI::InstMethod filesDir{env, baseActivity, "filesDir", "()Ljava/lang/String;"}; @@ -101,7 +102,7 @@ std::vector ApplicationContext::rootFileLocations() const else { std::vector rootLocation{sharedStoragePathLocation()}; - logMsg("enumerating storage volumes"); + log.info("enumerating storage volumes"); auto env = thisThreadJniEnv(); auto baseActivity = baseActivityObject(); JNI::InstMethod jNewStorageManagerHelper{env, baseActivity, "storageManagerHelper", "()Lcom/imagine/StorageManagerHelper;"}; @@ -112,12 +113,12 @@ std::vector ApplicationContext::rootFileLocations() const { "volumeEnumerated", "(JLjava/lang/String;Ljava/lang/String;)V", (void*)(void (*)(JNIEnv*, jobject, jlong, jstring, jstring)) - ([](JNIEnv* env, jobject thiz, jlong userData, jstring jName, jstring jPath) + ([](JNIEnv* env, jobject, jlong userData, jstring jName, jstring jPath) { auto rootLocation = (std::vector*)userData; FS::PathString path{JNI::StringChars(env, jPath)}; FS::FileString name{JNI::StringChars(env, jName)}; - logMsg("volume:%s with path:%s", name.data(), path.data()); + log.info("volume:{} with path:{}", name, path); rootLocation->emplace_back(path, name); }) }, @@ -238,7 +239,7 @@ static jstring permissionToJString(JNIEnv *env, Permission p) } } -bool ApplicationContext::usesPermission(Permission p) const +bool ApplicationContext::usesPermission(Permission) const { if(androidSDK() < 23 || androidSDK() >= 30) return false; @@ -335,7 +336,7 @@ void ApplicationContext::setSustainedPerformanceMode(bool on) { if(!hasSustainedPerformanceMode()) return; - logMsg("set sustained performance mode:%s", on ? "on" : "off"); + log.info("set sustained performance mode:{}", on); auto env = mainThreadJniEnv(); auto baseActivity = baseActivityObject(); JNI::InstMethod jSetSustainedPerformanceMode{env, baseActivity, "setSustainedPerformanceMode", "(Z)V"}; @@ -396,7 +397,7 @@ void ApplicationContext::exitWithMessage(int exitVal, const char *msg) auto baseActivity = baseActivityObject(); JNI::InstMethod jMakeErrorPopup{env, baseActivity, "makeErrorPopup", "(Ljava/lang/String;)V"}; jMakeErrorPopup(env, baseActivity, env->NewStringUTF(msg)); - auto exitTimer = new Timer{"exitTimer", [=]() { ::exit(exitVal); }}; + auto exitTimer = new Timer{{.debugLabel = "exitTimer"}, [=]{ ::exit(exitVal); }}; exitTimer->runIn(Seconds{3}); } @@ -417,7 +418,7 @@ void ApplicationContext::addNotification(CStringView onShow, CStringView title, void ApplicationContext::addLauncherIcon(CStringView name, CStringView path) { - logMsg("adding launcher icon:%s, for location:%s", name.data(), path.data()); + log.info("adding launcher icon:{}, for location:{}", name, path); auto env = mainThreadJniEnv(); auto baseActivity = baseActivityObject(); JNI::InstMethod jAddViewShortcut{env, baseActivity, "addViewShortcut", "(Ljava/lang/String;Ljava/lang/String;)V"}; @@ -463,15 +464,15 @@ void NoopThread::start() { // keep cpu governor busy by running a low priority thread executing no-op instructions setpriority(PRIO_PROCESS, 0, 19); - logMsg("started no-op thread"); + log.info("started no-op thread"); while(isRunning.load(std::memory_order_relaxed)) { - for(auto i : iotaCount(16)) + for([[maybe_unused]] auto i : iotaCount(16)) { asm("nop"); } } - logMsg("ended no-op thread"); + log.info("ended no-op thread"); }); } diff --git a/imagine/src/base/android/FrameTimer.cc b/imagine/src/base/android/FrameTimer.cc index f7b89404b..a511136d7 100644 --- a/imagine/src/base/android/FrameTimer.cc +++ b/imagine/src/base/android/FrameTimer.cc @@ -13,7 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "FrameTimer" #include #include #include @@ -31,6 +30,8 @@ namespace IG { +constexpr SystemLogger log{"Choreographer"}; + void AndroidApplication::emplaceFrameTimer(FrameTimer &t, Screen &screen, bool useVariableTime) { if(useVariableTime) @@ -91,32 +92,36 @@ static void updatePostedScreens(auto &choreographer, SteadyClockTimePoint timest } else { - //logMsg("stopping screen updates"); + //log.info("stopping screen updates"); } } JavaChoreographer::JavaChoreographer(AndroidApplication &app, JNIEnv *env, jobject baseActivity, jclass baseActivityClass): appPtr{&app} { + jniEnv = env; JNI::InstMethod jChoreographerHelper{env, baseActivityClass, "choreographerHelper", "(J)Lcom/imagine/ChoreographerHelper;"}; frameHelper = {env, jChoreographerHelper(env, baseActivity, (jlong)this)}; auto choreographerHelperCls = env->GetObjectClass(frameHelper); jPostFrame = {env, choreographerHelperCls, "postFrame", "()V"}; + jSetInstance = {env, choreographerHelperCls, "setInstance", "()V"}; JNINativeMethod method[] { { "onFrame", "(JJ)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong userData, jlong frameTimeNanos) + +[](JNIEnv*, jobject, jlong userData, jlong frameTimeNanos) { auto &inst = *((JavaChoreographer*)userData); + if(!inst.requested) [[unlikely]] + return; inst.requested = false; updatePostedScreens(inst, SteadyClockTimePoint{Nanoseconds{frameTimeNanos}}, *inst.appPtr); } } }; env->RegisterNatives(choreographerHelperCls, method, std::size(method)); - logMsg("using Java Choreographer"); + log.info("using Java Choreographer"); } void JavaChoreographer::scheduleVSync() @@ -125,20 +130,26 @@ void JavaChoreographer::scheduleVSync() if(requested) return; requested = true; - jPostFrame(frameHelper.jniEnv(), frameHelper); + jPostFrame(jniEnv, frameHelper); +} + +void JavaChoreographer::setEventsOnThisThread(ApplicationContext ctx) +{ + jniEnv = ctx.thisThreadJniEnv(); + jSetInstance(jniEnv, frameHelper); + requested = false; } NativeChoreographer::NativeChoreographer(AndroidApplication &app): appPtr{&app} { - AChoreographer* (*getInstance)(){}; loadSymbol(getInstance, {}, "AChoreographer_getInstance"); assert(getInstance); loadSymbol(postFrameCallback, {}, "AChoreographer_postFrameCallback"); assert(postFrameCallback); choreographer = getInstance(); assert(choreographer); - logMsg("using native Choreographer"); + log.info("using native Choreographer"); } void NativeChoreographer::scheduleVSync() @@ -146,13 +157,20 @@ void NativeChoreographer::scheduleVSync() if(requested) return; requested = true; - postFrameCallback(choreographer, - [](long frameTimeNanos, void* userData) - { - auto &inst = *((NativeChoreographer*)userData); - inst.requested = false; - updatePostedScreens(inst, SteadyClockTimePoint{Nanoseconds{frameTimeNanos}}, *inst.appPtr); - }, this); + postFrameCallback(choreographer, [](long frameTimeNanos, void* userData) + { + auto &inst = *((NativeChoreographer*)userData); + if(!inst.requested) [[unlikely]] + return; + inst.requested = false; + updatePostedScreens(inst, SteadyClockTimePoint{Nanoseconds{frameTimeNanos}}, *inst.appPtr); + }, this); +} + +void NativeChoreographer::setEventsOnThisThread(ApplicationContext) +{ + choreographer = getInstance(); + requested = false; } } diff --git a/imagine/src/base/android/PerformanceHintManager.cc b/imagine/src/base/android/PerformanceHintManager.cc index 55beeac6b..1243c3a74 100644 --- a/imagine/src/base/android/PerformanceHintManager.cc +++ b/imagine/src/base/android/PerformanceHintManager.cc @@ -25,7 +25,7 @@ namespace IG static APerformanceHintSession* (*APerformanceHint_createSession)(APerformanceHintManager* manager, const int32_t* threadIds, size_t size, int64_t initialTargetWorkDurationNanos); -static int64_t (*APerformanceHint_getPreferredUpdateRateNanos)(APerformanceHintManager* manager); // unused +//static int64_t (*APerformanceHint_getPreferredUpdateRateNanos)(APerformanceHintManager* manager); // unused static int (*APerformanceHint_updateTargetWorkDuration)(APerformanceHintSession* session, int64_t targetDurationNanos); static int (*APerformanceHint_reportActualWorkDuration)(APerformanceHintSession* session, int64_t actualDurationNanos); static void (*APerformanceHint_closeSession)(APerformanceHintSession* session); diff --git a/imagine/src/base/android/Sensor.cc b/imagine/src/base/android/Sensor.cc index 4c4f9de9e..977131b99 100644 --- a/imagine/src/base/android/Sensor.cc +++ b/imagine/src/base/android/Sensor.cc @@ -27,7 +27,7 @@ static_assert(to_underlying(SensorType::Accelerometer) == 1); static_assert(to_underlying(SensorType::Gyroscope) == 4); static_assert(to_underlying(SensorType::Light) == 5); -SensorListener::SensorListener(ApplicationContext ctx, SensorType type, SensorChangedDelegate del): +SensorListener::SensorListener(ApplicationContext, SensorType type, SensorChangedDelegate del): AndroidSensorListener{ASensorManager_getInstance(), type, del} {} AndroidSensorListener::AndroidSensorListener(ASensorManager *manager, SensorType type, SensorChangedDelegate changedDel): @@ -38,7 +38,7 @@ AndroidSensorListener::AndroidSensorListener(ASensorManager *manager, SensorType return; ctrl->queue.reset(ASensorManager_createEventQueue(manager, ALooper_forThread(), ALOOPER_POLL_CALLBACK, - [](int fd, int ev, void *data) -> int + []([[maybe_unused]] int fd, [[maybe_unused]] int ev, void *data) -> int { auto &[queue, del] = *((ControlBlock*)data); ssize_t eventsRead{}; diff --git a/imagine/src/base/android/TextField.cc b/imagine/src/base/android/TextField.cc index 6eb1ca400..ada542154 100644 --- a/imagine/src/base/android/TextField.cc +++ b/imagine/src/base/android/TextField.cc @@ -38,7 +38,6 @@ AndroidTextField::AndroidTextField(ApplicationContext ctx, TextFieldDelegate del textDelegate{del} { auto env = ctx.mainThreadJniEnv(); - auto &app = ctx.application(); auto baseActivity = ctx.baseActivityObject(); setupBaseActivityJni(env, baseActivity); logMsg("starting system text input"); @@ -64,7 +63,7 @@ void AndroidTextField::setupTextEntryJni(JNIEnv* env, jobject textEntry) { { "textInputEnded", "(JLjava/lang/String;ZZ)V", - (void*)+[](JNIEnv* env, jobject thiz, jlong nUserData, jstring jStr, jboolean processText, jboolean isDoingDismiss) + (void*)+[](JNIEnv* env, jobject, jlong nUserData, jstring jStr, jboolean processText, [[maybe_unused]] jboolean isDoingDismiss) { if(!processText) { diff --git a/imagine/src/base/android/imagine-v9/build.gradle b/imagine/src/base/android/imagine-v9/build.gradle index ad1704e62..f2d39d9f1 100644 --- a/imagine/src/base/android/imagine-v9/build.gradle +++ b/imagine/src/base/android/imagine-v9/build.gradle @@ -4,7 +4,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:8.3.0' + classpath 'com.android.tools.build:gradle:8.5.0' } } diff --git a/imagine/src/base/android/imagine-v9/src/main/java/com/imagine/ChoreographerHelper.java b/imagine/src/base/android/imagine-v9/src/main/java/com/imagine/ChoreographerHelper.java index a7949edd0..f325a241f 100644 --- a/imagine/src/base/android/imagine-v9/src/main/java/com/imagine/ChoreographerHelper.java +++ b/imagine/src/base/android/imagine-v9/src/main/java/com/imagine/ChoreographerHelper.java @@ -16,6 +16,8 @@ package com.imagine; import android.view.Choreographer; +import android.os.Looper; +import android.util.Log; final class ChoreographerHelper { @@ -36,7 +38,7 @@ final class ChoreographerHelper private static final String logTag = "ChoreographerHelper"; private static native void onFrame(long nativeUserData, long frameTimeNanos); - private final Choreographer choreographer = Choreographer.getInstance(); + private Choreographer choreographer = Choreographer.getInstance(); private final Callback callback; ChoreographerHelper(long nativeUserData) @@ -48,4 +50,11 @@ final class ChoreographerHelper { choreographer.postFrameCallback(callback); } + + void setInstance() + { + if(Looper.myLooper() == null) + Looper.prepare(); + choreographer = Choreographer.getInstance(); + } } diff --git a/imagine/src/base/android/input.cc b/imagine/src/base/android/input.cc index b0e20def1..e2174d70e 100644 --- a/imagine/src/base/android/input.cc +++ b/imagine/src/base/android/input.cc @@ -60,7 +60,7 @@ static auto makeTimeFromKeyEvent(AInputEvent *event) } static std::pair mapKeycodesForSpecialDevices(const Input::Device &dev, - int32_t keyCode, int32_t metaState, Input::Source src, AInputEvent *event) + int32_t keyCode, int32_t metaState, Input::Source src) { using namespace IG::Input; switch(dev.subtype()) @@ -93,7 +93,7 @@ static std::pair mapKeycodesForSpecialDevices(const Inpu return {keyCode, src}; } -static const char *keyEventActionStr(uint32_t action) +constexpr const char *keyEventActionStr(uint32_t action) { switch(action) { @@ -244,7 +244,6 @@ bool AndroidApplication::processInputEvent(AInputEvent* event, Input::Device *de float iX = x * 1000.f, iY = y * 1000.f; auto pos = win.transformInputPos({iX, iY}); //logMsg("trackball ev %s %f %f", androidEventEnumToStr(action), x, y); - auto src = Source::KEYBOARD; if(actionCode == AMOTION_EVENT_ACTION_MOVE) win.dispatchInputEvent(MotionEvent{Map::REL_POINTER, 0, 0, Action::MOVED_RELATIVE, pos.x, pos.y, 0, Source::NAVIGATION, time, nullptr}); else @@ -336,7 +335,7 @@ bool AndroidApplication::processInputEvent(AInputEvent* event, Input::Device *de // repeatCount, keyEventActionStr(AKeyEvent_getAction(event)), sourceStr(eventSource)); } auto metaState = AKeyEvent_getMetaState(event); - auto [mappedKeyCode, mappedSource] = mapKeycodesForSpecialDevices(*devPtr, keyCode, metaState, eventSource, event); + auto [mappedKeyCode, mappedSource] = mapKeycodesForSpecialDevices(*devPtr, keyCode, metaState, eventSource); keyCode = mappedKeyCode; eventSource = mappedSource; if(!keyCode) [[unlikely]] // ignore "unknown" key codes diff --git a/imagine/src/base/android/inputConfig.cc b/imagine/src/base/android/inputConfig.cc index fec3cabc5..287994476 100644 --- a/imagine/src/base/android/inputConfig.cc +++ b/imagine/src/base/android/inputConfig.cc @@ -25,8 +25,8 @@ #include #include -static float (*AMotionEvent_getAxisValueFunc)(const AInputEvent* motion_event, int32_t axis, size_t pointer_index){}; -static float (*AMotionEvent_getButtonStateFunc)(const AInputEvent *motion_event){}; +[[maybe_unused]] static float (*AMotionEvent_getAxisValueFunc)(const AInputEvent* motion_event, int32_t axis, size_t pointer_index){}; +[[maybe_unused]] static float (*AMotionEvent_getButtonStateFunc)(const AInputEvent *motion_event){}; #if ANDROID_MIN_API == 9 CLINK float AMotionEvent_getAxisValue(const AInputEvent* motion_event, int32_t axis, size_t pointer_index) @@ -48,12 +48,10 @@ namespace IG::Input constexpr SystemLogger log{"InputConfig"}; -static constexpr uint32_t maxJoystickAxisPairs = 4; // 2 sticks + POV hat + L/R Triggers - // Note: values must remain in sync with Java code -static constexpr int DEVICE_ADDED = 0; -static constexpr int DEVICE_CHANGED = 1; -static constexpr int DEVICE_REMOVED = 2; +constexpr inline int DEVICE_ADDED = 0; +constexpr inline int DEVICE_CHANGED = 1; +constexpr inline int DEVICE_REMOVED = 2; static std::unique_ptr makeGenericKeyDevice() { @@ -88,9 +86,8 @@ static const char *inputDeviceKeyboardTypeToStr(int type) AndroidInputDevice::AndroidInputDevice(int osId, DeviceTypeFlags typeFlags, std::string name): BaseDevice{osId, Map::SYSTEM, typeFlags, std::move(name)} {} -AndroidInputDevice::AndroidInputDevice(JNIEnv* env, jobject aDev, - int osId, int src, std::string devName, int kbType, AxisFlags jsAxisFlags, - uint32_t vendorProductId, bool isPowerButton): +AndroidInputDevice::AndroidInputDevice(int osId, int src, std::string devName, + int kbType, AxisFlags jsAxisFlags, uint32_t vendorProductId, bool isPowerButton): BaseDevice{osId, Map::SYSTEM, {.miscKeys = true}, std::move(devName)} { typeFlags_.virtualInput = osId == -1; @@ -161,7 +158,7 @@ AndroidInputDevice::AndroidInputDevice(JNIEnv* env, jobject aDev, continue; } log.info("joystick axis:{}", (int)axisId); - axis.emplace_back(Map::SYSTEM, axisId); + axis.emplace_back(axisId); assert(!axis.isFull()); } // check trigger axes @@ -177,7 +174,7 @@ AndroidInputDevice::AndroidInputDevice(JNIEnv* env, jobject aDev, continue; } log.info("trigger axis:{}", (int)axisId); - axis.emplace_back(Map::SYSTEM, axisId); + axis.emplace_back(axisId); assert(!axis.isFull()); addedTriggers |= triggerAxisBits; if(addedTriggers == AxisFlags{.lTrigger = true, .rTrigger = true}) @@ -311,7 +308,7 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject { "deviceChanged", "(JIILandroid/view/InputDevice;Ljava/lang/String;IIII)V", (void*) - +[](JNIEnv* env, jobject thiz, jlong nUserData, jint change, jint devID, jobject jDev, + +[](JNIEnv* env, jobject, jlong nUserData, jint change, jint devID, [[maybe_unused]] jobject jDev, jstring jName, jint src, jint kbType, jint jsAxisFlags, jint vendorProductId) { ApplicationContext ctx{reinterpret_cast(nUserData)}; @@ -323,7 +320,7 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject else // add or update existing { const char *name = env->GetStringUTFChars(jName, nullptr); - auto sysDev = std::make_unique(std::in_place_type, env, jDev, devID, + auto sysDev = std::make_unique(std::in_place_type, devID, src, name, kbType, std::bit_cast(jsAxisFlags), (uint32_t)vendorProductId, false); env->ReleaseStringUTFChars(jName, name); app.updateAndroidInputDevice(ctx, std::move(sysDev), true); @@ -340,7 +337,7 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject impl.jRegister(env, impl.listenerHelper); return true; }, INPUT_DEVICE_ON_RESUME_PRIORITY); - addOnExit([this, env](ApplicationContext, bool backgrounded) + addOnExit([this, env](ApplicationContext, [[maybe_unused]] bool backgrounded) { log.info("unregistering input device listener"); auto &impl = *std::get_if(&inputDeviceChangeImpl); @@ -351,7 +348,8 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject else { log.info("setting up input notifications with inotify"); - auto &impl = inputDeviceChangeImpl.emplace(); + auto &impl = inputDeviceChangeImpl.emplace(Timer{ + {.debugLabel = "inputRescanCallback"}, [ctx]{ ctx.enumInputDevices(); }}); impl.fd = inotify_init(); if(impl.fd == -1) { @@ -365,10 +363,10 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject log.info("got inotify event"); auto &app = *((AndroidApplication*)data); auto &impl = *std::get_if(&app.inputDeviceChangeImpl); - if(events == POLLEV_IN) + if(events == ALOOPER_EVENT_INPUT) { char buffer[2048]; - auto size = read(fd, buffer, sizeof(buffer)); + [[maybe_unused]] auto size = read(fd, buffer, sizeof(buffer)); if(app.isRunning()) { impl.rescanTimer.runIn(IG::Milliseconds(250)); @@ -383,7 +381,6 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject addOnResume([this, env](ApplicationContext ctx, bool) { auto &impl = *std::get_if(&inputDeviceChangeImpl); - impl.rescanTimer = {"inputRescanCallback", [ctx]() { ctx.enumInputDevices(); }}; enumInputDevices(ctx, env, ctx.baseActivityObject(), true); if(impl.fd != -1 && impl.watch == -1) { @@ -396,7 +393,7 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject } return true; }, INPUT_DEVICE_ON_RESUME_PRIORITY); - addOnExit([this, env](ApplicationContext, bool backgrounded) + addOnExit([this](ApplicationContext, [[maybe_unused]] bool backgrounded) { auto &impl = *std::get_if(&inputDeviceChangeImpl); if(impl.watch != -1) @@ -404,7 +401,7 @@ void AndroidApplication::initInput(ApplicationContext ctx, JNIEnv *env, jobject log.info("unregistering inotify input device listener"); inotify_rm_watch(impl.fd, impl.watch); impl.watch = -1; - impl.rescanTimer = {}; + impl.rescanTimer.cancel(); } return true; }, INPUT_DEVICE_ON_EXIT_PRIORITY); diff --git a/imagine/src/base/android/moga.cc b/imagine/src/base/android/moga.cc index 6fe2ee5d4..24f5f5e24 100644 --- a/imagine/src/base/android/moga.cc +++ b/imagine/src/base/android/moga.cc @@ -84,7 +84,7 @@ std::unique_ptr MogaManager::makeMOGADevice(const char *name) static constexpr AxisId stickAxes[] { AxisId::X, AxisId::Y, AxisId::Z, AxisId::RZ }; for(auto axisId : stickAxes) { - axes.emplace_back(Map::SYSTEM, axisId); + axes.emplace_back(axisId); } } // set trigger axes @@ -92,7 +92,7 @@ std::unique_ptr MogaManager::makeMOGADevice(const char *name) static constexpr AxisId triggerAxes[] { AxisId::LTRIGGER, AxisId::RTRIGGER }; for(auto axisId : triggerAxes) { - axes.emplace_back(Map::SYSTEM, axisId); + axes.emplace_back(axisId); } } return devPtr; @@ -132,7 +132,7 @@ void MogaManager::initMOGAJNIAndDevice(JNIEnv *env, jobject mogaHelper) { "keyEvent", "(JIIJ)V", (void*)(void (*)(JNIEnv*, jobject, jlong, jint, jint, jlong)) - ([](JNIEnv* env, jobject thiz, jlong mogaManagerPtr, jint action, jint keyCode, jlong timestamp) + ([](JNIEnv*, jobject, jlong mogaManagerPtr, jint action, jint keyCode, jlong timestamp) { auto &mogaManager = *((MogaManager*)mogaManagerPtr); auto &mogaDev = *mogaManager.mogaDev; @@ -149,7 +149,7 @@ void MogaManager::initMOGAJNIAndDevice(JNIEnv *env, jobject mogaHelper) { "motionEvent", "(JFFFFFFJ)V", (void*)(void (*)(JNIEnv*, jobject, jlong, jfloat, jfloat, jfloat, jfloat, jfloat, jfloat, jlong)) - ([](JNIEnv* env, jobject thiz, jlong mogaManagerPtr, jfloat x, jfloat y, jfloat z, jfloat rz, jfloat lTrigger, jfloat rTrigger, jlong timestamp) + ([](JNIEnv*, jobject, jlong mogaManagerPtr, jfloat x, jfloat y, jfloat z, jfloat rz, jfloat lTrigger, jfloat rTrigger, jlong timestamp) { auto &mogaManager = *((MogaManager*)mogaManagerPtr); auto &mogaDev = *mogaManager.mogaDev; @@ -170,7 +170,7 @@ void MogaManager::initMOGAJNIAndDevice(JNIEnv *env, jobject mogaHelper) { "stateEvent", "(JII)V", (void*)(void (*)(JNIEnv*, jobject, jlong, jint, jint)) - ([](JNIEnv* env, jobject thiz, jlong mogaManagerPtr, jint state, jint action) + ([](JNIEnv* env, jobject, jlong mogaManagerPtr, jint state, jint action) { logMsg("MOGA state event: %d %d", state, action); if(state == STATE_CONNECTION) diff --git a/imagine/src/base/android/privateApi/GraphicBuffer.cc b/imagine/src/base/android/privateApi/GraphicBuffer.cc index 4561cf0b9..c6d13a72f 100644 --- a/imagine/src/base/android/privateApi/GraphicBuffer.cc +++ b/imagine/src/base/android/privateApi/GraphicBuffer.cc @@ -64,12 +64,12 @@ GraphicBuffer::GraphicBuffer() { initAllocDev(); common.incRef = - [](struct android_native_base_t *ptr) + [](struct android_native_base_t*) { //logMsg("called incRef:%p", ptr); }; common.decRef = - [](struct android_native_base_t *ptr) + [](struct android_native_base_t*) { //logMsg("called decRef:%p", ptr); }; diff --git a/imagine/src/base/android/proguard/imagine.cfg b/imagine/src/base/android/proguard/imagine.cfg index bb26b9960..10129cb23 100644 --- a/imagine/src/base/android/proguard/imagine.cfg +++ b/imagine/src/base/android/proguard/imagine.cfg @@ -71,6 +71,7 @@ -keepclassmembers class com.imagine.ChoreographerHelper { void postFrame(); + void setInstance(); } -keepclassmembers class com.imagine.TextEntry diff --git a/imagine/src/base/common/Application.cc b/imagine/src/base/common/Application.cc index de4f10b55..94593d963 100644 --- a/imagine/src/base/common/Application.cc +++ b/imagine/src/base/common/Application.cc @@ -226,13 +226,13 @@ void BaseApplication::dispatchOnExit(ApplicationContext ctx, bool backgrounded) } } -[[gnu::weak]] void ApplicationContext::setIdleDisplayPowerSave(bool on) {} +[[gnu::weak]] void ApplicationContext::setIdleDisplayPowerSave(bool) {} [[gnu::weak]] void ApplicationContext::endIdleByUserActivity() {} -[[gnu::weak]] bool ApplicationContext::registerInstance(ApplicationInitParams, const char *) { return false; } +[[gnu::weak]] bool ApplicationContext::registerInstance(ApplicationInitParams, const char*) { return false; } -[[gnu::weak]] void ApplicationContext::setAcceptIPC(bool on, const char *) {} +[[gnu::weak]] void ApplicationContext::setAcceptIPC(bool, const char*) {} void Application::runOnMainThread(MainThreadMessageDelegate del) { diff --git a/imagine/src/base/common/ApplicationContext.cc b/imagine/src/base/common/ApplicationContext.cc index 8b7f5ed21..d87aece10 100644 --- a/imagine/src/base/common/ApplicationContext.cc +++ b/imagine/src/base/common/ApplicationContext.cc @@ -227,7 +227,7 @@ FS::RootPathInfo ApplicationContext::rootPathInfo(std::string_view path) const return nearestPtr->root.info; } -AssetIO ApplicationContext::openAsset(CStringView name, OpenFlags openFlags, const char *appName) const +AssetIO ApplicationContext::openAsset(CStringView name, OpenFlags openFlags, [[maybe_unused]] const char* appName) const { #ifdef __ANDROID__ return {*this, name, openFlags}; @@ -236,7 +236,7 @@ AssetIO ApplicationContext::openAsset(CStringView name, OpenFlags openFlags, con #endif } -FS::AssetDirectoryIterator ApplicationContext::openAssetDirectory(CStringView path, const char *appName) +FS::AssetDirectoryIterator ApplicationContext::openAssetDirectory(CStringView path, [[maybe_unused]] const char* appName) { #ifdef __ANDROID__ return {aAssetManager(), path}; @@ -321,12 +321,9 @@ const InputDeviceContainer &ApplicationContext::inputDevices() const return application().inputDevices(); } -Input::Device *ApplicationContext::inputDevice(std::string_view name, int enumId) const +Input::Device* ApplicationContext::inputDevice(std::string_view name, int enumId) const { - auto it = std::ranges::find_if(inputDevices(), [&](auto &devPtr){ return devPtr->name() == name; }); - if(it == inputDevices().end()) - return {}; - return it->get(); + return findPtr(inputDevices(), [&](auto &devPtr){ return devPtr->enumId() == enumId && devPtr->name() == name; }); } void ApplicationContext::setHintKeyRepeat(bool on) @@ -381,13 +378,13 @@ void ApplicationContext::setSwappedConfirmKeys(std::optional opt) [[gnu::weak]] bool ApplicationContext::usesPermission(Permission) const { return false; } -[[gnu::weak]] bool ApplicationContext::permissionIsRestricted(Permission p) const { return false; } +[[gnu::weak]] bool ApplicationContext::permissionIsRestricted(Permission) const { return false; } [[gnu::weak]] bool ApplicationContext::requestPermission(Permission) { return false; } -[[gnu::weak]] void ApplicationContext::addNotification(CStringView onShow, CStringView title, CStringView message) {} +[[gnu::weak]] void ApplicationContext::addNotification(CStringView, CStringView, CStringView) {} -[[gnu::weak]] void ApplicationContext::addLauncherIcon(CStringView name, CStringView path) {} +[[gnu::weak]] void ApplicationContext::addLauncherIcon(CStringView, CStringView) {} [[gnu::weak]] bool VibrationManager::hasVibrator() const { return false; } @@ -404,14 +401,14 @@ void ApplicationContext::setSwappedConfirmKeys(std::optional opt) #endif } -[[gnu::weak]] int ApplicationContext::maxCPUFrequencyKHz(int cpuIdx) const +[[gnu::weak]] int ApplicationContext::maxCPUFrequencyKHz([[maybe_unused]] int cpuIdx) const { #ifdef __linux__ auto maxFreqFile = UniqueFileStream{fopen(std::format("/sys/devices/system/cpu/cpu{}/cpufreq/cpuinfo_max_freq", cpuIdx).c_str(), "r")}; if(!maxFreqFile) return 0; int freq{}; - auto items = fscanf(maxFreqFile.get(), "%d", &freq); + [[maybe_unused]] auto items = fscanf(maxFreqFile.get(), "%d", &freq); return freq; #else return 0; @@ -446,7 +443,7 @@ void ApplicationContext::setSwappedConfirmKeys(std::optional opt) [[gnu::weak]] PerformanceHintManager ApplicationContext::performanceHintManager() { return {}; } -[[gnu::weak]] bool ApplicationContext::packageIsInstalled(CStringView name) const { return false; } +[[gnu::weak]] bool ApplicationContext::packageIsInstalled(CStringView) const { return false; } [[gnu::weak]] int32_t ApplicationContext::androidSDK() const { @@ -454,7 +451,7 @@ void ApplicationContext::setSwappedConfirmKeys(std::optional opt) } [[gnu::weak]] bool ApplicationContext::hasSustainedPerformanceMode() const { return false; } -[[gnu::weak]] void ApplicationContext::setSustainedPerformanceMode(bool on) {} +[[gnu::weak]] void ApplicationContext::setSustainedPerformanceMode(bool) {} [[gnu::weak]] std::string ApplicationContext::formatDateAndTime(WallClockTimePoint time) { diff --git a/imagine/src/base/common/Base.cc b/imagine/src/base/common/Base.cc index 67eddf523..1168e887f 100755 --- a/imagine/src/base/common/Base.cc +++ b/imagine/src/base/common/Base.cc @@ -13,7 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#include #include #include #include @@ -57,17 +56,6 @@ std::string_view asString(Orientations o) return "Unknown"; } -FDEventSource::FDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd, EventLoop loop, PollEventDelegate callback, uint32_t events): - FDEventSource{debugLabel, std::move(fd)} -{ - attach(loop, callback, events); -} - -bool FDEventSource::attach(PollEventDelegate callback, uint32_t events) -{ - return attach({}, callback, events); -} - SharedLibraryRef openSharedLibrary(const char *name, OpenSharedLibraryFlags flags) { int mode = flags.resolveAllSymbols ? RTLD_NOW : RTLD_LAZY; @@ -164,7 +152,7 @@ WRect Viewport::relRectBestFit(WPt pos, float aspectRatio, _2DOrigin posOrigin, } #ifndef __ANDROID__ -static void logBacktrace() +inline void logBacktrace() { void *arr[10]; auto size = backtrace(arr, 10); diff --git a/imagine/src/base/common/PosixPipe.cc b/imagine/src/base/common/PosixPipe.cc index c3177b6f6..4c9501814 100644 --- a/imagine/src/base/common/PosixPipe.cc +++ b/imagine/src/base/common/PosixPipe.cc @@ -42,9 +42,8 @@ static auto makePipe() } Pipe::Pipe(const char *debugLabel, int preferredSize): - debugLabel{debugLabel ? debugLabel : "unnamed"}, io{makePipe()}, - fdSrc{debugLabel, io[0].fd()} + fdSrc{io[0].fd(), {.debugLabel = debugLabel}, {}} { log.info("opened fds:{},{} ({})", io[0].fd(), io[1].fd(), debugLabel); if(preferredSize) @@ -63,14 +62,14 @@ PosixIO &Pipe::sink() return io[1]; } -void Pipe::attach(EventLoop loop, PollEventDelegate callback) +void Pipe::attach(EventLoop loop) { if(io[0].fd() == -1) { log.info("can't add null pipe to event loop"); return; } - fdSrc.attach(loop, callback); + fdSrc.attach(loop); } void Pipe::detach() @@ -85,14 +84,14 @@ bool Pipe::hasData() void Pipe::dispatchSourceEvents() { - fdSrc.dispatchEvents(POLLEV_IN); + fdSrc.dispatchEvents(pollEventInput); } -void Pipe::setPreferredSize(int size) +void Pipe::setPreferredSize([[maybe_unused]] int size) { #ifdef __linux__ fcntl(io[1].fd(), F_SETPIPE_SZ, size); - log.debug("set size:{} ({})", size, debugLabel); + log.debug("set size:{} ({})", size, fdSrc.debugLabel()); #endif } diff --git a/imagine/src/base/common/Screen.cc b/imagine/src/base/common/Screen.cc index d5f0edaf5..49111812b 100644 --- a/imagine/src/base/common/Screen.cc +++ b/imagine/src/base/common/Screen.cc @@ -54,16 +54,12 @@ bool Screen::containsOnFrame(OnFrameDelegate del) const void Screen::runOnFrameDelegates(SteadyClockTimePoint timestamp) { + postFrame(); auto params = makeFrameParams(timestamp); onFrameDelegate.runAll([&](OnFrameDelegate del) - { - return del(params); - }); - if(onFrameDelegate.size()) { - //logDMsg("posting next frame"); - postFrame(); - } + return del(params); + }); } size_t Screen::onFrameDelegates() const diff --git a/imagine/src/base/common/SimpleFrameTimer.cc b/imagine/src/base/common/SimpleFrameTimer.cc index 50a2feef6..f93e72d76 100644 --- a/imagine/src/base/common/SimpleFrameTimer.cc +++ b/imagine/src/base/common/SimpleFrameTimer.cc @@ -26,7 +26,7 @@ constexpr SystemLogger log{"SimpleFrameTimer"}; SimpleFrameTimer::SimpleFrameTimer(Screen &screen, EventLoop loop): timer { - "SimpleFrameTimer", + {.debugLabel = "SimpleFrameTimer", .eventLoop = loop}, [this, &screen]() { if(!requested) @@ -48,8 +48,7 @@ SimpleFrameTimer::SimpleFrameTimer(Screen &screen, EventLoop loop): return true; } }, - interval{fromHz(screen.frameRate())}, - eventLoop{loop} {} + interval{fromHz(screen.frameRate())} {} void SimpleFrameTimer::scheduleVSync() { @@ -64,7 +63,7 @@ void SimpleFrameTimer::scheduleVSync() return; } assert(interval.count()); - timer.runIn(Nanoseconds{1}, interval, eventLoop); + timer.runIn(Nanoseconds{1}, interval); } void SimpleFrameTimer::cancel() @@ -79,8 +78,15 @@ void SimpleFrameTimer::setFrameRate(FrameRate rate) log.info("set frame rate:{:g} (timer interval:{}ns)", rate, interval.count()); if(timer.isArmed()) { - timer.runIn(Nanoseconds{1}, interval, eventLoop); + timer.runIn(Nanoseconds{1}, interval); } } +void SimpleFrameTimer::setEventsOnThisThread(ApplicationContext) +{ + timer.setEventLoop({}); +} + +void NullFrameTimer::setEventsOnThisThread(ApplicationContext) {} + } diff --git a/imagine/src/base/common/Window.cc b/imagine/src/base/common/Window.cc index 546b20aa4..d8d38d94a 100644 --- a/imagine/src/base/common/Window.cc +++ b/imagine/src/base/common/Window.cc @@ -44,27 +44,24 @@ BaseWindow::BaseWindow(ApplicationContext ctx, WindowConfig config): { auto &win = *static_cast(this); win.setDrawEventPriority(savedDrawEventPriority); - attachDrawEvent(); + drawEvent.attach(); return false; }, WINDOW_ON_RESUME_PRIORITY ); } return true; - }, ctx, WINDOW_ON_EXIT_PRIORITY} -{ - attachDrawEvent(); -} - -void BaseWindow::attachDrawEvent() -{ - drawEvent.attach( - [&win = *static_cast(this)]() + }, ctx, WINDOW_ON_EXIT_PRIORITY + }, + drawEvent + { + {.debugLabel = "Window::drawEvent", .eventLoop = EventLoop::forThread()}, + [&win = *static_cast(this)] { //log.debug("running window events"); win.dispatchOnFrame(); win.dispatchOnDraw(); - }); -} + } + } {} FrameTimeSource Window::evalFrameTimeSource(FrameTimeSource src) const { @@ -206,12 +203,25 @@ void Window::postFrameReadyToMainThread() postFrameReady(); } +void Window::setFrameEventsOnThisThread() +{ + unpostDraw(); + screen()->setFrameEventsOnThisThread(); + drawEvent.attach(); +} + +void Window::removeFrameEvents() +{ + unpostDraw(); + screen()->removeFrameEvents(); + drawEvent.detach(); +} + int8_t Window::setDrawEventPriority(int8_t priority) { if(priority == drawEventPriorityLocked) { setNeedsDraw(false); - drawPhase = DrawPhase::UPDATE; } return std::exchange(drawEventPriority_, priority); } @@ -230,11 +240,11 @@ bool Window::dispatchInputEvent(Input::Event event) { bool handled = onEvent.callCopy(*this, event); return event.visit(overloaded{ - [&](const Input::MotionEvent &e) + [&](const Input::MotionEvent& e) { return handled || (e.isPointer() && contentBounds().overlaps(e.pos())); }, - [&](const Input::KeyEvent &e) { return handled; } + [&](const Input::KeyEvent&) { return handled; } }); } diff --git a/imagine/src/base/common/eventloop/CFEventLoop.cc b/imagine/src/base/common/eventloop/CFEventLoop.cc index afc762305..f3e67c81a 100644 --- a/imagine/src/base/common/eventloop/CFEventLoop.cc +++ b/imagine/src/base/common/eventloop/CFEventLoop.cc @@ -56,10 +56,11 @@ void CFFDEventSourceInfo::detachSource() loop = {}; } -CFFDEventSource::CFFDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd): - debugLabel{debugLabel ? debugLabel : "unnamed"}, - info{std::make_unique()} +CFFDEventSource::CFFDEventSource(MaybeUniqueFileDescriptor fd, FDEventSourceDesc, PollEventDelegate del): + info{fd.get() != -1 ? std::make_unique(del) : std::unique_ptr{}} { + if(fd.get() == -1) + return; CFFileDescriptorContext ctx{.version{}, .info = info.get(), .retain{}, .release{}, .copyDescription{}}; info->fdRef = CFFileDescriptorCreate(kCFAllocatorDefault, fd.release(), fd.ownsFd(), eventCallback, &ctx); @@ -74,7 +75,6 @@ CFFDEventSource &CFFDEventSource::operator=(CFFDEventSource &&o) noexcept { deinit(); info = std::move(o.info); - debugLabel = o.debugLabel; return *this; } @@ -83,19 +83,24 @@ CFFDEventSource::~CFFDEventSource() deinit(); } -bool FDEventSource::attach(EventLoop loop, PollEventDelegate callback, uint32_t events) +bool FDEventSource::attach(EventLoop loop, PollEventFlags events) { - assumeExpr(info); - detach(); - if(Config::DEBUG_BUILD) + if(fd() == -1) [[unlikely]] { - log.info("adding fd:{} to run loop ({})", fd(), debugLabel); + log.error("trying to attach without valid fd"); + return false; } - info->callback = callback; - CFFileDescriptorEnableCallBacks(info->fdRef, events); - info->src = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, info->fdRef, 0); + detach(); if(!loop) loop = EventLoop::forThread(); + if(Config::DEBUG_BUILD) + { + log.info("adding fd:{} ({}) to run loop:{}", fd(), debugLabel(), (void*)loop.nativeObject()); + } + assumeExpr(info); + events &= 0x3; + CFFileDescriptorEnableCallBacks(info->fdRef, events); + info->src = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, info->fdRef, 0); CFRunLoopAddSource(loop.nativeObject(), info->src, kCFRunLoopDefaultMode); info->loop = loop.nativeObject(); return true; @@ -107,53 +112,47 @@ void FDEventSource::detach() return; if(Config::DEBUG_BUILD) { - log.info("removing fd:{} from run loop ({})", fd(), debugLabel); + log.info("removing fd:{} ({}) from run loop:{}", fd(), debugLabel(), (void*)info->loop); } info->detachSource(); } -void FDEventSource::setEvents(uint32_t events) +void FDEventSource::setEvents(PollEventFlags events) { - assumeExpr(info); if(!hasEventLoop()) { log.error("trying to set events while not attached to event loop"); return; } - uint32_t disableEvents = ~events & 0x3; + assumeExpr(info); + events &= 0x3; + auto disableEvents = ~events; if(disableEvents) CFFileDescriptorDisableCallBacks(info->fdRef, disableEvents); if(events) CFFileDescriptorEnableCallBacks(info->fdRef, events); } -void FDEventSource::dispatchEvents(uint32_t events) +void FDEventSource::dispatchEvents(PollEventFlags events) { assumeExpr(info); - eventCallback(info->fdRef, events, info.get()); + eventCallback(info->fdRef, events & 0x3, info.get()); } void FDEventSource::setCallback(PollEventDelegate callback) { assumeExpr(info); - if(!hasEventLoop()) - { - log.error("trying to set callback while not attached to event loop"); - return; - } info->callback = callback; } bool FDEventSource::hasEventLoop() const { - assumeExpr(info); - return info->loop; + return info && info->loop; } int FDEventSource::fd() const { - assumeExpr(info); - return info->fdRef ? CFFileDescriptorGetNativeDescriptor(info->fdRef) : -1; + return info ? CFFileDescriptorGetNativeDescriptor(info->fdRef) : -1; } void CFFDEventSource::deinit() @@ -178,9 +177,12 @@ EventLoop EventLoop::makeForThread() return forThread(); } -void EventLoop::run() +void EventLoop::run(const bool& condition) { - CFRunLoopRun(); + while(condition) + { + CFRunLoopRun(); + } } void EventLoop::stop() diff --git a/imagine/src/base/common/eventloop/FDCustomEvent.cc b/imagine/src/base/common/eventloop/FDCustomEvent.cc index 8e7c1df4f..a6ffa7d09 100644 --- a/imagine/src/base/common/eventloop/FDCustomEvent.cc +++ b/imagine/src/base/common/eventloop/FDCustomEvent.cc @@ -48,7 +48,7 @@ static IG::UniqueFileDescriptor makeEventFD() #endif } -static void notifyEventFD(int fd, const char *debugLabel) +static void notifyEventFD(int fd, [[maybe_unused]] const char *debugLabel) { #ifdef USE_EVENTFD eventfd_t counter = 1; @@ -64,7 +64,7 @@ static void notifyEventFD(int fd, const char *debugLabel) #endif } -static void cancelEventFD(int fd, const char *debugLabel) +static void cancelEventFD(int fd, [[maybe_unused]] const char *debugLabel) { #ifdef USE_EVENTFD eventfd_t counter; @@ -81,21 +81,15 @@ static void cancelEventFD(int fd, const char *debugLabel) #endif } -FDCustomEvent::FDCustomEvent(const char *debugLabel): - debugLabel{debugLabel ? debugLabel : "unnamed"}, - fdSrc{debugLabel, makeEventFD()} +FDCustomEvent::FDCustomEvent(FDEventSourceDesc desc, PollEventDelegate del): + fdSrc{makeEventFD(), {.debugLabel = desc.debugLabel, .eventLoop = desc.eventLoop}, del} { if(fdSrc.fd() == -1) { - log.error("error creating fd ({})", debugLabel); + log.error("error creating fd ({})", desc.debugLabel); } } -void FDCustomEvent::attach(EventLoop loop, PollEventDelegate del) -{ - fdSrc.attach(loop, del); -} - void CustomEvent::detach() { fdSrc.detach(); @@ -103,12 +97,12 @@ void CustomEvent::detach() void CustomEvent::notify() { - notifyEventFD(fdSrc.fd(), debugLabel); + notifyEventFD(fdSrc.fd(), debugLabel()); } void CustomEvent::cancel() { - cancelEventFD(fdSrc.fd(), debugLabel); + cancelEventFD(fdSrc.fd(), debugLabel()); } bool CustomEvent::isAttached() const diff --git a/imagine/src/base/common/eventloop/GlibEventLoop.cc b/imagine/src/base/common/eventloop/GlibEventLoop.cc index 0c305fb30..722dfe9f8 100644 --- a/imagine/src/base/common/eventloop/GlibEventLoop.cc +++ b/imagine/src/base/common/eventloop/GlibEventLoop.cc @@ -27,36 +27,79 @@ namespace IG constexpr SystemLogger log{"EventLoop"}; -void destroyGSource(GSource *src) +void destroyGSource(GSource* src) { log.info("destroying GSource:{}", (void*)src); g_source_destroy(src); g_source_unref(src); } -GlibFDEventSource::GlibFDEventSource(const char *debugLabel, MaybeUniqueFileDescriptor fd): - debugLabel{debugLabel ? debugLabel : "unnamed"}, +GlibFDEventSource::GlibFDEventSource(MaybeUniqueFileDescriptor fd, FDEventSourceDesc, PollEventDelegate del): + source{fd.get() != -1 ? makeSource(del) : UniqueGSource{}}, fd_{std::move(fd)} {} -bool FDEventSource::attach(EventLoop loop, GSource *source, uint32_t events) +bool FDEventSource::attach(EventLoop loop, PollEventFlags events) { - usingGlibSource = false; - if(!loop) - loop = EventLoop::forThread(); - tag = g_source_add_unix_fd(source, fd_, static_cast(events)); - g_source_set_callback(source, nullptr, tag, nullptr); - if(!g_source_attach(source, loop.nativeObject())) + if(fd_.get() == -1) [[unlikely]] { - log.error("error attaching fd:{} ({})", fd_.get(), debugLabel); + log.error("trying to attach without valid fd"); return false; } - fdSource.reset(source); - if(tag) - log.info("added fd:{} source:{} to GMainContext:{} ({})", fd_.get(), (void*)source, (void*)loop.nativeObject(), debugLabel); + detach(); + if(!loop) + loop = EventLoop::forThread(); + tag = g_source_add_unix_fd(source.get(), fd_, static_cast(events)); + g_source_set_callback(source.get(), nullptr, tag, nullptr); + if(!g_source_attach(source.get(), loop.nativeObject())) + { + log.error("error attaching fd:{} ({})", fd_.get(), debugLabel()); + detach(); + return false; + } + log.info("added fd:{} source:{} to GMainContext:{} ({})", fd_.get(), (void*)source.get(), (void*)loop.nativeObject(), debugLabel()); return true; } -bool FDEventSource::attach(EventLoop loop, PollEventDelegate callback_, uint32_t events) +void FDEventSource::detach() +{ + if(!hasEventLoop()) + return; + // Re-create the GSource to detach it + source = makeSource(getDelegate(source.get())); + tag = {}; +} + +void FDEventSource::setEvents(PollEventFlags events) +{ + if(!hasEventLoop()) + { + log.error("trying to set events while not attached to event loop"); + return; + } + g_source_modify_unix_fd(source.get(), tag, (GIOCondition)events); +} + +void FDEventSource::dispatchEvents(PollEventFlags events) +{ + getDelegate(source.get())(fd(), events); +} + +void FDEventSource::setCallback(PollEventDelegate callback) +{ + getDelegate(source.get()) = callback; +} + +bool FDEventSource::hasEventLoop() const +{ + return tag; +} + +int FDEventSource::fd() const +{ + return fd_; +} + +UniqueGSource GlibFDEventSource::makeSource(PollEventDelegate callback) { static GSourceFuncs fdSourceFuncs { @@ -76,65 +119,14 @@ bool FDEventSource::attach(EventLoop loop, PollEventDelegate callback_, uint32_t .closure_callback{}, .closure_marshal{}, }; - auto source = (PollEventGSource*)g_source_new(&fdSourceFuncs, sizeof(PollEventGSource)); - source->callback = callback_; - if(!attach(loop, source, events)) - { - g_source_unref(source); - return false; - } - usingGlibSource = true; - return true; + auto source = static_cast(g_source_new(&fdSourceFuncs, sizeof(PollEventGSource))); + source->callback = callback; + return UniqueGSource{source}; } -void FDEventSource::detach() +PollEventDelegate& GlibFDEventSource::getDelegate(GSource* src) { - fdSource = {}; - usingGlibSource = false; -} - -void FDEventSource::setEvents(uint32_t events) -{ - if(!hasEventLoop()) - { - log.error("trying to set events while not attached to event loop"); - return; - } - g_source_modify_unix_fd(fdSource.get(), tag, (GIOCondition)events); -} - -void FDEventSource::dispatchEvents(uint32_t events) -{ - assert(usingGlibSource); - static_cast(fdSource.get())->callback(fd(), events); -} - -void FDEventSource::setCallback(PollEventDelegate callback) -{ - if(!hasEventLoop()) - { - log.error("trying to set callback while not attached to event loop"); - return; - } - assert(usingGlibSource); - static_cast(fdSource.get())->callback = callback; -} - -bool FDEventSource::hasEventLoop() const -{ - if(fdSource) - { - return !g_source_is_destroyed(fdSource.get()); - } - else - { - return false; - } -} - -int FDEventSource::fd() const -{ - return fd_; + return static_cast(src)->callback; } EventLoop EventLoop::forThread() @@ -157,11 +149,11 @@ EventLoop EventLoop::makeForThread() return defaultCtx; } -void EventLoop::run() +void EventLoop::run(const bool& condition) { - if(g_main_context_iteration(mainContext, true)) + while(condition) { - //log.debug("handled events for event loop:{}", (void*)mainContext); + g_main_context_iteration(mainContext, true); } } diff --git a/imagine/src/base/common/timer/CFTimer.cc b/imagine/src/base/common/timer/CFTimer.cc index fa5029025..75d641f22 100644 --- a/imagine/src/base/common/timer/CFTimer.cc +++ b/imagine/src/base/common/timer/CFTimer.cc @@ -23,22 +23,20 @@ namespace IG constexpr SystemLogger log{"Timer"}; -CFTimer::CFTimer(const char *debugLabel, CallbackDelegate c): - debugLabel{debugLabel ? debugLabel : "unnamed"}, - info{std::make_unique(CFTimerInfo{c, {}})} -{} +CFTimer::CFTimer(TimerDesc desc, CallbackDelegate del): + debugLabel_{desc.debugLabel ? desc.debugLabel : "unnamed"}, + info{std::make_unique(del, CFRunLoopRef{}, desc.eventLoop.nativeObject() ?: EventLoop::forThread().nativeObject())} {} -CFTimer::CFTimer(CFTimer &&o) noexcept +CFTimer::CFTimer(CFTimer&& o) noexcept { *this = std::move(o); } -CFTimer &CFTimer::operator=(CFTimer &&o) noexcept +CFTimer& CFTimer::operator=(CFTimer&& o) noexcept { deinit(); timer = std::exchange(o.timer, {}); info = std::move(o.info); - debugLabel = o.debugLabel; return *this; } @@ -79,7 +77,7 @@ void CFTimer::callbackInCFAbsoluteTime(CFAbsoluteTime absTime, CFTimeInterval re } }, &context); createdTimer = true; - log.info("created timer:{} ({})", (void*)timer, debugLabel); + log.info("created timer:{} ({})", (void*)timer, debugLabel()); } else { @@ -89,7 +87,7 @@ void CFTimer::callbackInCFAbsoluteTime(CFAbsoluteTime absTime, CFTimeInterval re { log.info("{}timer:{} ({}) to run in:{}s repeats:{}s", createdTimer ? "created " : "", - (void*)timer, debugLabel, makeRelativeSecs(absTime), (double)repeatInterval); + (void*)timer, debugLabel(), makeRelativeSecs(absTime), (double)repeatInterval); } if(loop != info->loop) { @@ -100,16 +98,14 @@ void CFTimer::callbackInCFAbsoluteTime(CFAbsoluteTime absTime, CFTimeInterval re } } -void Timer::run(Time time, Time repeatTime, bool isAbsTime, EventLoop loop, CallbackDelegate callback) +void Timer::run(Time time, Time repeatTime, bool isAbsTime, CallbackDelegate callback) { if(callback) setCallback(callback); - if(!loop) - loop = EventLoop::forThread(); CFAbsoluteTime absTime = duration_cast(time).count(); if(!isAbsTime) absTime += CFAbsoluteTimeGetCurrent(); - callbackInCFAbsoluteTime(absTime, repeatTime.count(), loop.nativeObject()); + callbackInCFAbsoluteTime(absTime, repeatTime.count(), info->setLoop); } void Timer::cancel() @@ -125,6 +121,12 @@ void Timer::setCallback(CallbackDelegate callback) info->callback = callback; } +void Timer::setEventLoop(EventLoop loop) +{ + cancel(); + info->setLoop = loop.nativeObject() ?: EventLoop::forThread().nativeObject(); +} + void Timer::dispatchEarly() { cancel(); diff --git a/imagine/src/base/common/timer/TimerFD.cc b/imagine/src/base/common/timer/TimerFD.cc index 0b76a5fa6..31f95b440 100644 --- a/imagine/src/base/common/timer/TimerFD.cc +++ b/imagine/src/base/common/timer/TimerFD.cc @@ -66,49 +66,47 @@ namespace IG constexpr SystemLogger log{"Timer"}; -TimerFD::TimerFD(const char *debugLabel, CallbackDelegate c): - debugLabel{debugLabel ? debugLabel : "unnamed"}, - callback_{std::make_unique(c)}, - fdSrc{debugLabel, UniqueFileDescriptor{timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC)}} +static void cancelTimer(int fd) { - if(fdSrc.fd() == -1) - { - log.error("error creating timerfd"); - } + struct itimerspec newTime{}; + timerfd_settime(fd, 0, &newTime, nullptr); } -bool TimerFD::arm(timespec time, timespec repeatInterval, int flags, EventLoop loop) -{ - if(!fdSrc.hasEventLoop()) +TimerFD::TimerFD(TimerDesc desc, CallbackDelegate del): + callback_{std::make_unique(del)}, + fdSrc { - if(!loop) - loop = EventLoop::forThread(); - fdSrc.attach(loop, - [callback = callback_.get()](int fd, int) + UniqueFileDescriptor{timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC)}, + {.debugLabel = desc.debugLabel, .eventLoop = desc.eventLoop}, + [callback = callback_.get()](int fd, int) + { + //log.debug("callback ready for fd:{}", fd); + uint64_t timesFired; + auto ret = ::read(fd, ×Fired, 8); + if(ret == -1) { - //log.debug("callback ready for fd:{}", fd); - uint64_t timesFired; - auto ret = ::read(fd, ×Fired, 8); - if(ret == -1) - { - if(Config::DEBUG_BUILD && errno != EAGAIN) - log.error("error reading timerfd in callback"); - return false; - } - bool keepTimer = (*callback)(); - return keepTimer; - }); - } + if(Config::DEBUG_BUILD && errno != EAGAIN) + log.error("error reading timerfd in callback"); + return true; + } + if(!(*callback)()) + cancelTimer(fd); + return true; + } + } {} + +bool TimerFD::arm(timespec time, timespec repeatInterval, int flags) +{ struct itimerspec newTime{repeatInterval, time}; if(timerfd_settime(fdSrc.fd(), flags, &newTime, nullptr) != 0) { - log.error("error in timerfd_settime:{} ({})", strerror(errno), debugLabel); + log.error("error in timerfd_settime:{} ({})", strerror(errno), fdSrc.debugLabel()); return false; } return true; } -void Timer::run(Time time, Time repeatTime, bool isAbsTime, EventLoop loop, CallbackDelegate callback) +void Timer::run(Time time, Time repeatTime, bool isAbsTime, CallbackDelegate callback) { if(callback) setCallback(callback); @@ -120,9 +118,9 @@ void Timer::run(Time time, Time repeatTime, bool isAbsTime, EventLoop loop, Call { FloatSeconds relTime = isAbsTime ? time - SteadyClock::now().time_since_epoch() : time; log.info("arming fd:{} ({}) to run in:{}s repeats:{}s", - fdSrc.fd(), debugLabel, relTime.count(), IG::FloatSeconds(repeatTime).count()); + fdSrc.fd(), fdSrc.debugLabel(), relTime.count(), FloatSeconds(repeatTime).count()); } - if(!arm({seconds, leftoverNs}, {repeatSeconds, repeatLeftoverNs}, isAbsTime ? TFD_TIMER_ABSTIME : 0, loop)) + if(!arm({seconds, leftoverNs}, {repeatSeconds, repeatLeftoverNs}, isAbsTime ? TFD_TIMER_ABSTIME : 0)) { log.error("failed to setup timer, OS resources may be low or bad parameters present"); } @@ -130,9 +128,7 @@ void Timer::run(Time time, Time repeatTime, bool isAbsTime, EventLoop loop, Call void Timer::cancel() { - fdSrc.detach(); - struct itimerspec newTime{}; - timerfd_settime(fdSrc.fd(), 0, &newTime, nullptr); + cancelTimer(fdSrc.fd()); } void Timer::setCallback(CallbackDelegate callback) @@ -140,6 +136,12 @@ void Timer::setCallback(CallbackDelegate callback) *callback_ = callback; } +void Timer::setEventLoop(EventLoop loop) +{ + cancel(); + fdSrc.attach(loop); +} + void Timer::dispatchEarly() { cancel(); @@ -148,7 +150,9 @@ void Timer::dispatchEarly() bool Timer::isArmed() { - return fdSrc.hasEventLoop(); + struct itimerspec currTime{}; + timerfd_gettime(fdSrc.fd(), &currTime); + return currTime.it_value.tv_nsec || currTime.it_value.tv_sec; } Timer::operator bool() const diff --git a/imagine/src/base/iphone/IOSGLContext.mm b/imagine/src/base/iphone/IOSGLContext.mm index 407fd7696..1f311a512 100644 --- a/imagine/src/base/iphone/IOSGLContext.mm +++ b/imagine/src/base/iphone/IOSGLContext.mm @@ -120,7 +120,7 @@ void GLContext::setSwapInterval(int) {} // GLManager -GLManager::GLManager(NativeDisplayConnection ctx, GL::API api) +GLManager::GLManager(NativeDisplayConnection, GL::API api) { if(!bindAPI(api)) { diff --git a/imagine/src/base/iphone/IOSScreen.mm b/imagine/src/base/iphone/IOSScreen.mm index e6df7b766..790d4f0a6 100644 --- a/imagine/src/base/iphone/IOSScreen.mm +++ b/imagine/src/base/iphone/IOSScreen.mm @@ -98,6 +98,7 @@ IOSScreen::IOSScreen(ApplicationContext, InitParams initParams) displayLink_ = (void*)CFBridgingRetain([screen displayLinkWithTarget:[[DisplayLinkHelper alloc] initWithScreen:(Screen*)this] selector:@selector(onFrame:)]); displayLink().paused = YES; + updateDisplayLinkRunLoop(); // note: the _refreshRate value is actually time per frame in seconds auto frameTime = [uiScreen() _refreshRate]; @@ -113,7 +114,9 @@ IOSScreen::IOSScreen(ApplicationContext, InitParams initParams) IOSScreen::~IOSScreen() { logMsg("deinit screen %p", uiScreen_); + [displayLink() invalidate]; CFRelease(displayLink_); + CFRelease(displayLinkRunLoop_); CFRelease(uiScreen_); } @@ -162,7 +165,7 @@ void Screen::unpostFrameTimer() displayLink().paused = YES; } -void Screen::setFrameRate(FrameRate rate) +void Screen::setFrameRate(FrameRate) { // unsupported } @@ -173,9 +176,32 @@ std::span Screen::supportedFrameRates() const return {&frameRate_, 1}; } -void Screen::setVariableFrameTime(bool useVariableTime) +void Screen::setVariableFrameTime(bool) { // TODO } +void Screen::setFrameEventsOnThisThread() +{ + unpostFrame(); + removeFrameEvents(); + updateDisplayLinkRunLoop(); +} + +void Screen::removeFrameEvents() +{ + unpostFrame(); + if(!displayLinkRunLoop_) + return; + [displayLink() removeFromRunLoop:displayLinkRunLoop() forMode:NSDefaultRunLoopMode]; + CFRelease(std::exchange(displayLinkRunLoop_, nullptr)); +} + +void IOSScreen::updateDisplayLinkRunLoop() +{ + assert(!displayLinkRunLoop_); + displayLinkRunLoop_ = (void*)CFBridgingRetain([NSRunLoop currentRunLoop]); + [displayLink() addToRunLoop:displayLinkRunLoop() forMode:NSDefaultRunLoopMode]; +} + } diff --git a/imagine/src/base/iphone/IOSWindow.mm b/imagine/src/base/iphone/IOSWindow.mm index 091c50deb..433e337d6 100644 --- a/imagine/src/base/iphone/IOSWindow.mm +++ b/imagine/src/base/iphone/IOSWindow.mm @@ -83,7 +83,7 @@ bool Window::setValidOrientations(Orientations o) return true; } -bool Window::requestOrientationChange(Rotation o) +bool Window::requestOrientationChange(Rotation) { // no-op, OS manages orientation changes return false; @@ -229,9 +229,9 @@ Window *windowForUIWindow(ApplicationContext ctx, UIWindow *uiWin) return nullptr; } -void Window::setTitle(const char *name) {} +void Window::setTitle(const char*) {} -void Window::setAcceptDnd(bool on) {} +void Window::setAcceptDnd(bool) {} NativeWindow Window::nativeObject() const { @@ -265,7 +265,7 @@ IG::PixelFormat Window::pixelFormat() const return PixelFmtRGBA8888; } -void Window::setIntendedFrameRate(FrameRate rate) {} +void Window::setIntendedFrameRate(FrameRate) {} void WindowConfig::setFormat(IG::PixelFormat) {} diff --git a/imagine/src/base/iphone/input.mm b/imagine/src/base/iphone/input.mm index 26fdfca11..76d8ab73a 100755 --- a/imagine/src/base/iphone/input.mm +++ b/imagine/src/base/iphone/input.mm @@ -74,12 +74,10 @@ static_assert(__has_feature(objc_arc), "This file requires ARC"); namespace IG::Input { -static constexpr int GSEVENT_TYPE = 2; -static constexpr int GSEVENT_FLAGS = 12; -static constexpr int GSEVENT_TYPE_KEYDOWN = 10; -static constexpr int GSEVENT_TYPE_KEYUP = 11; - -static constexpr double MSEC_PER_SEC = 1000; +constexpr inline int GSEVENT_TYPE = 2; +constexpr inline int GSEVENT_FLAGS = 12; +constexpr inline int GSEVENT_TYPE_KEYDOWN = 10; +constexpr inline int GSEVENT_TYPE_KEYUP = 11; static Input::Device *keyDevPtr; static bool hardwareKBAttached = false; @@ -150,7 +148,8 @@ static void setupTextView(ApplicationContext ctx, UITextField *vkbdField, NSStri logMsg("init vkeyboard"); } -UIKitTextField::UIKitTextField(ApplicationContext ctx, TextFieldDelegate del, CStringView initialText, CStringView promptText, int fontSizePixels): +UIKitTextField::UIKitTextField(ApplicationContext ctx, TextFieldDelegate del, CStringView initialText, + [[maybe_unused]] CStringView promptText, [[maybe_unused]] int fontSizePixels): ctx{ctx} { auto uiTextField = [[UITextField alloc] initWithFrame: toCGRect(*ctx.deviceWindow(), textRect)]; diff --git a/imagine/src/base/iphone/iphone.mm b/imagine/src/base/iphone/iphone.mm index 5c9a6ef69..48e57b79b 100755 --- a/imagine/src/base/iphone/iphone.mm +++ b/imagine/src/base/iphone/iphone.mm @@ -55,7 +55,6 @@ Application *appPtr{}; bool isIPad = false; static bool isRunningAsSystemApp = false; UIApplication *sharedApp{}; -static const char *docPath{}; static FS::PathString appPath{}; static id onOrientationChangedObserver = nil; @@ -91,7 +90,6 @@ static Screen &setupUIScreen(ApplicationContext ctx, UIScreen *screen, bool setO screen.overscanCompensation = UIScreenOverscanCompensationInsetApplicationFrame; IOSScreen::InitParams initParams{(__bridge void*)screen}; auto s = std::make_unique(ctx, initParams); - [s->displayLink() addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; return ctx.application().addScreen(ctx, std::move(s), true); } @@ -146,7 +144,7 @@ IOSApplication::IOSApplication(ApplicationInitParams initParams): log.info("screen {} already in list", (__bridge void*)screen); return; } - auto &s = setupUIScreen(ctx, screen, true); + setupUIScreen(ctx, screen, true); }]; [nCenter addObserverForName:UIScreenDidDisconnectNotification object:nil queue:nil usingBlock: @@ -157,14 +155,14 @@ IOSApplication::IOSApplication(ApplicationInitParams initParams): if(auto removedScreen = removeScreen(ctx, (__bridge void*)screen, true); removedScreen) { - [removedScreen->displayLink() removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + log.info("screen removed from list"); } }]; if(Config::DEBUG_BUILD) { [nCenter addObserverForName:UIScreenModeDidChangeNotification object:nil queue:nil usingBlock: - ^(NSNotification *note) + ^(NSNotification*) { log.info("screen mode change"); }]; @@ -176,7 +174,6 @@ IOSApplication::IOSApplication(ApplicationInitParams initParams): } #else mainScreen().init([UIScreen mainScreen]); - [mainScreen().displayLink() addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; #endif } @@ -392,7 +389,7 @@ void ApplicationContext::setOnDeviceOrientationChanged(DeviceOrientationChangedD } onOrientationChangedObserver = [nCenter addObserverForName:UIDeviceOrientationDidChangeNotification object:nil queue:nil usingBlock: - ^(NSNotification *note) + ^(NSNotification*) { auto o = iOSOrientationToGfx([[UIDevice currentDevice] orientation]); if(o != Rotation::ANY) @@ -427,7 +424,7 @@ Orientations ApplicationContext::defaultSystemOrientations() const return isIPad ? Orientations::all() : Orientations::allButUpsideDown(); } -void ApplicationContext::setOnSystemOrientationChanged(SystemOrientationChangedDelegate del) +void ApplicationContext::setOnSystemOrientationChanged(SystemOrientationChangedDelegate) { // TODO } @@ -590,7 +587,7 @@ CLINK int32_t __isOSVersionAtLeast(int32_t major, int32_t minor, int32_t submino return subminor <= platformVersion.subminor; } -CLINK int32_t __isPlatformVersionAtLeast(uint32_t Platform, uint32_t major, uint32_t minor, uint32_t subminor) +CLINK int32_t __isPlatformVersionAtLeast([[maybe_unused]] uint32_t Platform, uint32_t major, uint32_t minor, uint32_t subminor) { return __isOSVersionAtLeast(major, minor, subminor); } @@ -598,7 +595,7 @@ CLINK int32_t __isPlatformVersionAtLeast(uint32_t Platform, uint32_t major, uint #if __IPHONE_OS_VERSION_MIN_REQUIRED < 100000 CLINK int clock_gettime(clockid_t clock_id, struct timespec *tp) { - if(clock_id == CLOCK_MONOTONIC) + if(clock_id == CLOCK_MONOTONIC_RAW) { auto nanos = mach_absolute_time() * timebaseInfo.numer / timebaseInfo.denom; tp->tv_sec = nanos / 1000000000ULL; diff --git a/imagine/src/base/linux/ApplicationContext.cc b/imagine/src/base/linux/ApplicationContext.cc index a40a1a296..c8c5e0e0a 100644 --- a/imagine/src/base/linux/ApplicationContext.cc +++ b/imagine/src/base/linux/ApplicationContext.cc @@ -13,7 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "AppCtx" #include #include #include @@ -24,6 +23,7 @@ namespace IG { +constexpr SystemLogger log{"AppCtx"}; constexpr mode_t defaultDirMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH; void ApplicationContext::exit(int returnVal) @@ -36,8 +36,8 @@ void ApplicationContext::exit(int returnVal) void ApplicationContext::openURL(CStringView url) const { - logMsg("opening url:%s", url.data()); - auto ret = system(std::format("xdg-open {}", url).data()); + log.info("opening url:{}", url); + [[maybe_unused]] auto ret = system(std::format("xdg-open {}", url).data()); } FS::PathString ApplicationContext::assetPath(const char *) const @@ -61,7 +61,7 @@ FS::PathString ApplicationContext::supportPath(const char *appName) const g_mkdir_with_parents(path.data(), defaultDirMode); return path; } - logErr("XDG_DATA_HOME and HOME env variables not defined"); + log.error("XDG_DATA_HOME and HOME env variables not defined"); return {}; } @@ -81,7 +81,7 @@ FS::PathString ApplicationContext::cachePath(const char *appName) const g_mkdir_with_parents(path.data(), defaultDirMode); return path; } - logErr("XDG_DATA_HOME and HOME env variables not defined"); + log.error("XDG_DATA_HOME and HOME env variables not defined"); return {}; } @@ -94,7 +94,7 @@ FS::PathString ApplicationContext::sharedStoragePath() const { if(entry.type() == FS::file_type::directory && std::string_view{entry.name()} == "mmcblk") { - //logMsg("storage dir: %s", entry.path().data()); + //log.info("storage dir:{}", entry.path()); return entry.path(); } } @@ -105,7 +105,7 @@ FS::PathString ApplicationContext::sharedStoragePath() const { return home; } - logErr("HOME env variable not defined"); + log.error("HOME env variable not defined"); return {}; } @@ -136,7 +136,7 @@ FS::PathString ApplicationContext::libPath(const char *) const void ApplicationContext::exitWithMessage(int exitVal, const char *msg) { auto cmd = std::format("zenity --warning --title='Exited with error' --text='{}'", msg); - auto cmdResult = system(cmd.data()); + [[maybe_unused]] auto cmdResult = system(cmd.data()); ::exit(exitVal); } diff --git a/imagine/src/base/linux/DRMFrameTimer.cc b/imagine/src/base/linux/DRMFrameTimer.cc index 1955ad8a0..f21e2c9f0 100644 --- a/imagine/src/base/linux/DRMFrameTimer.cc +++ b/imagine/src/base/linux/DRMFrameTimer.cc @@ -13,7 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "DRMFrameTimer" #include #include #include @@ -25,12 +24,14 @@ namespace IG { +constexpr SystemLogger log{"DRMFrameTimer"}; + static UniqueFileDescriptor openDevice() { const char *drmCardPath = getenv("KMSDEVICE"); if(!drmCardPath) drmCardPath = "/dev/dri/card0"; - logMsg("opening device path:%s", drmCardPath); + log.info("opening device path:{}", drmCardPath); return open(drmCardPath, O_RDWR | O_CLOEXEC, 0); } @@ -42,8 +43,8 @@ DRMFrameTimer::DRMFrameTimer(Screen &screen, EventLoop loop) logErr("error opening device:%s", std::system_category().message(errno).c_str()); return; } - fdSrc = {"DRMFrameTimer", std::move(fd), loop, - [this, &screen](int fd, int event) + fdSrc = {std::move(fd), {.debugLabel = "DRMFrameTimer", .eventLoop = loop}, + [this, &screen](int fd, int) { requested = false; if(cancelled) @@ -54,7 +55,7 @@ DRMFrameTimer::DRMFrameTimer(Screen &screen, EventLoop loop) drmEventContext ctx{}; ctx.version = DRM_EVENT_CONTEXT_VERSION; ctx.vblank_handler = - [](int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data) + []([[maybe_unused]] int fd, [[maybe_unused]] unsigned int frame, unsigned int sec, unsigned int usec, void* data) { auto &frameTimer = *((DRMFrameTimer*)data); constexpr uint64_t USEC_PER_SEC = 1000000; @@ -64,7 +65,7 @@ DRMFrameTimer::DRMFrameTimer(Screen &screen, EventLoop loop) auto err = drmHandleEvent(fd, &ctx); if(err) { - logErr("error in drmHandleEvent"); + log.error("error in drmHandleEvent"); } if(screen.isPosted()) { @@ -72,7 +73,8 @@ DRMFrameTimer::DRMFrameTimer(Screen &screen, EventLoop loop) scheduleVSync(); } return true; - }}; + } + }; } void DRMFrameTimer::scheduleVSync() @@ -89,7 +91,7 @@ void DRMFrameTimer::scheduleVSync() if(int err = drmWaitVBlank(fdSrc.fd(), &vbl); err) { - logErr("error in drmWaitVBlank"); + log.error("error in drmWaitVBlank"); } } @@ -98,12 +100,17 @@ void DRMFrameTimer::cancel() cancelled = true; } +void DRMFrameTimer::setEventsOnThisThread(ApplicationContext) +{ + fdSrc.attach(EventLoop::forThread(), {}); +} + bool DRMFrameTimer::testSupport() { int fd = openDevice(); if(fd == -1) { - logErr("error opening device:%s", std::system_category().message(errno).c_str()); + log.error("error opening device:{}", std::system_category().message(errno)); return false; } // test drmWaitVBlank @@ -114,7 +121,7 @@ bool DRMFrameTimer::testSupport() if(int err = drmWaitVBlank(fd, &vbl); err) { - logErr("error in drmWaitVBlank:%s, cannot use frame timer", std::system_category().message(errno).c_str()); + log.error("error in drmWaitVBlank:{}, cannot use frame timer", std::system_category().message(errno)); return false; } } diff --git a/imagine/src/base/linux/FBDevFrameTimer.cc b/imagine/src/base/linux/FBDevFrameTimer.cc index 2ffabceef..68c575e03 100644 --- a/imagine/src/base/linux/FBDevFrameTimer.cc +++ b/imagine/src/base/linux/FBDevFrameTimer.cc @@ -13,7 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "FBDevFrameTimer" #include #include #include @@ -29,34 +28,25 @@ namespace IG { +constexpr SystemLogger log{"FBDevFrameTimer"}; + static UniqueFileDescriptor openDevice() { const char *fbDevPath = "/dev/fb0"; - logMsg("opening device path:%s", fbDevPath); + log.info("opening device path:{}", fbDevPath); return open(fbDevPath, O_RDWR | O_CLOEXEC); } -FBDevFrameTimer::FBDevFrameTimer(Screen &screen, EventLoop loop) -{ - auto fbdev = openDevice(); - if(fbdev == -1) +FBDevFrameTimer::FBDevFrameTimer(Screen &screen, EventLoop loop): + fdSrc { - logErr("error opening device:%s", std::generic_category().message(errno).c_str()); - return; - } - int fd = eventfd(0, 0); - if(fd == -1) - { - logErr("error creating eventfd"); - return; - } - fdSrc = {"FBDevFrameTimer", fd, loop, - [this, &screen](int fd, int event) + eventfd(0, 0), {.debugLabel = "FBDevFrameTimer", .eventLoop = loop}, + [this, &screen](int fd, int) { eventfd_t timestamp; auto ret = read(fd, ×tamp, sizeof(timestamp)); assert(ret == sizeof(timestamp)); - //logDMsg("read frame timestamp:%lu", (long unsigned int)timestamp); + //log.debug("read frame timestamp:{}", timestamp); requested = false; if(cancelled) { @@ -69,25 +59,33 @@ FBDevFrameTimer::FBDevFrameTimer(Screen &screen, EventLoop loop) scheduleVSync(); } return true; - }}; + } + } +{ + auto fbdev = openDevice(); + if(fbdev == -1) + { + log.error("error opening device:{}", std::generic_category().message(errno)); + return; + } thread = std::thread( - [this, fd, fbdev = fbdev.release()]() + [this, fd = fdSrc.fd(), fbdev = fbdev.release()]() { - //logMsg("ready to wait for vsync"); + //log.info("ready to wait for vsync"); for(;;) { sem.acquire(); if(quiting) break; - //logMsg("waiting for vsync"); + //log.info("waiting for vsync"); int arg = 0; if(int res = ioctl(fbdev, FBIO_WAITFORVSYNC, &arg); res == -1) { - logErr("error in ioctl FBIO_WAITFORVSYNC"); + log.error("error in ioctl FBIO_WAITFORVSYNC"); } eventfd_t timestamp = SteadyClock::now().time_since_epoch().count(); - //logMsg("got vsync at time %lu", (long unsigned int)timestamp); + //log.info("got vsync at time:{}", timestamp); auto ret = write(fd, ×tamp, sizeof(timestamp)); assert(ret == sizeof(timestamp)); } @@ -119,19 +117,24 @@ void FBDevFrameTimer::cancel() cancelled = true; } +void FBDevFrameTimer::setEventsOnThisThread(ApplicationContext) +{ + fdSrc.attach(EventLoop::forThread(), {}); +} + bool FBDevFrameTimer::testSupport() { auto fbdev = openDevice(); if(fbdev == -1) { - logErr("error opening device:%s", std::generic_category().message(errno).c_str()); + log.error("error opening device:{}", std::generic_category().message(errno)); return false; } // test ioctl FBIO_WAITFORVSYNC if(int arg = 0, res = ioctl(fbdev, FBIO_WAITFORVSYNC, &arg); res == -1) { - logErr("error in ioctl FBIO_WAITFORVSYNC, cannot use frame timer"); + log.error("error in ioctl FBIO_WAITFORVSYNC, cannot use frame timer"); return false; } return true; diff --git a/imagine/src/base/linux/dbus.cc b/imagine/src/base/linux/dbus.cc index f42b03634..6833c2ca7 100644 --- a/imagine/src/base/linux/dbus.cc +++ b/imagine/src/base/linux/dbus.cc @@ -58,8 +58,8 @@ static guint setOpenPathListener(LinuxApplication &app, GDBusConnection *bus, co return g_dbus_connection_signal_subscribe(bus, name, name, "openPath", appObjectPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, - [](GDBusConnection *connection, const gchar *name, const gchar *path, const gchar *interface, - const gchar *signal, GVariant *param, gpointer userData) + [](GDBusConnection*, [[maybe_unused]] const gchar *name, [[maybe_unused]] const gchar *path, [[maybe_unused]] const gchar *interface, + [[maybe_unused]] const gchar *signal, GVariant *param, gpointer userData) { if(!g_variant_is_of_type(param, G_VARIANT_TYPE("(s)"))) { diff --git a/imagine/src/base/x11/Application.cc b/imagine/src/base/x11/Application.cc index 771cee877..a6de08f37 100755 --- a/imagine/src/base/x11/Application.cc +++ b/imagine/src/base/x11/Application.cc @@ -30,11 +30,17 @@ namespace IG constexpr SystemLogger log{"X11"}; +static void initXFixes(xcb_connection_t& conn); + XApplication::XApplication(ApplicationInitParams initParams): LinuxApplication{initParams}, - supportedFrameTimer{testFrameTimers()} + supportedFrameTimer{testFrameTimers()}, + xEventSrc{makeXDisplayConnection(initParams.eventLoop)} { - xEventSrc = makeXDisplayConnection(initParams.eventLoop); + ApplicationContext appCtx{static_cast(*this)}; + addScreen(appCtx, std::make_unique(appCtx, Screen::InitParams{*xConn, *xScr}), false); + initXFixes(*xConn); + initInputSystem(); } XApplication::~XApplication() @@ -296,16 +302,16 @@ FDEventSource XApplication::makeXDisplayConnection(EventLoop loop) auto &screen = *xcb_setup_roots_iterator(xcb_get_setup(&conn)).data; xScr = &screen; log.info("created X connection:{} screen:{}", (void*)&conn, (void*)&screen); - ApplicationContext appCtx{static_cast(*this)}; - addScreen(appCtx, std::make_unique(appCtx, Screen::InitParams{conn, screen}), false); - initXFixes(conn); - initInputSystem(); - FDEventSource x11Src{"XServer", xcb_get_file_descriptor(&conn)}; - x11Src.attach(loop, [this, &conn](int fd, int event) + FDEventSource x11Src { - runX11Events(conn); - return true; - }); + xcb_get_file_descriptor(&conn), + {.debugLabel = "XServer", .eventLoop = loop}, + [this, &conn](int, int) + { + runX11Events(conn); + return true; + } + }; return x11Src; } diff --git a/imagine/src/base/x11/FrameTimer.cc b/imagine/src/base/x11/FrameTimer.cc index 1196b1a3f..bf85153fc 100644 --- a/imagine/src/base/x11/FrameTimer.cc +++ b/imagine/src/base/x11/FrameTimer.cc @@ -13,7 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "FrameTimer" #include #include #include @@ -21,6 +20,8 @@ namespace IG { +constexpr SystemLogger log{"FrameTimer"}; + void XApplication::emplaceFrameTimer(FrameTimer &t, Screen &screen, bool useVariableTime) { if(useVariableTime) @@ -45,16 +46,16 @@ SupportedFrameTimer XApplication::testFrameTimers() #if CONFIG_PACKAGE_LIBDRM if(DRMFrameTimer::testSupport()) { - logMsg("using DRM frame timer"); + log.info("using DRM frame timer"); return SupportedFrameTimer::DRM; } #endif if(FBDevFrameTimer::testSupport()) { - logMsg("using FBDev frame timer"); + log.info("using FBDev frame timer"); return SupportedFrameTimer::FBDEV; } - logMsg("using simple frame timer"); + log.info("using simple frame timer"); return SupportedFrameTimer::SIMPLE; } diff --git a/imagine/src/base/x11/XGLContextEGL.cc b/imagine/src/base/x11/XGLContextEGL.cc index 19545dd47..a0c147147 100644 --- a/imagine/src/base/x11/XGLContextEGL.cc +++ b/imagine/src/base/x11/XGLContextEGL.cc @@ -79,7 +79,7 @@ std::optional GLManager::tryBufferConfig(ApplicationContext ctx, // find the config with a visual bits/channel == 8 for(auto conf : configs | std::views::take(configCount)) { - auto visualId = eglConfigAttrib(display(), conf, EGL_NATIVE_VISUAL_ID); + [[maybe_unused]] auto visualId = eglConfigAttrib(display(), conf, EGL_NATIVE_VISUAL_ID); auto found = findVisualType(ctx.application().xScreen(), 32, [&](const xcb_visualtype_t& v) { return v.bits_per_rgb_value == 8; diff --git a/imagine/src/base/x11/XScreen.cc b/imagine/src/base/x11/XScreen.cc index 0f87a3e89..07d29cad5 100644 --- a/imagine/src/base/x11/XScreen.cc +++ b/imagine/src/base/x11/XScreen.cc @@ -91,7 +91,7 @@ XScreen::XScreen(ApplicationContext ctx, InitParams params) } assert(frameTime_.count()); } - log.info("screen:{} {}x{} ({}x{}mm) %.2fHz", (void*)&screen, + log.info("screen:{} {}x{} ({}x{}mm) {}Hz", (void*)&screen, screen.width_in_pixels, screen.height_in_pixels, (int)xMM, (int)yMM, frameRate_); ctx.application().emplaceFrameTimer(frameTimer, *static_cast(this)); } @@ -204,4 +204,15 @@ void Screen::setVariableFrameTime(bool useVariableTime) application().emplaceFrameTimer(frameTimer, *static_cast(this), useVariableTime); } +void Screen::setFrameEventsOnThisThread() +{ + unpostFrame(); + frameTimer.setEventsOnThisThread(appContext()); +} + +void Screen::removeFrameEvents() +{ + unpostFrame(); +} + } diff --git a/imagine/src/base/x11/XWindow.cc b/imagine/src/base/x11/XWindow.cc index 0d93e5ede..6872c3faf 100644 --- a/imagine/src/base/x11/XWindow.cc +++ b/imagine/src/base/x11/XWindow.cc @@ -237,6 +237,7 @@ XWindow::~XWindow() { xcb_free_colormap(xConn, colormap); } + xcb_flush(xConn); } void Window::show() @@ -257,7 +258,7 @@ void Window::setIntendedFrameRate(FrameRate rate) screen()->setFrameRate(rate); } -void Window::setFormat(NativeWindowFormat fmt) {} +void Window::setFormat(NativeWindowFormat) {} void Window::setFormat(PixelFormat) {} diff --git a/imagine/src/base/x11/input.cc b/imagine/src/base/x11/input.cc index cfd62c625..0b4f6c712 100755 --- a/imagine/src/base/x11/input.cc +++ b/imagine/src/base/x11/input.cc @@ -87,11 +87,6 @@ static bool hasXInputDeviceId(Input::Device &d, int id) return isXInputDevice(d) && d.id() == id; } -static void setXcbMask(uint8_t* mask, int bit) -{ - mask[bit >> 3] |= 1 << (bit & 7); -} - static inline float fixed1616ToFloat(xcb_input_fp1616_t val) { return float(val) / 0x10000; @@ -137,7 +132,7 @@ constexpr XIEventMaskData windowXIEventMaskData() void XApplication::initPerWindowInputData(xcb_window_t win) { - if(Config::MACHINE_IS_PANDORA) + if constexpr(Config::MACHINE_IS_PANDORA) { xcb_xfixes_hide_cursor(xConn, win); } @@ -146,7 +141,6 @@ void XApplication::initPerWindowInputData(xcb_window_t win) if(!blankCursor) { // make a blank cursor - char data[1]{}; auto blank = xcb_generate_id(xConn); xcb_create_pixmap(xConn, 1, blank, win, 1, 1); blankCursor = xcb_generate_id(xConn); @@ -315,15 +309,6 @@ void XApplication::deinitInputSystem() xkb_state_unref(kbState); } -static uint32_t makePointerButtonState(const xcb_input_button_press_event_t& ev) -{ - auto len = xcb_input_button_press_button_mask_length(&ev); - auto mask = xcb_input_button_press_button_mask(&ev); - uint8_t byte1 = len > 0 ? mask[0] : 0; - uint8_t byte2 = len > 1 ? mask[1] : 0; - return byte1 | (byte2 << 8); -} - static xcb_window_t eventXWindow(const xcb_ge_generic_event_t& e) { switch(e.event_type) @@ -440,7 +425,6 @@ bool XApplication::handleXI2GenericEvent(xcb_ge_generic_event_t& event) auto dev = deviceForInputId(event.sourceid); auto k = xkb_state_key_get_one_sym(kbState, event.detail); bool repeated = event.flags & XCB_INPUT_KEY_EVENT_FLAGS_KEY_REPEAT; - //log.info("KeySym:{}, KeyCode:{}, repeat:{}", k, ievent.detail, repeated); if(pushed && k == XKB_KEY_Return && (event.mods.effective & (XCB_MOD_MASK_1 | XCB_MOD_MASK_5)) && !repeated) { win.toggleFullScreen(); @@ -448,6 +432,7 @@ bool XApplication::handleXI2GenericEvent(xcb_ge_generic_event_t& event) else { auto key = keysymToKey(k); + //log.info("KeySym:{}, KeyCode:{}, repeat:{}", k, key, repeated); auto ev = Input::KeyEvent{Input::Map::SYSTEM, key, action, (uint32_t)event.mods.effective, repeated, Input::Source::KEYBOARD, time, dev}; ev.setX11RawKey(event.detail); diff --git a/imagine/src/bluetooth/AndroidBluetoothAdapter.cc b/imagine/src/bluetooth/AndroidBluetoothAdapter.cc index 8489c8ab9..3abd50c24 100644 --- a/imagine/src/bluetooth/AndroidBluetoothAdapter.cc +++ b/imagine/src/bluetooth/AndroidBluetoothAdapter.cc @@ -63,13 +63,13 @@ void AndroidBluetoothAdapter::sendSocketStatusMessage(const SocketStatusMessage } } -static void JNICALL btScanStatus(JNIEnv* env, jobject thiz, jlong btaAddr, jint res) +static void JNICALL btScanStatus(JNIEnv*, jobject, jlong btaAddr, jint res) { auto &bta = *reinterpret_cast(btaAddr); bta.handleScanStatus(BluetoothScanState(res)); } -void AndroidBluetoothAdapter::handleScanStatus(BluetoothScanState result) +void AndroidBluetoothAdapter::handleScanStatus(BluetoothScanState) { auto &bta = static_cast(*this); assert(inDetect); @@ -81,7 +81,7 @@ void AndroidBluetoothAdapter::handleScanStatus(BluetoothScanState result) inDetect = 0; } -static jboolean JNICALL scanDeviceClass(JNIEnv* env, jobject thiz, jlong btaAddr, jint classInt) +static jboolean JNICALL scanDeviceClass(JNIEnv*, jobject, jlong btaAddr, jint classInt) { auto &bta = *reinterpret_cast(btaAddr); return bta.handleScanClass(classInt); @@ -108,7 +108,7 @@ bool AndroidBluetoothAdapter::handleScanClass(uint32_t classInt) return 1; } -static void JNICALL scanDeviceName(JNIEnv* env, jobject thiz, jlong btaAddr, jstring name, jstring addr) +static void JNICALL scanDeviceName(JNIEnv* env, jobject, jlong btaAddr, jstring name, jstring addr) { auto &bta = *reinterpret_cast(btaAddr); bta.handleScanName(env, name, addr); @@ -134,7 +134,7 @@ void AndroidBluetoothAdapter::handleScanName(JNIEnv* env, jstring name, jstring env->ReleaseStringUTFChars(name, nameStr); } -static void JNICALL turnOnResult(JNIEnv* env, jobject thiz, jlong btaAddr, jboolean success) +static void JNICALL turnOnResult(JNIEnv*, jobject, jlong btaAddr, jboolean success) { auto &bta = *reinterpret_cast(btaAddr); bta.handleTurnOnResult(success); @@ -231,12 +231,12 @@ bool BluetoothAdapter::openDefault() adapter = env->NewGlobalRef(adapter); assert(adapter); { - int ret = pipe(statusPipe); + [[maybe_unused]] int ret = pipe(statusPipe); assert(ret == 0); ret = ALooper_addFd(EventLoop::forThread().nativeObject(), statusPipe[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, [](int fd, int events, void* data) { - if(events & POLLEV_ERR) + if(events & pollEventError) return 0; while(fd_bytesReadable(fd)) { @@ -370,13 +370,13 @@ bool BluetoothAdapter::isInScan() const { return inDetect; } bool AndroidBluetoothSocket::readPendingData(int events) { auto &sock = static_cast(*this); - if(events & POLLEV_ERR) + if(events & pollEventError) { logMsg("socket %d disconnected", nativeFd); sock.onStatus(sock, BluetoothSocketState::ReadError); return false; } - else if(events & POLLEV_IN) + else if(events & pollEventInput) { char buff[50]; //logMsg("at least %d bytes ready on socket %d", fd_bytesReadable(nativeFd), nativeFd); @@ -410,11 +410,7 @@ void AndroidBluetoothSocket::onStatusDelegateMessage(BluetoothAdapter& bta, Blue { if(nativeFd != -1) { - fdSrc = {nativeFd, {}, - [this](int fd, int events) - { - return readPendingData(events); - }}; + fdSrc = {nativeFd, {.eventLoop = EventLoop::forThread()}, [this](int, int events) { return readPendingData(events); }}; } else { @@ -436,12 +432,12 @@ void AndroidBluetoothSocket::onStatusDelegateMessage(BluetoothAdapter& bta, Blue auto looper = EventLoop::forThread().nativeObject(); int dataPipe[2]; { - int ret = pipe(dataPipe); + [[maybe_unused]] int ret = pipe(dataPipe); assert(ret == 0); ret = ALooper_addFd(looper, dataPipe[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, [](int fd, int events, void* data) { - if(events & POLLEV_ERR) + if(events & pollEventError) return 0; auto &socket = *((BluetoothSocket*)data); while(fd_bytesReadable(fd)) diff --git a/imagine/src/bluetooth/BluetoothInputDevScanner.cc b/imagine/src/bluetooth/BluetoothInputDevScanner.cc index a424ab384..1b8046e36 100644 --- a/imagine/src/bluetooth/BluetoothInputDevScanner.cc +++ b/imagine/src/bluetooth/BluetoothInputDevScanner.cc @@ -35,7 +35,7 @@ static bool hidServiceActive = false; static std::unique_ptr pendingPS3Controller; static BluetoothPendingSocket pendingSocket; static BluetoothAdapter::OnStatusDelegate onServerStatus; -static Timer unregisterHIDServiceCallback{"unregisterHIDServiceCallback"}; +static std::optional unregisterHIDServiceCallback; #endif static bool testSupportedBTDevClasses(std::array devClass) @@ -116,7 +116,7 @@ bool listenForDevices(ApplicationContext ctx, BluetoothAdapter &bta, const Bluet logMsg("registering HID PSMs"); hidServiceActive = true; bta.setL2capService(0x13, true, - [](BluetoothAdapter &bta, BluetoothScanState state, int arg) + [](BluetoothAdapter& bta, BluetoothScanState state, int) { if(state <= BluetoothScanState::Failed) { @@ -127,7 +127,7 @@ bool listenForDevices(ApplicationContext ctx, BluetoothAdapter &bta, const Bluet logMsg("INT PSM registered"); // now register the 2nd PSM bta.setL2capService(0x11, true, - [](BluetoothAdapter &bta, BluetoothScanState state, int arg) + [](BluetoothAdapter& bta, BluetoothScanState state, int) { if(state <= BluetoothScanState::Failed) { @@ -139,14 +139,18 @@ bool listenForDevices(ApplicationContext ctx, BluetoothAdapter &bta, const Bluet logMsg("CTL PSM registered"); onServerStatus(bta, BluetoothScanState::Complete, 0); // both PSMs are registered - unregisterHIDServiceCallback.runIn(IG::Seconds{8}, {}, - [&bta]() - { - logMsg("unregistering HID PSMs from timeout"); - bta.setL2capService(0x11, false, {}); - bta.setL2capService(0x13, false, {}); - hidServiceActive = false; - }); + if(!unregisterHIDServiceCallback) + { + unregisterHIDServiceCallback.emplace(TimerDesc{.debugLabel = "unregisterHIDServiceCallback"}, + [&bta] + { + logMsg("unregistering HID PSMs from timeout"); + bta.setL2capService(0x11, false, {}); + bta.setL2capService(0x13, false, {}); + hidServiceActive = false; + }); + } + unregisterHIDServiceCallback->runIn(IG::Seconds{8}); } ); } diff --git a/imagine/src/bluetooth/BluezBluetoothAdapter.cc b/imagine/src/bluetooth/BluezBluetoothAdapter.cc index 3d20f4909..9971eca44 100644 --- a/imagine/src/bluetooth/BluezBluetoothAdapter.cc +++ b/imagine/src/bluetooth/BluezBluetoothAdapter.cc @@ -303,8 +303,8 @@ void BluetoothAdapter::setL2capService(uint32_t psm, bool active, OnStatusDelega } auto &server = serverList.emplace_back(psm, serverFd); - server.connectSrc = {serverFd, {}, - [this](int fd, int events) + server.connectSrc = {serverFd, {.eventLoop = EventLoop::forThread()}, + [this](int fd, int) { logMsg("incoming l2cap connection from server fd %d", fd); BluetoothPendingSocket pending; @@ -320,8 +320,9 @@ void BluetoothAdapter::setL2capService(uint32_t psm, bool active, OnStatusDelega logMsg("for PSM 0x%X, fd %d", pending.addr.l2_psm, pending.fd); onIncomingL2capConnection(*this, pending); return true; - }}; - //addPollEvent(serverFd, serverList.back().onConnect, POLLEV_IN); + } + }; + //addPollEvent(serverFd, serverList.back().onConnect, pollEventInput); onResult(*this, BluetoothScanState::Complete, 0); } @@ -354,18 +355,18 @@ std::system_error BluetoothSocket::open(BluetoothAdapter&, BluetoothPendingSocke fd = pending.fd; pending = {}; if(onStatus(*this, BluetoothSocketState::Opened) == 1) - setupFDEvents(POLLEV_IN); - //addPollEvent(fd, pollEvDel, POLLEV_IN); + setupFDEvents(pollEventInput); + //addPollEvent(fd, pollEvDel, pollEventInput); return std::error_code{}; } -bool BluezBluetoothSocket::readPendingData(int events) +bool BluezBluetoothSocket::readPendingData(PollEventFlags events) { auto &sock = static_cast(*this); - if(events & POLLEV_ERR) + if(events & pollEventError) { logMsg("poll error with events %X", events); - if(events & POLLEV_OUT) // happened while connecting + if(events & pollEventOutput) // happened while connecting { logErr("error connecting socket %d", fd); if(Config::DEBUG_BUILD) @@ -384,7 +385,7 @@ bool BluezBluetoothSocket::readPendingData(int events) } return false; } - else if(events & POLLEV_IN) + else if(events & pollEventInput) { char buff[50]; //logMsg("at least %d bytes ready on socket %d", fd_bytesReadable(fd), fd); @@ -403,11 +404,11 @@ bool BluezBluetoothSocket::readPendingData(int events) break; // socket was closed } } - else if(events & POLLEV_OUT) + else if(events & pollEventOutput) { logMsg("finished opening socket %d", fd); if(sock.onStatus(sock, BluetoothSocketState::Opened) == 1) - fdSrc.setEvents(POLLEV_IN); + fdSrc.setEvents(pollEventInput); else fdSrc.detach(); } @@ -415,14 +416,9 @@ bool BluezBluetoothSocket::readPendingData(int events) return true; } -void BluezBluetoothSocket::setupFDEvents(int events) +void BluezBluetoothSocket::setupFDEvents(PollEventFlags events) { - fdSrc = {fd, {}, - [this](int fd, int events) - { - return readPendingData(events); - }, - POLLEV_OUT}; + fdSrc = {fd, {.eventLoop = EventLoop::forThread(), .events = events}, [this](int, int events) {return readPendingData(events); }}; } std::system_error BluetoothSocket::openRfcomm(BluetoothAdapter &, BluetoothAddr bdaddr, uint32_t channel) @@ -449,7 +445,7 @@ std::system_error BluetoothSocket::openRfcomm(BluetoothAdapter &, BluetoothAddr return IO_ERROR;*/ } fd_setNonblock(fd, 0); - setupFDEvents(POLLEV_OUT); + setupFDEvents(pollEventOutput); return std::error_code{}; } @@ -481,7 +477,7 @@ std::system_error BluetoothSocket::openL2cap(BluetoothAdapter &, BluetoothAddr b //logMsg("success"); } fd_setNonblock(fd, 0); - setupFDEvents(POLLEV_OUT); + setupFDEvents(pollEventOutput); return std::error_code{}; } diff --git a/imagine/src/bluetooth/BtstackBluetoothAdapter.cc b/imagine/src/bluetooth/BtstackBluetoothAdapter.cc index b03d2e750..f5e562649 100644 --- a/imagine/src/bluetooth/BtstackBluetoothAdapter.cc +++ b/imagine/src/bluetooth/BtstackBluetoothAdapter.cc @@ -217,7 +217,7 @@ public: } }; -static void sprintBTAddr(char *addrStr, bd_addr_t &addr) +inline void sprintBTAddr(char *addrStr, bd_addr_t &addr) { strcpy(addrStr, ""); for(auto i : iotaCount(6)) @@ -1001,7 +1001,7 @@ void BtstackBluetoothSocket::setPin(const void *pin, uint32_t size) pinSize = size; } -void BtstackBluetoothSocket::handleRfcommChannelOpened(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) +void BtstackBluetoothSocket::handleRfcommChannelOpened([[maybe_unused]] uint8_t packet_type, [[maybe_unused]] uint16_t channel, uint8_t *packet, [[maybe_unused]] uint16_t size) { int ch = packet[11]; bd_addr_t addr; @@ -1034,7 +1034,7 @@ void BtstackBluetoothSocket::handleRfcommChannelOpened(uint8_t packet_type, uint } } -void BtstackBluetoothSocket::handleL2capChannelOpened(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) +void BtstackBluetoothSocket::handleL2capChannelOpened([[maybe_unused]] uint8_t packet_type, [[maybe_unused]] uint16_t channel, uint8_t *packet, [[maybe_unused]] uint16_t size) { uint16_t psm = READ_BT_16(packet, 11); bd_addr_t addr; diff --git a/imagine/src/bluetooth/IControlPad.cc b/imagine/src/bluetooth/IControlPad.cc index 3856a22cd..8a339eb7f 100644 --- a/imagine/src/bluetooth/IControlPad.cc +++ b/imagine/src/bluetooth/IControlPad.cc @@ -29,7 +29,7 @@ namespace IG using namespace IG::Input; -static const PackedInputAccess iCPDataAccess[] = +constexpr PackedInputAccess iCPDataAccess[] { { 0, bit(2), iControlPadKey::LEFT }, { 0, bit(1), iControlPadKey::RIGHT }, @@ -46,36 +46,36 @@ static const PackedInputAccess iCPDataAccess[] = { 1, bit(1), iControlPadKey::START }, }; -static const uint8_t CMD_SPP_GP_REPORTS = 0xAD; -static const uint8_t turnOnReports[2] = { CMD_SPP_GP_REPORTS, 1 }; -static const uint8_t turnOffReports[2] = { CMD_SPP_GP_REPORTS, 0 }; +constexpr inline uint8_t CMD_SPP_GP_REPORTS = 0xAD; +constexpr inline uint8_t turnOnReports[2] = { CMD_SPP_GP_REPORTS, 1 }; +constexpr inline uint8_t turnOffReports[2] = { CMD_SPP_GP_REPORTS, 0 }; -static const uint8_t CMD_SET_LED = 0xFF; -static const uint8_t turnOnLED[2] = { CMD_SET_LED, 1 }; +constexpr inline uint8_t CMD_SET_LED = 0xFF; +constexpr inline uint8_t turnOnLED[2] = { CMD_SET_LED, 1 }; -static const uint8_t CMD_FORCE_LED_CTRL = 0x6D; -static const uint8_t turnOnLEDControl[2] = { CMD_FORCE_LED_CTRL, 1 }; +constexpr inline uint8_t CMD_FORCE_LED_CTRL = 0x6D; +constexpr inline uint8_t turnOnLEDControl[2] = { CMD_FORCE_LED_CTRL, 1 }; -static const uint8_t CMD_SET_LED_MODE = 0xE4; -static const uint8_t LED_PULSE_DOUBLE = 0; -static const uint8_t setLEDPulseDouble[2] = { CMD_SET_LED_MODE, LED_PULSE_DOUBLE }; -static const uint8_t LED_PULSE_INVERSE = 2; -static const uint8_t setLEDPulseInverse[2] = { CMD_SET_LED_MODE, LED_PULSE_INVERSE }; -/*const uint8_t LED_NO_PULSE = 3; -const uint8_t setLEDNoPulse[2] = { CMD_SET_LED_MODE, LED_NO_PULSE };*/ -static const uint8_t LED_PULSE_DQUICK = 5; -static const uint8_t setLEDPulseDQuick[2] = { CMD_SET_LED_MODE, LED_PULSE_DQUICK }; +constexpr inline uint8_t CMD_SET_LED_MODE = 0xE4; +constexpr inline uint8_t LED_PULSE_DOUBLE = 0; +constexpr inline uint8_t setLEDPulseDouble[2] = { CMD_SET_LED_MODE, LED_PULSE_DOUBLE }; +constexpr inline uint8_t LED_PULSE_INVERSE = 2; +constexpr inline uint8_t setLEDPulseInverse[2] = { CMD_SET_LED_MODE, LED_PULSE_INVERSE }; +/*constexpr inline uint8_t LED_NO_PULSE = 3; +constexpr inline uint8_t setLEDNoPulse[2] = { CMD_SET_LED_MODE, LED_NO_PULSE };*/ +constexpr inline uint8_t LED_PULSE_DQUICK = 5; +constexpr inline uint8_t setLEDPulseDQuick[2] = { CMD_SET_LED_MODE, LED_PULSE_DQUICK }; -static const uint8_t CMD_POWER_OFF = 0x94; -static const uint8_t PWR_OFF_CHK_BYTE1 = 0x27; -static const uint8_t PWR_OFF_CHK_BYTE2 = 0x6A; -static const uint8_t PWR_OFF_CHK_BYTE3 = 0xFE; -//static const char shutdown[] = { CMD_POWER_OFF, PWR_OFF_CHK_BYTE1, PWR_OFF_CHK_BYTE2, PWR_OFF_CHK_BYTE3 }; +constexpr inline uint8_t CMD_POWER_OFF = 0x94; +constexpr inline uint8_t PWR_OFF_CHK_BYTE1 = 0x27; +constexpr inline uint8_t PWR_OFF_CHK_BYTE2 = 0x6A; +constexpr inline uint8_t PWR_OFF_CHK_BYTE3 = 0xFE; +//constexpr inline char shutdown[] = { CMD_POWER_OFF, PWR_OFF_CHK_BYTE1, PWR_OFF_CHK_BYTE2, PWR_OFF_CHK_BYTE3 }; -static const uint8_t RESP_OKAY = 0x80; +constexpr inline uint8_t RESP_OKAY = 0x80; -static const char *icpButtonName(Key b) +constexpr const char* icpButtonName(Key b) { switch(b) { diff --git a/imagine/src/bluetooth/PS3Controller.cc b/imagine/src/bluetooth/PS3Controller.cc index e9872a8f0..263565ab0 100644 --- a/imagine/src/bluetooth/PS3Controller.cc +++ b/imagine/src/bluetooth/PS3Controller.cc @@ -121,7 +121,7 @@ const char *PS3Controller::keyName(Input::Key k) const return ps3ButtonName(k); } -bool PS3Controller::open(BluetoothAdapter &adapter, Input::Device &dev) +bool PS3Controller::open(BluetoothAdapter&, Input::Device&) { return false; } @@ -193,7 +193,7 @@ void PS3Controller::close() ctlSock.close(); } -bool PS3Controller::dataHandler(Input::Device &dev, const char *packetPtr, size_t size) +bool PS3Controller::dataHandler(Input::Device& dev, const char* packetPtr, size_t) { auto packet = (const uint8_t*)packetPtr; /*logMsg("data with size %d", (int)size); diff --git a/imagine/src/bluetooth/Wiimote.cc b/imagine/src/bluetooth/Wiimote.cc index 40bd19ae3..2eac25e6b 100644 --- a/imagine/src/bluetooth/Wiimote.cc +++ b/imagine/src/bluetooth/Wiimote.cc @@ -302,7 +302,7 @@ void Wiimote::sendDataModeByExtension() } } -bool Wiimote::dataHandler(Input::Device &dev, const char *packetPtr, size_t size) +bool Wiimote::dataHandler(Input::Device& dev, const char* packetPtr, size_t) { using namespace IG::Input; auto packet = (const uint8_t*)packetPtr; @@ -395,10 +395,10 @@ bool Wiimote::dataHandler(Input::Device &dev, const char *packetPtr, size_t size std::ranges::fill(prevExtData, 0xFF); static constexpr float axisClassicLScaler = 1./31.; static constexpr float axisClassicRScaler = 1./15.; - axis[0] = {Map::WII_CC, Input::AxisId::X, axisClassicLScaler}; - axis[1] = {Map::WII_CC, Input::AxisId::Y, axisClassicLScaler}; - axis[2] = {Map::WII_CC, Input::AxisId::Z, axisClassicRScaler}; - axis[3] = {Map::WII_CC, Input::AxisId::RZ, axisClassicRScaler}; + axis[0] = {Input::AxisId::X, axisClassicLScaler}; + axis[1] = {Input::AxisId::Y, axisClassicLScaler}; + axis[2] = {Input::AxisId::Z, axisClassicRScaler}; + axis[3] = {Input::AxisId::RZ, axisClassicRScaler}; assert(!extDevicePtr); extDevicePtr = &ctx.application().addInputDevice(ctx, std::make_unique(std::in_place_type, Input::Map::WII_CC, DeviceTypeFlags{.gamepad = true}, "Wii Classic Controller"), true); @@ -410,8 +410,8 @@ bool Wiimote::dataHandler(Input::Device &dev, const char *packetPtr, size_t size sendDataModeByExtension(); std::ranges::fill(prevExtData, 0xFF); static constexpr float axisNunchukScaler = 1./127.; - axis[0] = {Input::Map::WIIMOTE, Input::AxisId::X, axisNunchukScaler}; - axis[1] = {Input::Map::WIIMOTE, Input::AxisId::Y, axisNunchukScaler}; + axis[0] = {Input::AxisId::X, axisNunchukScaler}; + axis[1] = {Input::AxisId::Y, axisNunchukScaler}; } else if(memcmp(&packet[8], wiiUProType, sizeof(ccType)) == 0) { @@ -420,10 +420,10 @@ bool Wiimote::dataHandler(Input::Device &dev, const char *packetPtr, size_t size sendDataModeByExtension(); std::ranges::fill(prevExtData, 0xFF); static constexpr float axisClassicProScaler = 1./2047.; - axis[0] = {Input::Map::WII_CC, Input::AxisId::X, axisClassicProScaler}; - axis[1] = {Input::Map::WII_CC, Input::AxisId::Y, axisClassicProScaler}; - axis[2] = {Input::Map::WII_CC, Input::AxisId::Z, axisClassicProScaler}; - axis[3] = {Input::Map::WII_CC, Input::AxisId::RZ, axisClassicProScaler}; + axis[0] = {Input::AxisId::X, axisClassicProScaler}; + axis[1] = {Input::AxisId::Y, axisClassicProScaler}; + axis[2] = {Input::AxisId::Z, axisClassicProScaler}; + axis[3] = {Input::AxisId::RZ, axisClassicProScaler}; map_ = Input::Map::WII_CC; name_ = "Wii U Pro Controller"; } diff --git a/imagine/src/bluetooth/Zeemote.cc b/imagine/src/bluetooth/Zeemote.cc index 8aed3e847..9cad3d14c 100644 --- a/imagine/src/bluetooth/Zeemote.cc +++ b/imagine/src/bluetooth/Zeemote.cc @@ -91,7 +91,7 @@ void Zeemote::close() sock.close(); } -uint32_t Zeemote::statusHandler(Input::Device &dev, BluetoothSocket &sock, BluetoothSocketState status) +uint32_t Zeemote::statusHandler(Input::Device& dev, BluetoothSocket&, BluetoothSocketState status) { if(status == BluetoothSocketState::Opened) { diff --git a/imagine/src/data-type/image/Android.cc b/imagine/src/data-type/image/Android.cc index 88977a936..a9be19d73 100755 --- a/imagine/src/data-type/image/Android.cc +++ b/imagine/src/data-type/image/Android.cc @@ -48,7 +48,7 @@ static PixmapImage makePixmapImage(JNIEnv *env, jobject bitmap, JNI::InstMethod< return PixmapImage{{env, bitmap, recycle}, pix}; } -PixmapImage PixmapReader::load(const char *name, PixmapReaderParams params) const +PixmapImage PixmapReader::load(const char *name, PixmapReaderParams) const { auto env = app().thisThreadJniEnv(); auto nameJStr = env->NewStringUTF(name); diff --git a/imagine/src/data-type/image/LibPNG.cc b/imagine/src/data-type/image/LibPNG.cc index c5047afa6..ed67eb399 100755 --- a/imagine/src/data-type/image/LibPNG.cc +++ b/imagine/src/data-type/image/LibPNG.cc @@ -105,13 +105,13 @@ PixelFormat PngImage::pixelFormat() return PixelFmtRGBA8888; } -static png_voidp png_memAlloc(png_structp png_ptr, png_size_t size) +static png_voidp png_memAlloc(png_structp, png_size_t size) { //log_mPrintf(LOG_MSG, "about to allocate %d bytes", size); return new uint8_t[size]; } -static void png_memFree(png_structp png_ptr, png_voidp ptr) +static void png_memFree(png_structp, png_voidp ptr) { delete[] (uint8_t*)ptr; } @@ -195,7 +195,7 @@ bool PngImage::hasAlphaChannel() ( png_get_valid(png, info, PNG_INFO_tRNS) ) ) ? 1 : 0; } -void PngImage::setTransforms(PixelFormat outFormat, png_infop transInfo) +void PngImage::setTransforms(PixelFormat outFormat) { int addingAlphaChannel = 0; @@ -290,7 +290,7 @@ std::errc PngImage::readImage(MutablePixmapView dest) png_infopp pngInfopAddr = &transInfo; png_destroy_info_struct(png, pngInfopAddr); }); - setTransforms(dest.format(), transInfo); + setTransforms(dest.format()); //log_mPrintf(LOG_MSG,"after transforms, rowbytes = %u", (uint32_t)png_get_rowbytes(data->png, data->info)); @@ -431,7 +431,7 @@ bool PixmapWriter::writeToFile(PixmapView pix, const char *path) const //png_error(pngPtr, "Write Error"); } }, - [](png_structp pngPtr) + [](png_structp) { logMsg("called png_ioFlush"); }); @@ -447,7 +447,7 @@ bool PixmapWriter::writeToFile(PixmapView pix, const char *path) const int rowBytes = png_get_rowbytes(pngPtr, infoPtr); assert(rowBytes == tempPix.pitchBytes()); auto rowData = (png_const_bytep)tempPix.data(); - for(auto i : iotaCount(tempPix.h())) + for([[maybe_unused]] auto i : iotaCount(tempPix.h())) { png_write_row(pngPtr, rowData); rowData += tempPix.pitchBytes(); diff --git a/imagine/src/font/AndroidFont.cc b/imagine/src/font/AndroidFont.cc index 9a2ff3749..fd443f570 100755 --- a/imagine/src/font/AndroidFont.cc +++ b/imagine/src/font/AndroidFont.cc @@ -25,7 +25,7 @@ namespace IG { -static const char *androidBitmapResultToStr(int result) +constexpr auto androidBitmapResultToStr(int result) { switch(result) { @@ -53,7 +53,7 @@ AndroidFontManager::AndroidFontManager(ApplicationContext ctx): { "charMetricsCallback", "(JIIIII)V", (void*)(void (*)(JNIEnv*, jobject, jlong, jint, jint, jint, jint, jint)) - ([](JNIEnv* env, jobject thiz, jlong metricsAddr, + ([](JNIEnv*, jobject, jlong metricsAddr, jint xSize, jint ySize, jint xOff, jint yOff, jint xAdv) { auto &metrics = *((GlyphMetrics*)metricsAddr); @@ -114,7 +114,7 @@ Font::Glyph Font::glyph(int idx, FontSize &size) if(!bitmap) return {}; void *data{}; - auto res = AndroidBitmap_lockPixels(env, bitmap, &data); + [[maybe_unused]] auto res = AndroidBitmap_lockPixels(env, bitmap, &data); auto pix = makePixmapView(env, bitmap, data, PixelFmtA8); //logMsg("AndroidBitmap_lockPixels returned %s", androidBitmapResultToStr(res)); assert(res == ANDROID_BITMAP_RESULT_SUCCESS); diff --git a/imagine/src/font/FreetypeFont.cc b/imagine/src/font/FreetypeFont.cc index 1f0c6a023..b5ab6276b 100755 --- a/imagine/src/font/FreetypeFont.cc +++ b/imagine/src/font/FreetypeFont.cc @@ -370,7 +370,6 @@ FreetypeFont::GlyphRenderData FreetypeFont::makeGlyphRenderData(int idx, Freetyp logErr("error activating size object"); return {}; } - std::errc ec; auto data = makeGlyphRenderDataWithFace(library, font.face, idx, keepPixData); if(!data) { diff --git a/imagine/src/fs/FS.cc b/imagine/src/fs/FS.cc index 8447064a1..24e1f8198 100755 --- a/imagine/src/fs/FS.cc +++ b/imagine/src/fs/FS.cc @@ -101,7 +101,7 @@ std::pair uriPathSegment(std::string_view uri, std::st size_t directoryItems(CStringView path) { size_t items = 0; - forEachInDirectory(path, [&](auto &entry){ items++; return true; }); + forEachInDirectory(path, [&](auto&){ items++; return true; }); return items; } diff --git a/imagine/src/gfx/common/GfxText.cc b/imagine/src/gfx/common/GfxText.cc index f01cd0515..007b6dc30 100644 --- a/imagine/src/gfx/common/GfxText.cc +++ b/imagine/src/gfx/common/GfxText.cc @@ -187,7 +187,7 @@ bool Text::compile(TextLayoutConfig conf) } std::unreachable(); }; - for(auto i : iotaCount(lines)) + for([[maybe_unused]] auto i : iotaCount(lines)) { auto [xLineSize, charsToDraw] = LineSpan::decode({spansPtr, LineSpan::encodedChar16Size}); spansPtr += LineSpan::encodedChar16Size; @@ -252,7 +252,7 @@ void Text::draw(RendererCommands &cmds, WPt pos, _2DOrigin o) const auto s = textStr.data(); auto spansPtr = &textStr[sizeBeforeLineSpans]; int spriteOffset = 0; - for(auto i : iotaCount(lines)) + for([[maybe_unused]] auto i : iotaCount(lines)) { auto [xLineSize, charsToDraw] = LineSpan::decode({spansPtr, LineSpan::encodedChar16Size}); spansPtr += LineSpan::encodedChar16Size; diff --git a/imagine/src/gfx/opengl/Buffer.cc b/imagine/src/gfx/opengl/Buffer.cc index ab55b2813..6002b0d0f 100644 --- a/imagine/src/gfx/opengl/Buffer.cc +++ b/imagine/src/gfx/opengl/Buffer.cc @@ -107,7 +107,7 @@ void GLBuffer::reset(ByteBufferConfig config) } template -MappedByteBuffer GLBuffer::map(ssize_t offset, size_t size) +MappedByteBuffer GLBuffer::map(ssize_t offset, size_t size, BufferMapMode mode) { assumeExpr(taskPtr()); if(!size) @@ -115,7 +115,9 @@ MappedByteBuffer GLBuffer::map(ssize_t offset, size_t size) assert(offset + size <= sizeBytes()); if(!size) return {}; - if(hasBufferMap(task().renderer())) + if(mode == BufferMapMode::unset) + mode = BufferMapMode::direct; + if(mode == BufferMapMode::direct && hasBufferMap(task().renderer())) { void *ptr; task().runSync([this, &ptr, offset, size]() @@ -126,7 +128,7 @@ MappedByteBuffer GLBuffer::map(ssize_t offset, size_t size) offset, size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT); //log.debug("mapped offset:{} size:{} of buffer:0x{:X} to {}", offset, size, name(), ptr); }); - return {{static_cast(ptr), size}, [this](const uint8_t *ptr, size_t) + return {{static_cast(ptr), size}, [this](const uint8_t*, size_t) { task().run([name = name(), &support = task().renderer().support]() { @@ -179,7 +181,7 @@ void destroyGLBufferRef(RendererTask &rTask, GLBufferRef name) template class GLBuffer; template class GLBuffer; -void GLVertexArray::initArray(GLBufferRef vbo, GLBufferRef ibo, int stride, VertexLayoutFlags enabledLayout, VertexLayoutDesc layoutDesc) +void GLVertexArray::initArray(GLBufferRef vbo, GLBufferRef ibo, int stride, VertexLayoutDesc layoutDesc) { assumeExpr(taskPtr()); if(!task().renderer().support.hasVAOFuncs()) diff --git a/imagine/src/gfx/opengl/DrawContextSupport.cc b/imagine/src/gfx/opengl/DrawContextSupport.cc index d9178f15b..f179054ae 100644 --- a/imagine/src/gfx/opengl/DrawContextSupport.cc +++ b/imagine/src/gfx/opengl/DrawContextSupport.cc @@ -102,7 +102,7 @@ bool DrawContextSupport::hasServerWaitSync() const */ } -GLsync DrawContextSupport::fenceSync(GLDisplay dpy) +GLsync DrawContextSupport::fenceSync([[maybe_unused]] GLDisplay dpy) { #ifdef CONFIG_BASE_GL_PLATFORM_EGL return static_cast(eglCreateSync(dpy, EGL_SYNC_FENCE, nullptr)); @@ -111,7 +111,7 @@ GLsync DrawContextSupport::fenceSync(GLDisplay dpy) #endif } -void DrawContextSupport::deleteSync(GLDisplay dpy, GLsync sync) +void DrawContextSupport::deleteSync([[maybe_unused]] GLDisplay dpy, GLsync sync) { #ifdef CONFIG_BASE_GL_PLATFORM_EGL if(bool success = eglDestroySync(dpy, sync); @@ -124,7 +124,7 @@ void DrawContextSupport::deleteSync(GLDisplay dpy, GLsync sync) #endif } -GLenum DrawContextSupport::clientWaitSync(GLDisplay dpy, GLsync sync, GLbitfield flags, GLuint64 timeout) +GLenum DrawContextSupport::clientWaitSync([[maybe_unused]] GLDisplay dpy, GLsync sync, GLbitfield flags, GLuint64 timeout) { #ifdef CONFIG_BASE_GL_PLATFORM_EGL if(auto status = eglClientWaitSync(dpy, sync, flags, timeout); @@ -143,7 +143,7 @@ GLenum DrawContextSupport::clientWaitSync(GLDisplay dpy, GLsync sync, GLbitfield #endif } -void DrawContextSupport::waitSync(GLDisplay dpy, GLsync sync) +void DrawContextSupport::waitSync(GLDisplay, GLsync) { bug_unreachable("waitSync() not currently used"); /*#ifdef CONFIG_BASE_GL_PLATFORM_EGL @@ -248,10 +248,12 @@ void DrawContextSupport::setGLDebugOutput(bool on) glDebugMessageCallback = (typeof(glDebugMessageCallback))GLManager::procAddress(glDebugMessageCallbackName); } glDebugMessageCallback( - GL_APIENTRY [](GLenum source, GLenum type, GLuint id, - GLenum severity, GLsizei length, const GLchar *message, const void *userParam) + GL_APIENTRY []([[maybe_unused]] GLenum source, GLenum type, [[maybe_unused]] GLuint id, + GLenum severity, [[maybe_unused]] GLsizei length, const GLchar* message, [[maybe_unused]] const void* userParam) { - if(Config::envIsAndroid && std::string_view{message} == "FreeAllocationOnTimestamp - WaitForTimestamp") + std::string_view msgString{message, size_t(length)}; + if(Config::envIsAndroid && (msgString == "FreeAllocationOnTimestamp - WaitForTimestamp" + || msgString.contains("Submission has been flushed"))) { return; } diff --git a/imagine/src/gfx/opengl/GLTask.cc b/imagine/src/gfx/opengl/GLTask.cc index ee39637bc..85fb3b081 100644 --- a/imagine/src/gfx/opengl/GLTask.cc +++ b/imagine/src/gfx/opengl/GLTask.cc @@ -74,7 +74,7 @@ bool GLTask::makeGLContext(GLTaskConfig config) if(backgrounded) { runSync( - [&glContext = context](TaskContext ctx) + [&glContext = context](TaskContext) { // unset the drawable and finish all commands before entering background if(GLManager::hasCurrentDrawable()) diff --git a/imagine/src/gfx/opengl/Program.cc b/imagine/src/gfx/opengl/Program.cc index 69b299549..cd27ef7a7 100644 --- a/imagine/src/gfx/opengl/Program.cc +++ b/imagine/src/gfx/opengl/Program.cc @@ -316,18 +316,18 @@ static GLuint makeCompatGLShader(RendererTask &rTask, std::span compatSrcs; std::string_view version = Config::Gfx::OPENGL_ES ? "#version 300 es\n"sv : "#version 330\n"sv; - std::string_view legacyVertDefs // for GL ES 2.0 + constexpr std::string_view legacyVertDefs // for GL ES 2.0 { "#define in attribute\n" "#define out varying\n" }; - std::string_view legacyFragDefs // for GL ES 2.0 + constexpr std::string_view legacyFragDefs // for GL ES 2.0 { "#define in varying\n" "#define texture texture2D\n" "#define FRAGCOLOR gl_FragColor\n" }; - std::string_view fragDefs + constexpr std::string_view fragDefs { "out mediump vec4 FRAGCOLOR;\n" }; diff --git a/imagine/src/gfx/opengl/Renderer.cc b/imagine/src/gfx/opengl/Renderer.cc index 6051bb76f..4fdb6bfd2 100755 --- a/imagine/src/gfx/opengl/Renderer.cc +++ b/imagine/src/gfx/opengl/Renderer.cc @@ -54,7 +54,17 @@ Renderer::~Renderer() GLRenderer::GLRenderer(ApplicationContext ctx): glManager{ctx.nativeDisplayConnection(), glAPI}, mainTask{ctx, "Main GL Context Messages", *static_cast(this)}, - releaseShaderCompilerEvent{"GLRenderer::releaseShaderCompilerEvent"} + releaseShaderCompilerEvent + { + {.debugLabel = "GLRenderer::releaseShaderCompilerEvent"}, + [&task = mainTask, ctx] + { + if(!ctx.isRunning()) + return; + logMsg("automatically releasing shader compiler"); + task.releaseShaderCompiler(); + } + } { if(!glManager) { @@ -316,7 +326,7 @@ int GLRenderer::toSwapInterval(const Window &win, PresentMode mode) const std::unreachable(); } -PresentMode Renderer::evalPresentMode(const Window &win, PresentMode mode) const +PresentMode Renderer::evalPresentMode(const Window&, PresentMode mode) const { if(mode == PresentMode::Auto) return PresentMode::FIFO; @@ -491,7 +501,7 @@ BasicEffect &Renderer::basicEffect() void Renderer::animateWindowRotation(Window &win, float srcAngle, float destAngle) { winData(win).projAngleM = {srcAngle, destAngle, {}, SteadyClock::now(), Milliseconds{165}}; - win.addOnFrame([this, &win](FrameParams params) + win.addOnFrame([&win](FrameParams params) { win.signalSurfaceChanged({.contentRectResized = true}); bool didUpdate = winData(win).projAngleM.update(params.timestamp); @@ -650,7 +660,7 @@ void GLRenderer::setupNonPow2MipmapRepeatTextures() support.textureSizeSupport.nonPow2CanRepeat = true; } -void GLRenderer::setupImmutableTexStorage(bool extSuffix) +void GLRenderer::setupImmutableTexStorage([[maybe_unused]] bool extSuffix) { if(support.hasImmutableTexStorage) return; @@ -738,7 +748,7 @@ void GLRenderer::setupMemoryBarrier() #endif*/ } -void GLRenderer::setupVAOFuncs(bool oes) +void GLRenderer::setupVAOFuncs([[maybe_unused]] bool oes) { #ifdef CONFIG_GFX_OPENGL_ES if(support.glBindVertexArray) @@ -782,7 +792,7 @@ void GLRenderer::setupAppleFenceSync() #endif } -void GLRenderer::setupEglFenceSync(std::string_view eglExtenstionStr) +void GLRenderer::setupEglFenceSync([[maybe_unused]] std::string_view eglExtenstionStr) { if(Config::MACHINE_IS_PANDORA) // TODO: driver waits for full timeout even if commands complete, return; // possibly broken glFlush() behavior? @@ -1039,15 +1049,9 @@ void Renderer::setWindowValidOrientations(Window &win, Orientations validO) } } -void GLRenderer::addEventHandlers(ApplicationContext ctx, RendererTask &task) +void GLRenderer::addEventHandlers(ApplicationContext, RendererTask &task) { - releaseShaderCompilerEvent.attach([&task, ctx]() - { - if(!ctx.isRunning()) - return; - logMsg("automatically releasing shader compiler"); - task.releaseShaderCompiler(); - }); + releaseShaderCompilerEvent.attach(); if constexpr(Config::envIsIOS) task.setIOSDrawableDelegates(); } diff --git a/imagine/src/gfx/opengl/RendererCommands.cc b/imagine/src/gfx/opengl/RendererCommands.cc index b2f9b8b74..a3096e465 100644 --- a/imagine/src/gfx/opengl/RendererCommands.cc +++ b/imagine/src/gfx/opengl/RendererCommands.cc @@ -295,11 +295,6 @@ Color RendererCommands::color() const return vColor; } -void RendererCommands::setImgMode(EnvMode mode) -{ - // TODO -} - void RendererCommands::setDither(bool on) { rTask->verifyCurrentContext(); diff --git a/imagine/src/gfx/opengl/RendererTask.cc b/imagine/src/gfx/opengl/RendererTask.cc index f5ffa9e47..b763b8412 100644 --- a/imagine/src/gfx/opengl/RendererTask.cc +++ b/imagine/src/gfx/opengl/RendererTask.cc @@ -165,7 +165,7 @@ void GLRendererTask::destroyDrawable(GLDrawable &drawable) if(!drawable) return; GLTask::runSync( - [this, drawable = (Drawable)drawable](TaskContext ctx) + [this, drawable = (Drawable)drawable](TaskContext) { // unset the drawable if it's currently in use if(GLManager::hasCurrentDrawable(drawable)) diff --git a/imagine/src/gfx/opengl/Texture.cc b/imagine/src/gfx/opengl/Texture.cc index 75270c76e..bf07226b5 100644 --- a/imagine/src/gfx/opengl/Texture.cc +++ b/imagine/src/gfx/opengl/Texture.cc @@ -346,7 +346,7 @@ bool Texture::setFormat(PixmapDesc desc, int levels, ColorSpace colorSpace, Text r.support.glTexStorage2D(GL_TEXTURE_2D, levels, internalFormat, desc.w(), desc.h()); }, "glTexStorage2D()"); setSwizzleForFormatInGL(r, desc.format, texName); - setSamplerParamsInGL(r, samplerParams); + setSamplerParamsInGL(samplerParams); }); } else @@ -383,7 +383,7 @@ bool Texture::setFormat(PixmapDesc desc, int levels, ColorSpace colorSpace, Text } setSwizzleForFormatInGL(r, desc.format, texName); if(remakeTexName) - setSamplerParamsInGL(r, samplerParams); + setSamplerParamsInGL(samplerParams); }, remakeTexName ? MessageReplyMode::wait : MessageReplyMode::none); } updateFormatInfo(desc, levels); @@ -562,7 +562,7 @@ WSize Texture::size(int level) const { assert(levels_); int w = pixDesc.w(), h = pixDesc.h(); - for(auto i : iotaCount(level)) + for([[maybe_unused]] auto i : iotaCount(level)) { w = std::max(1, (w / 2)); h = std::max(1, (h / 2)); @@ -580,10 +580,10 @@ void Texture::setSampler(TextureSamplerConfig samplerConf) if(!texName()) [[unlikely]] return; task().run( - [&r = std::as_const(renderer()), target = target(), texName = texName(), params = asSamplerParams(samplerConf)]() + [target = target(), texName = texName(), params = asSamplerParams(samplerConf)]() { glBindTexture(target, texName); - setSamplerParamsInGL(r, params, target); + setSamplerParamsInGL(params, target); }); } @@ -675,7 +675,7 @@ static void setTexParameteri(GLenum target, GLenum pname, GLint param) }, "glTexParameteri()"); } -void GLTexture::setSamplerParamsInGL(const Renderer &r, SamplerParams params, GLenum target) +void GLTexture::setSamplerParamsInGL(SamplerParams params, GLenum target) { assert(params.magFilter); setTexParameteri(target, GL_TEXTURE_MAG_FILTER, params.magFilter); @@ -718,7 +718,7 @@ void GLTexture::initWithEGLImage(EGLImageKHR eglImg, PixmapDesc desc, SamplerPar } ctx.notifySemaphore(); setSwizzleForFormatInGL(r, formatID, texName); - setSamplerParamsInGL(r, samplerParams); + setSamplerParamsInGL(samplerParams); }); } else @@ -747,7 +747,7 @@ void GLTexture::initWithEGLImage(EGLImageKHR eglImg, PixmapDesc desc, SamplerPar ctx.notifySemaphore(); setSwizzleForFormatInGL(r, formatID, texName); if(madeTexName) - setSamplerParamsInGL(r, samplerParams); + setSamplerParamsInGL(samplerParams); }); } updateFormatInfo(desc, 1); @@ -756,7 +756,7 @@ void GLTexture::initWithEGLImage(EGLImageKHR eglImg, PixmapDesc desc, SamplerPar void GLTexture::updateWithEGLImage(EGLImageKHR eglImg) { task().GLTask::run( - [=, texName = texName()](GLTask::TaskContext ctx) + [=, texName = texName()](GLTask::TaskContext) { glBindTexture(GL_TEXTURE_2D, texName); assumeExpr(eglImg); diff --git a/imagine/src/gfx/opengl/TextureSampler.cc b/imagine/src/gfx/opengl/TextureSampler.cc index dcbb00ec1..238524046 100644 --- a/imagine/src/gfx/opengl/TextureSampler.cc +++ b/imagine/src/gfx/opengl/TextureSampler.cc @@ -26,7 +26,7 @@ namespace IG::Gfx constexpr SystemLogger log{"GLTextureSampler"}; -static void setSamplerParameteriImpl(const Renderer &r, GLuint sampler, GLenum pname, GLint param, const char *pnameStr) +static void setSamplerParameteri(const Renderer &r, GLuint sampler, GLenum pname, GLint param) { runGLCheckedVerbose( [&]() @@ -35,8 +35,6 @@ static void setSamplerParameteriImpl(const Renderer &r, GLuint sampler, GLenum p }, "glSamplerParameteri()"); } -#define setSamplerParameteri(r, sampler, pname, param) setSamplerParameteriImpl(r, sampler, pname, param, #pname); - // make sure sampler-related enums can fit into a 16-bit int static_assert(GL_LINEAR < std::numeric_limits::max()); static_assert(GL_NEAREST < std::numeric_limits::max()); @@ -102,7 +100,7 @@ GLTextureSampler::GLTextureSampler(RendererTask &rTask, TextureSamplerConfig con auto xWrapMode = makeWrapMode(config.xWrapMode); auto yWrapMode = makeWrapMode(config.yWrapMode); rTask.runSync( - [=, this, &rTask, &r = std::as_const(r)](GLTask::TaskContext ctx) + [=, this, &r = std::as_const(r)](GLTask::TaskContext ctx) { GLuint name; r.support.glGenSamplers(1, &name); diff --git a/imagine/src/gfx/opengl/android/SurfaceTextureStorage.cc b/imagine/src/gfx/opengl/android/SurfaceTextureStorage.cc index 9662171e1..1936b5b20 100644 --- a/imagine/src/gfx/opengl/android/SurfaceTextureStorage.cc +++ b/imagine/src/gfx/opengl/android/SurfaceTextureStorage.cc @@ -51,7 +51,7 @@ SurfaceTextureStorage::SurfaceTextureStorage(RendererTask &r, TextureConfig conf updateSurfaceTextureImage(env, surfaceTex); // set the initial display & context this->surfaceTex = env->NewGlobalRef(surfaceTex); ctx.notifySemaphore(); - setSamplerParamsInGL(renderer(), samplerParams, GL_TEXTURE_EXTERNAL_OES); + setSamplerParamsInGL(samplerParams, GL_TEXTURE_EXTERNAL_OES); }); if(!surfaceTex) [[unlikely]] { @@ -120,7 +120,7 @@ void SurfaceTextureStorage::deinit() } } -bool SurfaceTextureStorage::setFormat(IG::PixmapDesc desc, ColorSpace colorSpace, TextureSamplerConfig) +bool SurfaceTextureStorage::setFormat(IG::PixmapDesc desc, ColorSpace, TextureSamplerConfig) { logMsg("setting size:%dx%d format:%s", desc.w(), desc.h(), desc.format.name()); int winFormat = toAHardwareBufferFormat(desc.format); diff --git a/imagine/src/gfx/opengl/utils.hh b/imagine/src/gfx/opengl/utils.hh index 115806114..1624b73d6 100644 --- a/imagine/src/gfx/opengl/utils.hh +++ b/imagine/src/gfx/opengl/utils.hh @@ -61,7 +61,7 @@ extern bool checkGLErrors; extern bool checkGLErrorsVerbose; } -static const char *glErrorToString(GLenum err) +constexpr const char *glErrorToString(GLenum err) { switch(err) { @@ -74,7 +74,7 @@ static const char *glErrorToString(GLenum err) } } -static const char *glDataTypeToString(int format) +constexpr const char *glDataTypeToString(int format) { switch(format) { @@ -92,7 +92,7 @@ static const char *glDataTypeToString(int format) } } -static const char *glImageFormatToString(int format) +constexpr const char *glImageFormatToString(int format) { switch(format) { @@ -186,7 +186,7 @@ static bool runGLCheckedVerbose(FUNC func, const char *label = nullptr) return runGLChecked(func, label); } -static GLuint makeGLTextureName(GLuint oldTex) +inline GLuint makeGLTextureName(GLuint oldTex) { if(oldTex) { diff --git a/imagine/src/gui/AlertView.cc b/imagine/src/gui/AlertView.cc index 95d7e7d54..90ea46847 100644 --- a/imagine/src/gui/AlertView.cc +++ b/imagine/src/gui/AlertView.cc @@ -13,8 +13,6 @@ You should have received a copy of the GNU General Public License along with Imagine. If not, see */ -#define LOGTAG "BaseAlertView" - #include #include #include @@ -27,6 +25,8 @@ namespace IG { +constexpr SystemLogger log{"AlertView"}; + void BaseAlertView::init() { menu.setAlign(C2DO); @@ -36,7 +36,7 @@ void BaseAlertView::init() bool shouldDismiss = item.inputEvent(e, {.parentPtr = this}); if(shouldDismiss) { - logMsg("dismissing"); + log.info("dismissing via item #{}", i); dismiss(); } }); diff --git a/imagine/src/gui/FSPicker.cc b/imagine/src/gui/FSPicker.cc index 3202ce937..9db143fa9 100644 --- a/imagine/src/gui/FSPicker.cc +++ b/imagine/src/gui/FSPicker.cc @@ -39,6 +39,7 @@ FSPicker::FSPicker(ViewAttachParams attach, Gfx::TextureSpan backRes, Gfx::Textu filter{filter}, controller{attach}, msgText{attach.rendererTask, face_ ? face_ : &defaultFace()}, + dirListEvent{{.debugLabel = "FSPicker::dirListEvent", .eventLoop = EventLoop::forThread()}, {}}, mode_{mode} { auto nav = makeView @@ -351,7 +352,7 @@ void FSPicker::pushFileLocationsView(const Input::Event &e) if(appContext().hasSystemPathPicker()) { view->appendItem("Browse For Folder", - [this](View &view, const Input::Event &e) + [this](View& view, const Input::Event&) { if(!appContext().showSystemPathPicker()) { @@ -363,7 +364,7 @@ void FSPicker::pushFileLocationsView(const Input::Event &e) if(mode_ != Mode::DIR && appContext().hasSystemDocumentPicker()) { view->appendItem("Browse For File", - [this](View &view, const Input::Event &e) + [this](View& view, const Input::Event&) { if(!appContext().showSystemDocumentPicker()) { @@ -375,7 +376,7 @@ void FSPicker::pushFileLocationsView(const Input::Event &e) for(auto &loc : view->locations()) { view->appendItem(loc.description, - [this, &loc](View &view, const Input::Event &e) + [this, &loc](View& view, const Input::Event& e) { auto ctx = appContext(); if(ctx.usesPermission(Permission::WRITE_EXT_STORAGE)) @@ -390,14 +391,14 @@ void FSPicker::pushFileLocationsView(const Input::Event &e) if(Config::envIsLinux) { view->appendItem("Root Filesystem", - [this](View &view, const Input::Event &e) + [this](View& view, const Input::Event& e) { changeDirByInput("/", {}, e, DepthMode::reset); view.dismiss(); }); } view->appendItem("Custom Path", - [this](const Input::Event &e) + [this](const Input::Event& e) { auto textInputView = makeView( "Input a directory path", root.path, Gfx::TextureSpan{}, diff --git a/imagine/src/gui/MenuItem.cc b/imagine/src/gui/MenuItem.cc index 5cc15f030..87d5b3c2f 100644 --- a/imagine/src/gui/MenuItem.cc +++ b/imagine/src/gui/MenuItem.cc @@ -32,8 +32,6 @@ void MenuItem::prepareDraw() void MenuItem::draw(Gfx::RendererCommands&__restrict__ cmds, MenuItemDrawAttrs attrs) const { - auto [xPos, yPos] = attrs.rect.pos(LT2DO); - auto xSize = attrs.rect.size().x; if(!active()) { // half-bright color @@ -41,12 +39,10 @@ void MenuItem::draw(Gfx::RendererCommands&__restrict__ cmds, MenuItemDrawAttrs a attrs.color.g /= 2.f; attrs.color.b /= 2.f; } - if(attrs.align.isXCentered()) - xPos += xSize / 2; - else - xPos += attrs.xIndent; + if(!attrs.align.isXCentered()) + attrs.rect += WPt{attrs.xIndent, 0}; cmds.basicEffect().enableAlphaTexture(cmds); - t.draw(cmds, {xPos, yPos}, attrs.align, attrs.color); + t.draw(cmds, attrs.rect.pos(attrs.align), attrs.align, attrs.color); } void MenuItem::place() @@ -91,9 +87,8 @@ void BaseDualTextMenuItem::prepareDraw() void BaseDualTextMenuItem::draw2ndText(Gfx::RendererCommands &cmds, MenuItemDrawAttrs attrs) const { cmds.basicEffect().enableAlphaTexture(cmds); - auto [xPos, yPos] = attrs.rect.pos(LT2DO); - auto xSize = attrs.rect.size().x; - t2.draw(cmds, {(xPos + xSize) - attrs.xIndent, yPos}, RC2DO, attrs.color); + attrs.rect -= WPt{attrs.xIndent, 0}; + t2.draw(cmds, attrs.rect.pos(RC2DO), RC2DO, attrs.color); } void BaseDualTextMenuItem::draw(Gfx::RendererCommands&__restrict__ cmds, MenuItemDrawAttrs attrs) const @@ -205,8 +200,8 @@ public: void drawElement(Gfx::RendererCommands &__restrict__ cmds, size_t i, MenuItem &item, WRect rect, int xIndent) const final { - MenuItemDrawAttrs attrs{.rect = {{rect.x, rect.pos(C2DO).y}, rect.size()}, - .xIndent = xIndent, .color = menuTextColor((int)i == activeItem), .align = TableView::align}; + MenuItemDrawAttrs attrs{.rect = rect, .xIndent = xIndent, + .color = menuTextColor((int)i == activeItem), .align = TableView::align}; item.draw(cmds, attrs); } }; @@ -311,8 +306,8 @@ std::unique_ptr MultiChoiceMenuItem::makeTableView(ViewAttachParams a { return msg.visit(overloaded { - [&](const TableView::ItemsMessage &m) -> TableView::ItemReply { return items(); }, - [&](const TableView::GetItemMessage &m) -> TableView::ItemReply { return &item(m.idx); }, + [&](const TableView::ItemsMessage&) -> TableView::ItemReply { return items(); }, + [&](const TableView::GetItemMessage& m) -> TableView::ItemReply { return &item(m.idx); }, }); }, *this diff --git a/imagine/src/gui/NavView.cc b/imagine/src/gui/NavView.cc index 873fa4cec..b4347ebb9 100644 --- a/imagine/src/gui/NavView.cc +++ b/imagine/src/gui/NavView.cc @@ -52,7 +52,7 @@ bool NavView::selectNextLeftButton() if(selected == -1) selected = 1; int elem = IG::wrapMinMax(selected - 1, 0, controls); - for(auto i : iotaCount(controls)) + for([[maybe_unused]] auto i : iotaCount(controls)) { if(control[elem].isActive) { @@ -70,7 +70,7 @@ bool NavView::selectNextRightButton() if(selected == -1) selected = controls - 2; int elem = IG::wrapMinMax(selected + 1, 0, controls); - for(auto i : iotaCount(controls)) + for([[maybe_unused]] auto i : iotaCount(controls)) { if(control[elem].isActive) { @@ -287,7 +287,6 @@ void BasicNavView::draw(Gfx::RendererCommands &__restrict__ cmds, ViewDrawParams void BasicNavView::place() { using namespace IG::Gfx; - auto &r = renderer(); NavView::place(); if(leftTex) { diff --git a/imagine/src/gui/ScrollView.cc b/imagine/src/gui/ScrollView.cc index f630df2aa..df9ad468e 100644 --- a/imagine/src/gui/ScrollView.cc +++ b/imagine/src/gui/ScrollView.cc @@ -69,7 +69,7 @@ ScrollView::ScrollView(ViewAttachParams attach): //logMsg("animating over-scroll"); int clip = offset < 0 ? 0 : offsetMax; int sign = offset < 0 ? 1 : -1; - for(auto i : iotaCount(frames)) + for([[maybe_unused]] auto i : iotaCount(frames)) { int vel = std::abs((clip - offset) * overScrollVelScale); offset += sign * std::max(1, vel); diff --git a/imagine/src/gui/TableView.cc b/imagine/src/gui/TableView.cc index 7c3bc7dbf..91d2a8fac 100755 --- a/imagine/src/gui/TableView.cc +++ b/imagine/src/gui/TableView.cc @@ -290,7 +290,7 @@ int TableView::nextSelectableElement(int start, int items) { int elem = wrapMinMax(start, 0, items); auto src = itemSrc; - for(auto i : iotaCount(items)) + for([[maybe_unused]] auto i : iotaCount(items)) { if(item(src, elem).selectable()) { @@ -305,7 +305,7 @@ int TableView::prevSelectableElement(int start, int items) { int elem = wrapMinMax(start, 0, items); auto src = itemSrc; - for(auto i : iotaCount(items)) + for([[maybe_unused]] auto i : iotaCount(items)) { if(item(src, elem).selectable()) { @@ -493,11 +493,11 @@ bool TableView::handleTableInput(const Input::Event &e, bool &movedSelected) }); } -void TableView::drawElement(Gfx::RendererCommands &__restrict__ cmds, size_t i, MenuItem &item, WRect rect, int xIndent) const +void TableView::drawElement(Gfx::RendererCommands &__restrict__ cmds, size_t, MenuItem &item, WRect rect, int xIndent) const { static constexpr Gfx::Color highlightColor{0.f, .8f, 1.f}; - MenuItemDrawAttrs attrs{.rect = {{rect.x, rect.pos(C2DO).y}, rect.size()}, - .xIndent = xIndent, .color = item.highlighted() ? highlightColor : Gfx::Color(Gfx::ColorName::WHITE), .align = align}; + MenuItemDrawAttrs attrs{.rect = rect, .xIndent = xIndent, + .color = item.highlighted() ? highlightColor : Gfx::Color(Gfx::ColorName::WHITE), .align = align}; item.draw(cmds, attrs); } diff --git a/imagine/src/gui/TextEntry.cc b/imagine/src/gui/TextEntry.cc index 42c64d3e0..473e4f944 100644 --- a/imagine/src/gui/TextEntry.cc +++ b/imagine/src/gui/TextEntry.cc @@ -112,7 +112,7 @@ bool TextEntry::inputEvent(View &parentView, const Input::Event &e) }); } -void TextEntry::prepareDraw(Gfx::Renderer &r) +void TextEntry::prepareDraw() { t.makeGlyphs(); } @@ -124,16 +124,16 @@ void TextEntry::draw(Gfx::RendererCommands &__restrict__ cmds) const t.draw(cmds, b.pos(LC2DO), LC2DO, ColorName::WHITE); } -void TextEntry::place(Gfx::Renderer &r) +void TextEntry::place() { t.compile(); } -void TextEntry::place(Gfx::Renderer &r, WindowRect rect) +void TextEntry::place(WindowRect rect) { b = rect; bgQuads.write(0, {.bounds = rect.as()}); - place(r); + place(); } const char *TextEntry::textStr() const @@ -218,7 +218,7 @@ void CollectTextInputView::place() [&](auto &textEntry) { textRect.setPosRel(viewRect().pos(C2DO), {xSize, int(ySize * 1.5f)}, C2DO); - textEntry.place(renderer(), textRect); + textEntry.place(textRect); }, [&]() { @@ -269,9 +269,9 @@ void CollectTextInputView::prepareDraw() { message.makeGlyphs(); doIfUsed(textEntry, - [this](auto &textEntry) + [](auto &textEntry) { - textEntry.prepareDraw(renderer()); + textEntry.prepareDraw(); }); } diff --git a/imagine/src/gui/TextTableView.cc b/imagine/src/gui/TextTableView.cc index 414710fab..9dcbb1482 100644 --- a/imagine/src/gui/TextTableView.cc +++ b/imagine/src/gui/TextTableView.cc @@ -39,8 +39,8 @@ void TextTableView::onAddedToController(ViewController *c, const Input::Event &e void TextTableView::drawElement(Gfx::RendererCommands &__restrict__ cmds, size_t i, MenuItem &item, WRect rect, int xIndent) const { - MenuItemDrawAttrs attrs{.rect = {{rect.x, rect.pos(C2DO).y}, rect.size()}, - .xIndent = xIndent, .color = menuTextColor((int)i == activeItem), .align = TableView::align}; + MenuItemDrawAttrs attrs{.rect = rect, .xIndent = xIndent, + .color = menuTextColor((int)i == activeItem), .align = TableView::align}; item.draw(cmds, attrs); } diff --git a/imagine/src/gui/ToastView.cc b/imagine/src/gui/ToastView.cc index db63cc11a..9530aa458 100644 --- a/imagine/src/gui/ToastView.cc +++ b/imagine/src/gui/ToastView.cc @@ -33,11 +33,7 @@ ToastView::ToastView(ViewAttachParams attach): View{attach}, text{attach.rendererTask, &attach.viewManager.defaultFace}, unpostTimer { - "ToastView::unpostTimer", - [this]() - { - unpost(); - } + {.debugLabel = "ToastView::unpostTimer"}, [this]{ unpost(); } }, msgFrameQuads{attach.rendererTask, {.size = 1}} {} diff --git a/imagine/src/gui/View.cc b/imagine/src/gui/View.cc index 4d99065ec..01b2901a2 100644 --- a/imagine/src/gui/View.cc +++ b/imagine/src/gui/View.cc @@ -44,7 +44,7 @@ void ViewI::setFocus(bool) {} std::u16string_view ViewI::name() const { return u""; } -bool ViewI::onDocumentPicked(const DocumentPickerEvent& e) { return false; } +bool ViewI::onDocumentPicked(const DocumentPickerEvent&) { return false; } Gfx::Renderer &ViewAttachParams::renderer() const { @@ -77,7 +77,7 @@ void ViewController::popAndShow() dismissView(-1); } -void ViewController::popTo(View &v) +void ViewController::popTo(View&) { log.error("popTo() not implemented for this controller"); } diff --git a/imagine/src/gui/ViewStack.cc b/imagine/src/gui/ViewStack.cc index 5b74bf5bd..f131014eb 100644 --- a/imagine/src/gui/ViewStack.cc +++ b/imagine/src/gui/ViewStack.cc @@ -294,7 +294,7 @@ void ViewStack::pop() void ViewStack::popViews(size_t num) { auto win = view.size() ? &top().window() : nullptr; - for(auto i : iotaCount(num)) + for([[maybe_unused]] auto i : iotaCount(num)) { pop(); } diff --git a/imagine/src/input/Axis.cc b/imagine/src/input/Axis.cc index c3bfd91f5..1f0c712cc 100644 --- a/imagine/src/input/Axis.cc +++ b/imagine/src/input/Axis.cc @@ -75,7 +75,7 @@ constexpr std::pair joystickKeys(AxisId axisId) return {}; } -Axis::Axis(Map map, AxisId id, float scaler): +Axis::Axis(AxisId id, float scaler): scaler{scaler}, keyEmu { @@ -83,9 +83,9 @@ Axis::Axis(Map map, AxisId id, float scaler): }, id_{id} {} -static std::pair emulatedKeys(Map map, AxisId id, bool invertY) +static std::pair emulatedKeys(AxisId id, bool invertY) { - auto keys = directionKeys(map); + auto keys = directionKeys(); std::pair yKeys = {keys.up, keys.down}; if(invertY) std::swap(yKeys.first, yKeys.second); @@ -118,7 +118,7 @@ void Axis::setEmulatesKeys(Map map, bool on) if(on) { const bool invertY = Config::Input::BLUETOOTH && map != Map::SYSTEM; - auto dpadKeys = emulatedKeys(map, id(), invertY); + auto dpadKeys = emulatedKeys(id(), invertY); keyEmu.keys = dpadKeys; } else diff --git a/imagine/src/input/Device.cc b/imagine/src/input/Device.cc index cf54d3198..dd24e84cf 100644 --- a/imagine/src/input/Device.cc +++ b/imagine/src/input/Device.cc @@ -21,7 +21,7 @@ namespace IG::Input constexpr SystemLogger log{"InputDev"}; -static const char *keyButtonName(Key b) +constexpr auto keyButtonName(Key b) { switch(b) { @@ -239,7 +239,7 @@ static const char *keyButtonName(Key b) return ""; } -static const char *ps3SysButtonName(Key b) +constexpr const char* ps3SysButtonName([[maybe_unused]] Key b) { #if defined __ANDROID__ switch(b) @@ -259,7 +259,7 @@ static const char *ps3SysButtonName(Key b) } #ifdef __ANDROID__ -static const char *xperiaPlayButtonName(Key b) +constexpr const char* xperiaPlayButtonName(Key b) { switch(b) { @@ -271,7 +271,7 @@ static const char *xperiaPlayButtonName(Key b) return nullptr; } -static const char *ouyaButtonName(Key b) +constexpr const char* ouyaButtonName(Key b) { switch(b) { @@ -288,7 +288,7 @@ static const char *ouyaButtonName(Key b) #endif #ifdef CONFIG_MACHINE_PANDORA -static const char *openPandoraButtonName(Key b) +constexpr const char* openPandoraButtonName(Key b) { switch(b) { @@ -369,7 +369,7 @@ const char *Device::keyName(Key k) const default: return ""; case Map::SYSTEM: { - auto subtypeButtonName = [](Subtype subtype, Key k) -> const char * + auto subtypeButtonName = [](Subtype subtype, [[maybe_unused]] Key k) -> const char * { switch(subtype) { diff --git a/imagine/src/input/Input.cc b/imagine/src/input/Input.cc index 110ff0a6c..39e51cedd 100644 --- a/imagine/src/input/Input.cc +++ b/imagine/src/input/Input.cc @@ -98,7 +98,7 @@ std::string_view BaseEvent::mapName(Map map) } } -size_t BaseEvent::mapNumKeys(Map map) +size_t BaseEvent::mapNumKeys(Map) { return Input::Keycode::COUNT; } @@ -158,7 +158,7 @@ Map validateMap(uint8_t mapValue) } } -DirectionKeys directionKeys(Map map) +DirectionKeys directionKeys() { return {Keycode::UP, Keycode::RIGHT, Keycode::DOWN, Keycode::LEFT}; } @@ -184,8 +184,8 @@ void BaseApplication::startKeyRepeatTimer(Input::KeyEvent event) keyRepeatEvent.setRepeatCount(1); if(!keyRepeatTimer) [[unlikely]] { - keyRepeatTimer.emplace("keyRepeatTimer", - [this]() + keyRepeatTimer.emplace(TimerDesc{.debugLabel = "keyRepeatTimer"}, + [this] { //logMsg("repeating key event"); if(keyRepeatEvent.pushed()) [[likely]] diff --git a/imagine/src/input/apple/AppleGameDevice.mm b/imagine/src/input/apple/AppleGameDevice.mm index 33b3a2843..98f4fc658 100644 --- a/imagine/src/input/apple/AppleGameDevice.mm +++ b/imagine/src/input/apple/AppleGameDevice.mm @@ -38,10 +38,10 @@ AppleGameDevice::AppleGameDevice(ApplicationContext ctx, GCController *gcControl { typeFlags_.joystick = true; subtype_ = Subtype::APPLE_EXTENDED_GAMEPAD; - axis[0] = {Map::APPLE_GAME_CONTROLLER, Input::AxisId::X}; - axis[1] = {Map::APPLE_GAME_CONTROLLER, Input::AxisId::Y}; - axis[2] = {Map::APPLE_GAME_CONTROLLER, Input::AxisId::Z}; - axis[3] = {Map::APPLE_GAME_CONTROLLER, Input::AxisId::RZ}; + axis[0] = {Input::AxisId::X}; + axis[1] = {Input::AxisId::Y}; + axis[2] = {Input::AxisId::Z}; + axis[3] = {Input::AxisId::RZ}; } log.info("controller vendor:{}", name_); } @@ -52,92 +52,92 @@ AppleGameDevice::~AppleGameDevice() } template -void AppleGameDevice::setGamepadBlocks(Device &dev, GCController *controller, T gamepad) +void AppleGameDevice::setGamepadBlocks(Device& dev, GCController*, T gamepad) { gamepad.buttonA.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, float value, [[maybe_unused]] BOOL pressed) { this->handleKey(dev, AppleGC::A, value != 0.f); }; gamepad.buttonB.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, float value, [[maybe_unused]] BOOL pressed) { this->handleKey(dev, AppleGC::B, value != 0.f); }; gamepad.buttonX.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, float value, [[maybe_unused]] BOOL pressed) { this->handleKey(dev, AppleGC::X, value != 0.f); }; gamepad.buttonY.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, float value, [[maybe_unused]] BOOL pressed) { this->handleKey(dev, AppleGC::Y, value != 0.f); }; gamepad.leftShoulder.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, float value, [[maybe_unused]] BOOL pressed) { this->handleKey(dev, AppleGC::L1, value != 0.f); }; gamepad.rightShoulder.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, float value, [[maybe_unused]] BOOL pressed) { this->handleKey(dev, AppleGC::R1, value != 0.f); }; gamepad.dpad.up.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, [[maybe_unused]] float value, BOOL pressed) { this->handleKey(dev, AppleGC::UP, pressed); }; gamepad.dpad.down.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, [[maybe_unused]] float value, BOOL pressed) { this->handleKey(dev, AppleGC::DOWN, pressed); }; gamepad.dpad.left.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, [[maybe_unused]] float value, BOOL pressed) { this->handleKey(dev, AppleGC::LEFT, pressed); }; gamepad.dpad.right.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, [[maybe_unused]] float value, BOOL pressed) { this->handleKey(dev, AppleGC::RIGHT, pressed); }; } -void AppleGameDevice::setExtendedGamepadBlocks(Device &dev, GCController *controller, GCExtendedGamepad *extGamepad) +void AppleGameDevice::setExtendedGamepadBlocks(Device &dev, GCController*, GCExtendedGamepad* extGamepad) { extGamepad.leftTrigger.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, [[maybe_unused]] float value, BOOL pressed) { this->handleKey(dev, AppleGC::L2, pressed); }; extGamepad.rightTrigger.valueChangedHandler = - ^(GCControllerButtonInput *button, float value, BOOL pressed) + ^(GCControllerButtonInput*, [[maybe_unused]] float value, BOOL pressed) { this->handleKey(dev, AppleGC::R2, pressed); }; extGamepad.leftThumbstick.xAxis.valueChangedHandler = - ^(GCControllerAxisInput *, float value) + ^(GCControllerAxisInput*, float value) { if(axis[0].dispatchInputEvent(value, Map::APPLE_GAME_CONTROLLER, SteadyClock::now(), dev, ctx.mainWindow())) ctx.endIdleByUserActivity(); }; extGamepad.leftThumbstick.yAxis.valueChangedHandler = - ^(GCControllerAxisInput *, float value) + ^(GCControllerAxisInput*, float value) { if(axis[1].dispatchInputEvent(value, Map::APPLE_GAME_CONTROLLER, SteadyClock::now(), dev, ctx.mainWindow())) ctx.endIdleByUserActivity(); }; extGamepad.rightThumbstick.xAxis.valueChangedHandler = - ^(GCControllerAxisInput *, float value) + ^(GCControllerAxisInput*, float value) { if(axis[2].dispatchInputEvent(value, Map::APPLE_GAME_CONTROLLER, SteadyClock::now(), dev, ctx.mainWindow())) ctx.endIdleByUserActivity(); }; extGamepad.rightThumbstick.yAxis.valueChangedHandler = - ^(GCControllerAxisInput *, float value) + ^(GCControllerAxisInput*, float value) { if(axis[3].dispatchInputEvent(value, Map::APPLE_GAME_CONTROLLER, SteadyClock::now(), dev, ctx.mainWindow())) ctx.endIdleByUserActivity(); @@ -182,7 +182,7 @@ void AppleGameDevice::setKeys(Device &dev) setGamepadBlocks(dev, gcController(), gamepad); } gcController().controllerPausedHandler = - ^(GCController *controller) + ^(GCController*) { this->handleKey(dev, AppleGC::PAUSE, true, false); this->handleKey(dev, AppleGC::PAUSE, false, false); diff --git a/imagine/src/input/evdev/evdev.cc b/imagine/src/input/evdev/evdev.cc index ab78cc1e4..0e2ae8258 100644 --- a/imagine/src/input/evdev/evdev.cc +++ b/imagine/src/input/evdev/evdev.cc @@ -109,11 +109,9 @@ static constexpr bool isBitSetInArray(const T (&arr)[S], unsigned int bit) return arr[bit / bits] & ((T)1 << (bit % bits)); } -EvdevInputDevice::EvdevInputDevice() {} - -EvdevInputDevice::EvdevInputDevice(int id, int fd, DeviceTypeFlags typeFlags, std::string name_, uint32_t vendorProductId): +EvdevInputDevice::EvdevInputDevice(int id, UniqueFileDescriptor fd, DeviceTypeFlags typeFlags, std::string name_, uint32_t vendorProductId): BaseDevice{id, Map::SYSTEM, typeFlags, std::move(name_)}, - fd{fd} + fdSrc{std::move(fd), {.debugLabel = "EvdevInputDevice", .eventLoop = EventLoop::forThread()}, {}} { subtype_ = DeviceSubtype::GENERIC_GAMEPAD; updateGamepadSubtype(name_, vendorProductId); @@ -121,12 +119,6 @@ EvdevInputDevice::EvdevInputDevice(int id, int fd, DeviceTypeFlags typeFlags, st typeFlags_.joystick = true; } -EvdevInputDevice::~EvdevInputDevice() -{ - fdSrc.detach(); - ::close(fd); -} - void EvdevInputDevice::processInputEvents(Device &dev, LinuxApplication &app, std::span events) { for(auto &ev : events) @@ -165,14 +157,14 @@ void EvdevInputDevice::processInputEvents(Device &dev, LinuxApplication &app, st bool EvdevInputDevice::setupJoystickBits() { ulong evBit[IG::divRoundUp(EV_MAX, IG::bitSize)]{}; - bool isJoystick = (ioctl(fd, EVIOCGBIT(0, sizeof(evBit)), evBit) >= 0) + bool isJoystick = (ioctl(fd(), EVIOCGBIT(0, sizeof(evBit)), evBit) >= 0) && isBitSetInArray(evBit, EV_ABS); if(!isJoystick) return false; ulong absBit[IG::divRoundUp(ABS_MAX, IG::bitSize)]{}; - if((ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBit)), absBit) < 0)) + if((ioctl(fd(), EVIOCGBIT(EV_ABS, sizeof(absBit)), absBit) < 0)) { log.error("unable to check abs bits"); return false; @@ -189,14 +181,14 @@ bool EvdevInputDevice::setupJoystickBits() continue; log.info("joystick axis:{}", (int)axisId); struct input_absinfo info; - if(ioctl(fd, EVIOCGABS((int)axisId), &info) < 0) + if(ioctl(fd(), EVIOCGABS((int)axisId), &info) < 0) { logErr("error getting absinfo"); continue; } auto rangeSize = info.maximum - info.minimum; float scale = 2.f / rangeSize; - auto &currAxis = axis.emplace_back(Map::SYSTEM, axisId, scale); + auto &currAxis = axis.emplace_back(axisId, scale); axisRangeOffset[axis.size() - 1] = currAxis.isTrigger() ? 0 : (std::abs(info.minimum) - std::abs(info.maximum)) / 2; log.info("min:{} max:{} fuzz:{} flat:{} range offset:{}", info.minimum, info.maximum, info.fuzz, info.flat, axisRangeOffset[axis.size() - 1]); @@ -214,35 +206,34 @@ bool EvdevInputDevice::setupJoystickBits() void EvdevInputDevice::addPollEvent(Device &dev, LinuxApplication &app) { auto &evDev = getAs(dev); - assert(evDev.fd >= 0); - evDev.fdSrc = {"EvdevInputDevice", evDev.fd, {}, - [&dev, &app](int fd, int pollEvents) + assert(evDev.fd() >= 0); + evDev.fdSrc.setCallback([&dev, &app](int fd, int pollEvents) + { + if(pollEvents & pollEventError) [[unlikely]] { - if(pollEvents & POLLEV_ERR) [[unlikely]] + log.error("error:{} in input fd:{} ({})", errno, fd, dev.name()); + app.removeInputDevice(ApplicationContext{static_cast(app)}, dev, true); + return false; + } + else + { + struct input_event event[64]; + int len; + while((len = read(fd, event, sizeof event)) > 0) { - log.error("error:{} in input fd:{} ({})", errno, fd, dev.name()); + uint32_t events = len / sizeof(struct input_event); + //logMsg("read %d bytes from input fd %d, %d events", len, this->fd, events); + processInputEvents(dev, app, {event, events}); + } + if(len == -1 && errno != EAGAIN) + { + log.info("error:{} reading from input fd:{} ({})", errno, fd, dev.name()); app.removeInputDevice(ApplicationContext{static_cast(app)}, dev, true); return false; } - else - { - struct input_event event[64]; - int len; - while((len = read(fd, event, sizeof event)) > 0) - { - uint32_t events = len / sizeof(struct input_event); - //logMsg("read %d bytes from input fd %d, %d events", len, this->fd, events); - processInputEvents(dev, app, {event, events}); - } - if(len == -1 && errno != EAGAIN) - { - log.info("error:{} reading from input fd:{} ({})", errno, fd, dev.name()); - app.removeInputDevice(ApplicationContext{static_cast(app)}, dev, true); - return false; - } - } - return true; - }}; + } + return true; + }); } static bool devIsGamepad(int fd) @@ -341,9 +332,9 @@ void LinuxApplication::initEvdev(EventLoop loop) int inputDevNotifyFd = inotify_init(); if(inputDevNotifyFd >= 0) { - auto watch = inotify_add_watch(inputDevNotifyFd, DEV_NODE_PATH, IN_CREATE | IN_ATTRIB); + inotify_add_watch(inputDevNotifyFd, DEV_NODE_PATH, IN_CREATE | IN_ATTRIB); fd_setNonblock(inputDevNotifyFd, 1); - evdevSrc = {"Evdev Inotify", inputDevNotifyFd, loop, + evdevSrc = {inputDevNotifyFd, {.debugLabel = "Evdev Inotify", .eventLoop = loop}, [this](int fd, int) { char event[sizeof(struct inotify_event) + 2048]; @@ -375,7 +366,8 @@ void LinuxApplication::initEvdev(EventLoop loop) } while(len); } return true; - }}; + } + }; } else { diff --git a/imagine/src/io/AAssetIO.cc b/imagine/src/io/AAssetIO.cc index 96dd0eb5a..7bfed54ea 100755 --- a/imagine/src/io/AAssetIO.cc +++ b/imagine/src/io/AAssetIO.cc @@ -79,7 +79,7 @@ ssize_t AAssetIO::read(void *buff, size_t bytes, std::optional offset) } } -ssize_t AAssetIO::write(const void *buff, size_t bytes, std::optional offset) +ssize_t AAssetIO::write(const void*, size_t, std::optional) { return -1; } @@ -153,7 +153,7 @@ IOBuffer AAssetIO::releaseBuffer() auto map = mapIO.map(); logMsg("releasing asset:%p with buffer:%p (%zu bytes)", asset.get(), map.data(), map.size()); return {map, {}, - [asset = asset.release()](const uint8_t *ptr, size_t) + [asset = asset.release()](const uint8_t*, size_t) { logMsg("closing released asset:%p", asset); AAsset_close(asset); diff --git a/imagine/src/io/ArchiveIO.cc b/imagine/src/io/ArchiveIO.cc index 88c1c1f23..e841a9077 100755 --- a/imagine/src/io/ArchiveIO.cc +++ b/imagine/src/io/ArchiveIO.cc @@ -273,7 +273,7 @@ ssize_t ArchiveIO::read(void *buff, size_t bytes, std::optional offset) } } -ssize_t ArchiveIO::write(const void* buff, size_t bytes, std::optional offset) +ssize_t ArchiveIO::write(const void*, size_t, std::optional) { return -1; } diff --git a/imagine/src/io/PosixIO.cc b/imagine/src/io/PosixIO.cc index 68beaeb0f..e3ffad8e4 100755 --- a/imagine/src/io/PosixIO.cc +++ b/imagine/src/io/PosixIO.cc @@ -39,9 +39,9 @@ constexpr SystemLogger log{"PosixIO"}; constexpr int MAP_POPULATE = 0; #endif -static auto flagsString(OpenFlags openFlags) +constexpr auto flagsString(OpenFlags openFlags) { - StaticString<5> logFlagsStr{}; + StaticString<5> logFlagsStr; if(openFlags.read) logFlagsStr += 'r'; if(openFlags.write) logFlagsStr += 'w'; if(openFlags.create) logFlagsStr += 'c'; @@ -49,9 +49,9 @@ static auto flagsString(OpenFlags openFlags) return logFlagsStr; } -static auto protectionFlagsString(int flags) +constexpr auto protectionFlagsString(int flags) { - StaticString<3> logFlagsStr{}; + StaticString<3> logFlagsStr; if(flags & PROT_READ) logFlagsStr += 'r'; if(flags & PROT_WRITE) logFlagsStr += 'w'; return logFlagsStr; @@ -247,7 +247,7 @@ static int adviceToFAdv(IOAdvice advice) } #endif -void PosixIO::advise(off_t offset, size_t bytes, Advice advice) +void PosixIO::advise([[maybe_unused]] off_t offset, [[maybe_unused]] size_t bytes, [[maybe_unused]] Advice advice) { #ifdef __APPLE__ if(advice == Advice::Sequential || advice == Advice::WillNeed) @@ -309,7 +309,7 @@ IOBuffer PosixIO::byteBufferFromMmap(void *data, size_t size) log.info("unmapping:{} ({} bytes)", (void*)ptr, size); if(munmap((void*)ptr, size) == -1) { - if(Config::DEBUG_BUILD) + if constexpr(Config::DEBUG_BUILD) log.error("munmap({}, {}) error:{}", (void*)ptr, size, strerror(errno)); } } diff --git a/imagine/src/logger/stdio/logger.cc b/imagine/src/logger/stdio/logger.cc index b118448a3..00f2e5891 100755 --- a/imagine/src/logger/stdio/logger.cc +++ b/imagine/src/logger/stdio/logger.cc @@ -82,7 +82,7 @@ static void printToLogLineBuffer(const char* msg, va_list args) vsnprintf(logLineBuffer + strlen(logLineBuffer), sizeof(logLineBuffer) - strlen(logLineBuffer), msg, args); } -static int severityToLogLevel(LoggerSeverity severity) +constexpr int severityToLogLevel([[maybe_unused]] LoggerSeverity severity) { #ifdef __ANDROID__ switch(severity) @@ -165,7 +165,7 @@ void logger_printf(LoggerSeverity severity, const char* msg, ...) namespace IG::Log { -void printMsg(LoggerSeverity lv, const char* str, size_t strSize) +void printMsg([[maybe_unused]] LoggerSeverity lv, const char* str, size_t strSize) { const char newLine = '\n'; if(logExternalFile) diff --git a/imagine/tests/FrameRateTest/src/main/TestPicker.cc b/imagine/tests/FrameRateTest/src/main/TestPicker.cc index da07dedf1..fc0c5c6be 100644 --- a/imagine/tests/FrameRateTest/src/main/TestPicker.cc +++ b/imagine/tests/FrameRateTest/src/main/TestPicker.cc @@ -39,9 +39,9 @@ void TestPicker::setTests(const TestDesc *testDesc, unsigned tests) for(auto i : iotaCount(tests)) { testEntry.emplace_back(testDesc[i].name, u"", attachParams(), - [this, i](IG::DualTextMenuItem &, IG::View &, IG::Input::Event e) + [this, i] { - auto &app = mainApp(appContext()); + auto &app = appContext().applicationAs(); auto test = app.startTest(window(), testParam[i]); test->onTestFinished = [this, i](TestFramework &test) diff --git a/imagine/tests/FrameRateTest/src/main/main.cc b/imagine/tests/FrameRateTest/src/main/main.cc index 0c4d3c173..b1416ac90 100755 --- a/imagine/tests/FrameRateTest/src/main/main.cc +++ b/imagine/tests/FrameRateTest/src/main/main.cc @@ -86,14 +86,14 @@ FrameRateTestApplication::FrameRateTestApplication(IG::ApplicationInitParams ini setPickerHandlers(win); ctx.addOnResume( - [this, &win](IG::ApplicationContext, bool focused) + [this, &win](IG::ApplicationContext, [[maybe_unused]] bool focused) { windowData(win).picker.prepareDraw(); return true; }); ctx.addOnExit( - [this, &win](IG::ApplicationContext ctx, bool backgrounded) + [this, &win](IG::ApplicationContext, [[maybe_unused]] bool backgrounded) { if(backgrounded) { @@ -281,7 +281,7 @@ void FrameRateTestApplication::placeElements(const IG::Window &win) } else { - activeTest->place(renderer, win.contentBounds(), winData.testRect); + activeTest->place(win.contentBounds(), winData.testRect); } } @@ -291,7 +291,7 @@ void FrameRateTestApplication::finishTest(Window &win, SteadyClockTimePoint fram auto &activeTest = windowData(win).activeTest; if(activeTest) { - activeTest->finish(renderer.task(), frameTime); + activeTest->finish(frameTime); } renderer.mainTask.awaitPending(); activeTest.reset(); @@ -332,7 +332,6 @@ TestFramework *FrameRateTestApplication::startTest(IG::Window &win, const TestPa initCPUFreqStatus(); initCPULoadStatus(); placeElements(win); - auto &winData = windowData(win); setActiveTestHandlers(win); return activeTest.get(); } diff --git a/imagine/tests/FrameRateTest/src/main/main.hh b/imagine/tests/FrameRateTest/src/main/main.hh index 66be24d43..8950182c2 100644 --- a/imagine/tests/FrameRateTest/src/main/main.hh +++ b/imagine/tests/FrameRateTest/src/main/main.hh @@ -52,9 +52,4 @@ private: void updateWindowSurface(Window &, Window::SurfaceChange); }; -static FrameRateTestApplication &mainApp(IG::ApplicationContext ctx) -{ - return static_cast(ctx.application()); -} - } diff --git a/imagine/tests/FrameRateTest/src/main/tests.cc b/imagine/tests/FrameRateTest/src/main/tests.cc index a76742bf8..43e0474a8 100644 --- a/imagine/tests/FrameRateTest/src/main/tests.cc +++ b/imagine/tests/FrameRateTest/src/main/tests.cc @@ -79,7 +79,7 @@ void TestFramework::placeFrameStatsText() } } -void TestFramework::place(Gfx::Renderer &r, WRect viewBounds_, WRect testRect) +void TestFramework::place(WRect viewBounds_, WRect testRect) { viewBounds = viewBounds_; placeCPUStatsText(); @@ -91,7 +91,6 @@ void TestFramework::frameUpdate(Gfx::RendererTask &rTask, IG::Window &win, IG::F { auto timestamp = frameParams.timestamp; // CPU stats - auto &screen = *win.screen(); bool updatedCPUStats = false; if(frames % 8 == 0) { @@ -197,7 +196,7 @@ void TestFramework::draw(Gfx::RendererCommands &cmds, Gfx::ClipRect bounds, int } } -void TestFramework::finish(Gfx::RendererTask &task, SteadyClockTimePoint frameTime) +void TestFramework::finish(SteadyClockTimePoint frameTime) { endTime = frameTime; if(onTestFinished) diff --git a/imagine/tests/FrameRateTest/src/main/tests.hh b/imagine/tests/FrameRateTest/src/main/tests.hh index 82015b6b1..a6d21588f 100644 --- a/imagine/tests/FrameRateTest/src/main/tests.hh +++ b/imagine/tests/FrameRateTest/src/main/tests.hh @@ -89,15 +89,15 @@ public: TestFramework(ViewAttachParams); virtual ~TestFramework() {} - virtual void placeTest(WRect testRect) {} + virtual void placeTest(WRect) {} virtual void frameUpdateTest(Gfx::RendererTask &, Screen &, SteadyClockTimePoint) = 0; virtual void drawTest(Gfx::RendererCommands &cmds, Gfx::ClipRect bounds) = 0; - virtual void presentedTest(Gfx::RendererCommands &cmds) {} - void place(Gfx::Renderer &r, WRect viewBounds, WRect testRect); + virtual void presentedTest(Gfx::RendererCommands&) {} + void place(WRect viewBounds, WRect testRect); void frameUpdate(Gfx::RendererTask &rTask, IG::Window &win, IG::FrameParams frameParams); void prepareDraw(); void draw(Gfx::RendererCommands &cmds, Gfx::ClipRect bounds, int xIndent); - void finish(Gfx::RendererTask &, SteadyClockTimePoint); + void finish(SteadyClockTimePoint); void setCPUFreqText(std::string_view str); void setCPUUseText(std::string_view str);