Copy shape's hex color to clipboard

From The Document Foundation Wiki
Jump to navigation Jump to search
Other languages:
English • ‎italiano

Description

It is useful to be able to copy an attribute of a currently selected shape or object to the clipboard. To that end, it is quite useful to use Python, since it is easy to find and import a popular library for copying a string to the clipboard, which would be less trivial to do using functions or libraries of LibreOffice Basic. (Andrew Pitonyak's OOME book v3[1] does include an example of copying to clipboard in LO Basic on p. 267 though.)

In the below macro, the currently selected object is accessed using XSCRIPTCONTEXT.getDocument().CurrentSelection[0] i.e. the zeroth element of the array of selected objects. A shape such as a com.sun.star.drawing.RectangleShape will have the attribute FillColor[2]. The color is a single long integer, with the following mathematical definition:[3][4][5]

Color Value [math]\displaystyle{ =R*2^{16} + G*2^8 + B*2^0 }[/math]

where [math]\displaystyle{ R,G,B }[/math] are 8-bit values (between 0-255) for red, green, blue. Hence, a function has to be created making use moduli and other mathematical operations to extract to the more conventional RGB standard and then to hex color code.

After accessing the FillColor attribute, the script makes use of the pyperclip[6] module for copying to clipboard. To install pyperclip, in run

pip3 install --user pyperclip

You may also need to add path of packages if LibreOffice does not find your pyperclip installation, for example as such:

import sys
sys.path.append('~/.local/lib/python3.8/site-packages/')
import pyperclip

Code

Python

# -*- coding: utf-8 -*-
import uno
from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS

# Adjust and uncomment the following if the path of your packages does not load:
#import sys
#sys.path.append('~/.local/lib/python3.8/site-packages/')
import pyperclip


def copy_hex_color(*args):      # Must include '*args' in func. definition
    '''LO macro to extract the hex color of a selected shape's FillColor attribute to the clipboard.'''

    thisComponent = XSCRIPTCONTEXT.getDocument()

    try:
        sel = thisComponent.CurrentSelection[0]   # get currently selected shape
        hex_color = cval2hex(sel.FillColor)
        pyperclip.copy(hex_color)
        #msgbox( 'Copied "' + str(sel.FillColor) + '" as "' + pyperclip.paste() + '" !' )  # comment out for testing
    except:
        msgbox('Exception occured!')


def cval2hex(c):
    '''Convert Color Value to hex.'''

    # Extract 8-bit (0-255) RGB from Color Value
    red   = ( c - c % 2**16 ) /2**16;
    green = ( c % 2**16 - c % 2**8 ) /2**8;
    blue  = ( c % 2**8 ) /2**0;

    h = '#%02x%02x%02x' % (int(red), int(green), int(blue))  # RGB to hex
    return h[1:]  # exclude hash sign in return string


def rgb2cval(r,g,b):
    '''Returns Color Value from 8-bit (0-255) RGB components'''
    return (r * 2**16) + (g * 2**8) + (b * 2**0)


def msgbox(message, title='LibreOffice', buttons=MSG_BUTTONS.BUTTONS_OK, type_msg='infobox'):
    '''https://wiki.documentfoundation.org/Macros/Python_Guide/Useful_functions#MsgBox'''
    '''Create message box
       type_msg: infobox, warningbox, errorbox, querybox, messbox
       https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1awt_1_1XMessageBoxFactory.html
    '''
    toolkit = create_instance('com.sun.star.awt.Toolkit')
    parent = toolkit.getDesktopWindow()
    mb = toolkit.createMessageBox(parent, type_msg, buttons, title, str(message))
    return mb.execute()


def create_instance(name, with_context=False):
    '''https://wiki.documentfoundation.org/Macros/Python_Guide/Useful_functions#Create_instances'''
    CTX = uno.getComponentContext()
    SM = CTX.getServiceManager()
    if with_context:
        instance = SM.createInstanceWithContext(name, CTX)
    else:
        instance = SM.createInstance(name)
    return instance


# Make it such that only the copy_hex_color function will be visible in navigation tree of LO macros
g_exportedScripts = (copy_hex_color,)

LO Basic

tbc

Download ODP file

Notes