{- |
Copyright  : Will Thompson, Iñaki García Etxebarria and Jonas Platte
License    : LGPL-2.1
Maintainer : Iñaki García Etxebarria (garetxe@gmail.com)

'GI.Gio.Interfaces.MemoryMonitor.MemoryMonitor' will monitor system memory and suggest to the application
when to free memory so as to leave more room for other applications.
It is implemented on Linux using the <https://gitlab.freedesktop.org/hadess/low-memory-monitor/ Low Memory Monitor>
(<https://hadess.pages.freedesktop.org/low-memory-monitor/ API documentation>).

There is also an implementation for use inside Flatpak sandboxes.

Possible actions to take when the signal is received are:

* Free caches
* Save files that haven\'t been looked at in a while to disk, ready to be reopened when needed
* Run a garbage collection cycle
* Try and compress fragmented allocations
* Exit on idle if the process has no reason to stay around


See 'GI.Gio.Enums.MemoryMonitorWarningLevel' for details on the various warning levels.


=== /C code/
>
>static void
>warning_cb (GMemoryMonitor *m, GMemoryMonitorWarningLevel level)
>{
>  g_debug ("Warning level: %d", level);
>  if (warning_level > G_MEMORY_MONITOR_WARNING_LEVEL_LOW)
>    drop_caches ();
>}
>
>static GMemoryMonitor *
>monitor_low_memory (void)
>{
>  GMemoryMonitor *m;
>  m = g_memory_monitor_dup_default ();
>  g_signal_connect (G_OBJECT (m), "low-memory-warning",
>                    G_CALLBACK (warning_cb), NULL);
>  return m;
>}


Don\'t forget to disconnect the 'GI.Gio.Interfaces.MemoryMonitor.MemoryMonitor'::@/low-memory-warning/@
signal, and unref the 'GI.Gio.Interfaces.MemoryMonitor.MemoryMonitor' itself when exiting.

/Since: 2.64/
-}

#define ENABLE_OVERLOADING \
       (!defined(__HADDOCK_VERSION__))

module GI.Gio.Interfaces.MemoryMonitor
    (

-- * Exported types
    MemoryMonitor(..)                       ,
    noMemoryMonitor                         ,
    IsMemoryMonitor                         ,
    toMemoryMonitor                         ,


 -- * Methods
-- ** dupDefault #method:dupDefault#

    memoryMonitorDupDefault                 ,




 -- * Signals
-- ** lowMemoryWarning #signal:lowMemoryWarning#

    C_MemoryMonitorLowMemoryWarningCallback ,
    MemoryMonitorLowMemoryWarningCallback   ,
#if ENABLE_OVERLOADING
    MemoryMonitorLowMemoryWarningSignalInfo ,
#endif
    afterMemoryMonitorLowMemoryWarning      ,
    genClosure_MemoryMonitorLowMemoryWarning,
    mk_MemoryMonitorLowMemoryWarningCallback,
    noMemoryMonitorLowMemoryWarningCallback ,
    onMemoryMonitorLowMemoryWarning         ,
    wrap_MemoryMonitorLowMemoryWarningCallback,




    ) where

import Data.GI.Base.ShortPrelude
import qualified Data.GI.Base.ShortPrelude as SP
import qualified Data.GI.Base.Overloading as O
import qualified Prelude as P

import qualified Data.GI.Base.Attributes as GI.Attributes
import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr
import qualified Data.GI.Base.GError as B.GError
import qualified Data.GI.Base.GVariant as B.GVariant
import qualified Data.GI.Base.GValue as B.GValue
import qualified Data.GI.Base.GParamSpec as B.GParamSpec
import qualified Data.GI.Base.CallStack as B.CallStack
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as Map
import qualified Foreign.Ptr as FP

import qualified GI.GObject.Objects.Object as GObject.Object
import {-# SOURCE #-} qualified GI.Gio.Enums as Gio.Enums
import {-# SOURCE #-} qualified GI.Gio.Interfaces.Initable as Gio.Initable

-- interface MemoryMonitor 
-- | Memory-managed wrapper type.
newtype MemoryMonitor = MemoryMonitor (ManagedPtr MemoryMonitor)
-- | A convenience alias for `Nothing` :: `Maybe` `MemoryMonitor`.
noMemoryMonitor :: Maybe MemoryMonitor
noMemoryMonitor = Nothing

-- signal MemoryMonitor::low-memory-warning
{- |
Emitted when the system is running low on free memory. The signal
handler should then take the appropriate action depending on the
warning level. See the 'GI.Gio.Enums.MemoryMonitorWarningLevel' documentation for
details.

/Since: 2.64/
-}
type MemoryMonitorLowMemoryWarningCallback =
    Gio.Enums.MemoryMonitorWarningLevel
    {- ^ /@level@/: the 'GI.Gio.Enums.MemoryMonitorWarningLevel' warning level -}
    -> IO ()

-- | A convenience synonym for @`Nothing` :: `Maybe` `MemoryMonitorLowMemoryWarningCallback`@.
noMemoryMonitorLowMemoryWarningCallback :: Maybe MemoryMonitorLowMemoryWarningCallback
noMemoryMonitorLowMemoryWarningCallback = Nothing

-- | Type for the callback on the (unwrapped) C side.
type C_MemoryMonitorLowMemoryWarningCallback =
    Ptr () ->                               -- object
    CUInt ->
    Ptr () ->                               -- user_data
    IO ()

-- | Generate a function pointer callable from C code, from a `C_MemoryMonitorLowMemoryWarningCallback`.
foreign import ccall "wrapper"
    mk_MemoryMonitorLowMemoryWarningCallback :: C_MemoryMonitorLowMemoryWarningCallback -> IO (FunPtr C_MemoryMonitorLowMemoryWarningCallback)

-- | Wrap the callback into a `Closure`.
genClosure_MemoryMonitorLowMemoryWarning :: MemoryMonitorLowMemoryWarningCallback -> IO Closure
genClosure_MemoryMonitorLowMemoryWarning cb = do
    let cb' = wrap_MemoryMonitorLowMemoryWarningCallback cb
    mk_MemoryMonitorLowMemoryWarningCallback cb' >>= newCClosure


-- | Wrap a `MemoryMonitorLowMemoryWarningCallback` into a `C_MemoryMonitorLowMemoryWarningCallback`.
wrap_MemoryMonitorLowMemoryWarningCallback ::
    MemoryMonitorLowMemoryWarningCallback ->
    C_MemoryMonitorLowMemoryWarningCallback
wrap_MemoryMonitorLowMemoryWarningCallback _cb _ level _ = do
    let level' = (toEnum . fromIntegral) level
    _cb  level'


{- |
Connect a signal handler for the “@low-memory-warning@” signal, to be run before the default handler.
When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to

@
'Data.GI.Base.Signals.on' memoryMonitor #lowMemoryWarning callback
@
-}
onMemoryMonitorLowMemoryWarning :: (IsMemoryMonitor a, MonadIO m) => a -> MemoryMonitorLowMemoryWarningCallback -> m SignalHandlerId
onMemoryMonitorLowMemoryWarning obj cb = liftIO $ do
    let cb' = wrap_MemoryMonitorLowMemoryWarningCallback cb
    cb'' <- mk_MemoryMonitorLowMemoryWarningCallback cb'
    connectSignalFunPtr obj "low-memory-warning" cb'' SignalConnectBefore

{- |
Connect a signal handler for the “@low-memory-warning@” signal, to be run after the default handler.
When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to

@
'Data.GI.Base.Signals.after' memoryMonitor #lowMemoryWarning callback
@
-}
afterMemoryMonitorLowMemoryWarning :: (IsMemoryMonitor a, MonadIO m) => a -> MemoryMonitorLowMemoryWarningCallback -> m SignalHandlerId
afterMemoryMonitorLowMemoryWarning obj cb = liftIO $ do
    let cb' = wrap_MemoryMonitorLowMemoryWarningCallback cb
    cb'' <- mk_MemoryMonitorLowMemoryWarningCallback cb'
    connectSignalFunPtr obj "low-memory-warning" cb'' SignalConnectAfter


#if ENABLE_OVERLOADING
data MemoryMonitorLowMemoryWarningSignalInfo
instance SignalInfo MemoryMonitorLowMemoryWarningSignalInfo where
    type HaskellCallbackType MemoryMonitorLowMemoryWarningSignalInfo = MemoryMonitorLowMemoryWarningCallback
    connectSignal _ obj cb connectMode = do
        let cb' = wrap_MemoryMonitorLowMemoryWarningCallback cb
        cb'' <- mk_MemoryMonitorLowMemoryWarningCallback cb'
        connectSignalFunPtr obj "low-memory-warning" cb'' connectMode

type instance O.SignalList MemoryMonitor = MemoryMonitorSignalList
type MemoryMonitorSignalList = ('[ '("lowMemoryWarning", MemoryMonitorLowMemoryWarningSignalInfo), '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, *)])

#endif

foreign import ccall "g_memory_monitor_get_type"
    c_g_memory_monitor_get_type :: IO GType

instance GObject MemoryMonitor where
    gobjectType _ = c_g_memory_monitor_get_type


-- | Type class for types which can be safely cast to `MemoryMonitor`, for instance with `toMemoryMonitor`.
class GObject o => IsMemoryMonitor o
#if MIN_VERSION_base(4,9,0)
instance {-# OVERLAPPABLE #-} (GObject a, O.UnknownAncestorError MemoryMonitor a) =>
    IsMemoryMonitor a
#endif
instance IsMemoryMonitor MemoryMonitor
instance Gio.Initable.IsInitable MemoryMonitor
instance GObject.Object.IsObject MemoryMonitor

-- | Cast to `MemoryMonitor`, for types for which this is known to be safe. For general casts, use `Data.GI.Base.ManagedPtr.castTo`.
toMemoryMonitor :: (MonadIO m, IsMemoryMonitor o) => o -> m MemoryMonitor
toMemoryMonitor = liftIO . unsafeCastTo MemoryMonitor

#if ENABLE_OVERLOADING
instance O.HasAttributeList MemoryMonitor
type instance O.AttributeList MemoryMonitor = MemoryMonitorAttributeList
type MemoryMonitorAttributeList = ('[ ] :: [(Symbol, *)])
#endif

#if ENABLE_OVERLOADING
#endif

#if ENABLE_OVERLOADING
type family ResolveMemoryMonitorMethod (t :: Symbol) (o :: *) :: * where
    ResolveMemoryMonitorMethod "bindProperty" o = GObject.Object.ObjectBindPropertyMethodInfo
    ResolveMemoryMonitorMethod "bindPropertyFull" o = GObject.Object.ObjectBindPropertyFullMethodInfo
    ResolveMemoryMonitorMethod "forceFloating" o = GObject.Object.ObjectForceFloatingMethodInfo
    ResolveMemoryMonitorMethod "freezeNotify" o = GObject.Object.ObjectFreezeNotifyMethodInfo
    ResolveMemoryMonitorMethod "getv" o = GObject.Object.ObjectGetvMethodInfo
    ResolveMemoryMonitorMethod "init" o = Gio.Initable.InitableInitMethodInfo
    ResolveMemoryMonitorMethod "isFloating" o = GObject.Object.ObjectIsFloatingMethodInfo
    ResolveMemoryMonitorMethod "notify" o = GObject.Object.ObjectNotifyMethodInfo
    ResolveMemoryMonitorMethod "notifyByPspec" o = GObject.Object.ObjectNotifyByPspecMethodInfo
    ResolveMemoryMonitorMethod "ref" o = GObject.Object.ObjectRefMethodInfo
    ResolveMemoryMonitorMethod "refSink" o = GObject.Object.ObjectRefSinkMethodInfo
    ResolveMemoryMonitorMethod "runDispose" o = GObject.Object.ObjectRunDisposeMethodInfo
    ResolveMemoryMonitorMethod "stealData" o = GObject.Object.ObjectStealDataMethodInfo
    ResolveMemoryMonitorMethod "stealQdata" o = GObject.Object.ObjectStealQdataMethodInfo
    ResolveMemoryMonitorMethod "thawNotify" o = GObject.Object.ObjectThawNotifyMethodInfo
    ResolveMemoryMonitorMethod "unref" o = GObject.Object.ObjectUnrefMethodInfo
    ResolveMemoryMonitorMethod "watchClosure" o = GObject.Object.ObjectWatchClosureMethodInfo
    ResolveMemoryMonitorMethod "getData" o = GObject.Object.ObjectGetDataMethodInfo
    ResolveMemoryMonitorMethod "getProperty" o = GObject.Object.ObjectGetPropertyMethodInfo
    ResolveMemoryMonitorMethod "getQdata" o = GObject.Object.ObjectGetQdataMethodInfo
    ResolveMemoryMonitorMethod "setData" o = GObject.Object.ObjectSetDataMethodInfo
    ResolveMemoryMonitorMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo
    ResolveMemoryMonitorMethod l o = O.MethodResolutionFailed l o

instance (info ~ ResolveMemoryMonitorMethod t MemoryMonitor, O.MethodInfo info MemoryMonitor p) => O.IsLabelProxy t (MemoryMonitor -> p) where
    fromLabelProxy _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)

#if MIN_VERSION_base(4,9,0)
instance (info ~ ResolveMemoryMonitorMethod t MemoryMonitor, O.MethodInfo info MemoryMonitor p) => O.IsLabel t (MemoryMonitor -> p) where
#if MIN_VERSION_base(4,10,0)
    fromLabel = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#else
    fromLabel _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#endif
#endif

#endif

-- method MemoryMonitor::dup_default
-- method type : MemberFunction
-- Args : []
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "Gio", name = "MemoryMonitor"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_memory_monitor_dup_default" g_memory_monitor_dup_default ::
    IO (Ptr MemoryMonitor)

{- |
Gets a reference to the default 'GI.Gio.Interfaces.MemoryMonitor.MemoryMonitor' for the system.

/Since: 2.64/
-}
memoryMonitorDupDefault ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    m MemoryMonitor
    {- ^ __Returns:__ a new reference to the default 'GI.Gio.Interfaces.MemoryMonitor.MemoryMonitor' -}
memoryMonitorDupDefault  = liftIO $ do
    result <- g_memory_monitor_dup_default
    checkUnexpectedReturnNULL "memoryMonitorDupDefault" result
    result' <- (wrapObject MemoryMonitor) result
    return result'

#if ENABLE_OVERLOADING
#endif