
    VhI                     F   d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlmZ d dlmZmZmZ d dlmZ d d	lmZ d
Z	 d dlmZmZ  ej6                  d      5  d dlZddd        G d de      Z G d de      Zd Z e!dk(  r e         yy# e$ r dZeZY Qw xY w# 1 sw Y   ?xY w)    )absolute_importdivisionprint_functiona  
module: dconf
author:
  - "Branko Majic (@azaghal)"
short_description: Modify and read dconf database
description:
  - This module allows modifications and reading of C(dconf) database. The module is implemented as a wrapper around C(dconf)
    tool. Please see the dconf(1) man page for more details.
  - Since C(dconf) requires a running D-Bus session to change values, the module will try to detect an existing session and
    reuse it, or run the tool using C(dbus-run-session).
requirements:
  - Optionally the C(gi.repository) Python library (usually included in the OS on hosts which have C(dconf)); this will become
    a non-optional requirement in a future major release of community.general.
notes:
  - This module depends on C(psutil) Python library (version 4.0.0 and upwards), C(dconf), C(dbus-send), and C(dbus-run-session)
    binaries. Depending on distribution you are using, you may need to install additional packages to have these available.
  - This module uses the C(gi.repository) Python library when available for accurate comparison of values in C(dconf) to values
    specified in Ansible code. C(gi.repository) is likely to be present on most systems which have C(dconf) but may not be
    present everywhere. When it is missing, a simple string comparison between values is used, and there may be false positives,
    that is, Ansible may think that a value is being changed when it is not. This fallback will be removed in a future version
    of this module, at which point the module will stop working on hosts without C(gi.repository).
  - Detection of existing, running D-Bus session, required to change settings using C(dconf), is not 100% reliable due to
    implementation details of D-Bus daemon itself. This might lead to running applications not picking-up changes on-the-fly
    if options are changed using Ansible and C(dbus-run-session).
  - Keep in mind that the C(dconf) CLI tool, which this module wraps around, utilises an unusual syntax for the values (GVariant).
    For example, if you wanted to provide a string value, the correct syntax would be O(value="'myvalue'") - with single quotes
    as part of the Ansible parameter value.
  - When using loops in combination with a value like V("[('xkb', 'us'\), ('xkb', 'se'\)]"), you need to be aware of possible
    type conversions. Applying a filter V({{ item.value | string }}) to the parameter variable can avoid potential conversion
    problems.
  - The easiest way to figure out exact syntax/value you need to provide for a key is by making the configuration change in
    application affected by the key, and then having a look at value set using commands C(dconf dump /path/to/dir/) or C(dconf
    read /path/to/key).
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  key:
    type: str
    required: true
    description:
      - A dconf key to modify or read from the dconf database.
  value:
    type: raw
    required: false
    description:
      - Value to set for the specified dconf key. Value should be specified in GVariant format. Due to complexity of this
        format, it is best to have a look at existing values in the dconf database.
      - Required for O(state=present).
      - Although the type is specified as "raw", it should typically be specified as a string. However, boolean values in
        particular are handled properly even when specified as booleans rather than strings (in fact, handling booleans properly
        is why the type of this parameter is "raw").
  state:
    type: str
    required: false
    default: present
    choices: ['read', 'present', 'absent']
    description:
      - The action to take upon the key/value.
z
value:
  description: Value associated with the requested key.
  returned: success, state was "read"
  type: str
  sample: "'Default'"
a  
- name: Configure available keyboard layouts in Gnome
  community.general.dconf:
    key: "/org/gnome/desktop/input-sources/sources"
    value: "[('xkb', 'us'), ('xkb', 'se')]"
    state: present

- name: Read currently available keyboard layouts in Gnome
  community.general.dconf:
    key: "/org/gnome/desktop/input-sources/sources"
    state: read
  register: keyboard_layouts

- name: Reset the available keyboard layouts in Gnome
  community.general.dconf:
    key: "/org/gnome/desktop/input-sources/sources"
    state: absent

- name: Configure available keyboard layouts in Cinnamon
  community.general.dconf:
    key: "/org/gnome/libgnomekbd/keyboard/layouts"
    value: "['us', 'se']"
    state: present

- name: Read currently available keyboard layouts in Cinnamon
  community.general.dconf:
    key: "/org/gnome/libgnomekbd/keyboard/layouts"
    state: read
  register: keyboard_layouts

- name: Reset the available keyboard layouts in Cinnamon
  community.general.dconf:
    key: "/org/gnome/libgnomekbd/keyboard/layouts"
    state: absent

- name: Disable desktop effects in Cinnamon
  community.general.dconf:
    key: "/org/cinnamon/desktop-effects"
    value: "false"
    state: present
N)AnsibleModule)has_respawnedprobe_interpreters_for_modulerespawn_module)	to_native)depszgi.repository.GLib)VariantGErrorpsutilc                   "    e Zd ZdZd Zd Zd Zy)DBusWrapperas  
    Helper class that can be used for running a command with a working D-Bus
    session.

    If possible, command will be run against an existing D-Bus session,
    otherwise the session will be spawned via dbus-run-session.

    Example usage:

    dbus_wrapper = DBusWrapper(ansible_module)
    dbus_wrapper.run_command(["printenv", "DBUS_SESSION_BUS_ADDRESS"])
    c                     || _         | j                         | _        | j                  #| j                   j                  dd      | _        yy)z
        Initialises an instance of the class.

        :param module: Ansible module instance used to signal failures and run commands.
        :type module: AnsibleModule
        Nzdbus-run-sessionTrequired)module_get_existing_dbus_sessiondbus_session_bus_addressget_bin_pathdbus_run_session_cmd)selfr   s     k/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/dconf.py__init__zDBusWrapper.__init__   sO      )-(G(G(I% ((0(,(@(@AS^b(@(cD% 1    c                    t        j                         }| j                  j                  d|z         t	        j
                         D ]  }	 t	        j                  |      }|j                         \  }}}||k(  rd|j                         v r|j                         d   }| j                  j                  d|z         | j                  j                  dd      }|d|z  dd	d
g}| j                  j                  |      \  }	}}|	dk(  r"| j                  j                  d|z         |c S  | j                  j                  d       y# t        j                  $ r Y t        j                  $ r Y +w xY w)z
        Detects and returns an existing D-Bus session bus address.

        :returns: string -- D-Bus session bus address. If a running D-Bus session was not detected, returns None.
        z9Trying to detect existing D-Bus user session for user: %dDBUS_SESSION_BUS_ADDRESSz1Found D-Bus user session candidate at address: %sz	dbus-sendTr   z--address=%sz--type=signal/zcom.example.testr   z>Verified D-Bus user session candidate as usable at address: %szDFailed to find running D-Bus user session, will use dbus-run-sessionN)osgetuidr   debugr   pidsProcessuidsenvironr   run_commandAccessDeniedNoSuchProcess)
r   uidpidprocessprocess_real_uiddummy"dbus_session_bus_address_candidatedbus_send_cmdcommandrcs
             r   r   z&DBusWrapper._get_existing_dbus_session   sq    iik
 	UX[[\;;= 	C ..-18. %#s*/IW__M^/^9@9JKe9f6KK%%&Y\~&~$(KK$<$<[SW$<$XM,n?a.acrtw  zL  MG'+{{'>'>w'G$BuQw))*j  nP  +P  QAA	. 	`a && '' s   CEE3E32E3c                 x   | j                   {| j                  j                  d       | j                  g|z   }| j                  j	                  |      \  }}}| j                   T|dk(  rO| j                  j                  d|z         n/d| j                   i}| j                  j	                  ||      \  }}}|||fS )a  
        Runs the specified command within a functional D-Bus session. Command is
        effectively passed-on to AnsibleModule.run_command() method, with
        modification for using dbus-run-session if necessary.

        :param command: Command to run, including parameters. Each element of the list should be a string.
        :type module: list

        :returns: tuple(result_code, standard_output, standard_error) -- Result code, standard output, and standard error from running the command.
        z4Using dbus-run-session wrapper for running commands.   zMFailed to run passed-in command, dbus-run-session faced an internal error: %smsgr   )environ_update)r   r   r"   r   r'   	fail_json)r   r1   r2   outerrextra_environments         r   r'   zDBusWrapper.run_command   s     ((0KKTU001G;G;;227;LBS,,4s%%*y|*%  A!;T=Z=Z [;;227K\2]LBS3|r   N)__name__
__module____qualname____doc__r   r   r'    r   r   r   r      s    d&(Tr   r   c                   6    e Zd ZddZed        Zd Zd Zd Zy)DconfPreferencec                 d    || _         || _        | j                   j                  dd      | _        y)aG  
        Initialises instance of the class.

        :param module: Ansible module instance used to signal failures and run commands.
        :type module: AnsibleModule

        :param check_mode: Specify whether to only check if a change should be made or if to actually make a change.
        :type check_mode: bool
        dconfTr   N)r   
check_moder   	dconf_bin)r   r   rE   s      r   r   zDconfPreference.__init__   s-     $11'D1Ir   c                     | y	 t        j                  d|       }t        j                  |j                         |      }||k(  S # t        $ r | |k(  cY S w xY w)a  Compare two string GVariant representations for equality.

        Assumes `canonical_value` is "canonical" in the sense that the type of
        the variant is specified explicitly if it cannot be inferred; this is
        true for textual representations of variants generated by the `dconf`
        command. The type of `canonical_value` is used to parse `user_value`,
        so the latter does not need to be explicitly typed.

        Returns True if the two values are equal.
        NF)r   parseget_typer   )canonical_value
user_valuevariant1variant2s       r   variants_are_equalz"DconfPreference.variants_are_equal  sb     " 	1}}T?;H}}X%6%6%8*EHx'' 	1"j00	1s   >A AAc                     | j                   d|g}| j                  j                  |      \  }}}|dk7  r!| j                  j                  d|z  ||       |dk(  rd}|S |j	                  d      }|S )a  
        Retrieves current value associated with the dconf key.

        If an error occurs, a call will be made to AnsibleModule.fail_json.

        :returns: string -- Value assigned to the provided key. If the value is not set for specified key, returns None.
        readr   z3dconf failed while reading the value with error: %sr6   r9   r:    N
)rF   r   r'   r8   rstrip)r   keyr1   r2   r9   r:   values          r   rP   zDconfPreference.read&  s     >>63/{{..w7C7KK!!&[^a&a&)&) " + "9E  JJt$Er   c                 .   | j                  | j                  |      |      ry| j                  ry| j                  d||g}t	        | j
                        }|j                  |      \  }}}|dk7  r'| j
                  j                  d|d|d|||       y)	a  
        Writes the value for specified key.

        If an error occurs, a call will be made to AnsibleModule.fail_json.

        :param key: dconf key for which the value should be set. Should be a full path.
        :type key: str

        :param value: Value to set for the specified dconf key. Should be specified in GVariant format.
        :type value: str

        :returns: bool -- True if a change was made, False if no change was required.
        FTwriter   zdconf failed while writing key z, value z with error: rQ   )rN   rP   rE   rF   r   r   r'   r8   )r   rU   rV   r1   dbus_wrapperr2   r9   r:   s           r   rX   zDconfPreference.write>  s      ""499S>59__ >>7C7 #4;;/#//8C7KK!!fikpru&v&)&) " +
 r   c                    | j                  |      }|y| j                  ry| j                  d|g}t        | j                        }|j                  |      \  }}}|dk7  r!| j                  j                  d|z  ||       y)aV  
        Returns value for the specified key (removes it from user configuration).

        If an error occurs, a call will be made to AnsibleModule.fail_json.

        :param key: dconf key to reset. Should be a full path.
        :type key: str

        :returns: bool -- True if a change was made, False if no change was required.
        FTresetr   z5dconf failed while resetting the value with error: %srQ   )rP   rE   rF   r   r   r'   r8   )r   rU   current_valuer1   rY   r2   r9   r:   s           r   r[   zDconfPreference.resetc  s     		#  __ >>7C0 #4;;/#//8C7KK!!&]`c&c&)&) " +
 r   N)F)	r<   r=   r>   r   staticmethodrN   rP   rX   r[   r@   r   r   rB   rB      s,    J  1 1,0#J$r   rB   c                  ^   t        t        t        dg d      t        ddd      t        dd d	      
      ddddgfg      } t        Ut               r*| j	                  t
        dt        j                  d       g d}t        |t
              }|rt        |       | j                  d   et        | j                  d   t              r!| j                  d   rdnd| j                  d<   n't        | j                  d   d      | j                  d<   t        | j                  d       t        j                   |        t#        | | j$                        }| j                  d   dk(  r2|j'                  | j                  d         }| j)                  d|       y | j                  d   dk(  r?|j+                  | j                  d   | j                  d         }| j)                  |       y | j                  d   dk(  r1|j-                  | j                  d         }| j)                  |       y y )Npresent)r_   absentrP   )defaultchoicesTstrF)r   typeno_lograw)r   ra   rd   )staterU   rV   rg   rV   )argument_specsupports_check_moderequired_ifz$ must be installed and visible from .r5   )z/usr/bin/python3z/usr/bin/python2z/usr/bin/pythontruefalsesurrogate_or_strict)errorszWARNING: The gi.repository Python library is not available; using string comparison to check value equality. This fallback will be deprecated in a future version of community.general.rP   rU   )changedrV   )rp   r`   )r   dictr   r   r8   glib_module_namesys
executabler   r	   params
isinstanceboolr
   warnr   validaterB   rE   rP   	exit_jsonrX   r[   )r   interpretersinterpreterrD   rV   rp   s         r   mainr}     s   y2OPdu=t%@	
 !i'+
F  ?!3>>3  4+ 4*,  ;' }}W)fmmG,d3/5}}W/EV7FMM'"%.g&/D&FFMM'" K	L
 	MM& FF$5$56E }}W'

6==/0e4	w	9	,++fmmE2FMM'4JK)	w	8	+++fmmE23) 
,r   __main__)"
__future__r   r   r   rd   __metaclass__DOCUMENTATIONRETURNEXAMPLESr    rs   ansible.module_utils.basicr   #ansible.module_utils.common.respawnr   r   r	   +ansible.module_utils.common.text.convertersr
   :ansible_collections.community.general.plugins.module_utilsr   rr   gi.repository.GLibr   r   ImportErrorAttributeErrordeclarer   objectr   rB   r}   r<   r@   r   r   <module>r      s    A @?B
(V 
 
 4 
 B K' 2
 T\\( b& bJJf JZK*\ zF Q
  GF s   B B	BBB 