calc: on editing invalidation of view with different zoom is wrong
[LibreOffice.git] / wizards / source / scriptforge / python / ScriptForgeHelper.py
blobe228095053df48a41f2a21e29a0708295305de0e
1 # -*- coding: utf-8 -*-
3 # Copyright 2019-2022 Jean-Pierre LEDURE, Rafael LIMA, Alain ROMEDENNE
5 # ======================================================================================================================
6 # === The ScriptForge library and its associated libraries are part of the LibreOffice project. ===
7 # === Full documentation is available on https://help.libreoffice.org/ ===
8 # ======================================================================================================================
10 # ScriptForge is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 # ScriptForge is free software; you can redistribute it and/or modify it under the terms of either (at your option):
16 # 1) The Mozilla Public License, v. 2.0. If a copy of the MPL was not
17 # distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/ .
19 # 2) The GNU Lesser General Public License as published by
20 # the Free Software Foundation, either version 3 of the License, or
21 # (at your option) any later version. If a copy of the LGPL was not
22 # distributed with this file, see http://www.gnu.org/licenses/ .
24 """
25 Collection of Python helper functions called from the ScriptForge Basic libraries
26 to execute specific services that are not or not easily available from Basic directly.
27 When relevant, the methods present in the ScripForge Python module might call the
28 functions below for compatibility reasons.
29 """
31 import getpass
32 import os
33 import platform
34 import hashlib
35 import filecmp
36 import webbrowser
37 import json
40 class _Singleton(type):
41 """
42 A Singleton design pattern
43 Credits: « Python in a Nutshell » by Alex Martelli, O'Reilly
44 """
45 instances = {}
47 def __call__(cls, *args, **kwargs):
48 if cls not in cls.instances:
49 cls.instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
50 return cls.instances[cls]
53 # #################################################################
54 # Dictionary service
55 # #################################################################
57 def _SF_Dictionary__ConvertToJson(propval, indent = None) -> str:
58 # used by Dictionary.ConvertToJson() Basic method
59 """
60 Given an array of PropertyValues as argument, convert it to a JSON string
61 """
62 # Array of property values => Dict(ionary) => JSON
63 pvDict = {}
64 for pv in propval:
65 pvDict[pv.Name] = pv.Value
66 return json.dumps(pvDict, indent=indent, skipkeys=True)
69 def _SF_Dictionary__ImportFromJson(jsonstr: str): # used by Dictionary.ImportFromJson() Basic method
70 """
71 Given a JSON string as argument, convert it to a list of tuples (name, value)
72 The value must not be a (sub)dict. This doesn't pass the python-basic bridge.
73 """
74 # JSON => Dictionary => Array of tuples/lists
75 dico = json.loads(jsonstr)
76 result = []
77 for key in iter(dico):
78 value = dico[key]
79 item = value
80 if isinstance(value, dict): # check that first level is not itself a (sub)dict
81 item = None
82 elif isinstance(value, list): # check every member of the list is not a (sub)dict
83 for i in range(len(value)):
84 if isinstance(value[i], dict): value[i] = None
85 result.append((key, item))
86 return result
89 # #################################################################
90 # Exception service
91 # #################################################################
93 def _SF_Exception__PythonPrint(string: str) -> bool:
94 # used by SF_Exception.PythonPrint() Basic method
95 """
96 Write the argument to stdout.
97 If the APSO shell console is active, the argument will be displayed in the console window
98 """
99 print(string)
100 return True
103 # #################################################################
104 # FileSystem service
105 # #################################################################
107 def _SF_FileSystem__CompareFiles(filename1: str, filename2: str, comparecontents=True) -> bool:
108 # used by SF_FileSystem.CompareFiles() Basic method
110 Compare the 2 files, returning True if they seem equal, False otherwise.
111 By default, only their signatures (modification time, ...) are compared.
112 When comparecontents == True, their contents are compared.
114 try:
115 return filecmp.cmp(filename1, filename2, not comparecontents)
116 except Exception:
117 return False
120 def _SF_FileSystem__GetFilelen(systemfilepath: str) -> str: # used by SF_FileSystem.GetFilelen() Basic method
121 return str(os.path.getsize(systemfilepath))
124 def _SF_FileSystem__HashFile(filename: str, algorithm: str) -> str: # used by SF_FileSystem.HashFile() Basic method
126 Hash a given file with the given hashing algorithm
127 cfr. https://www.pythoncentral.io/hashing-files-with-python/
128 Example
129 hash = _SF_FileSystem__HashFile('myfile.txt','MD5')
131 algo = algorithm.lower()
132 try:
133 if algo in hashlib.algorithms_guaranteed:
134 BLOCKSIZE = 65535 # Provision for large size files
135 if algo == 'md5':
136 hasher = hashlib.md5()
137 elif algo == 'sha1':
138 hasher = hashlib.sha1()
139 elif algo == 'sha224':
140 hasher = hashlib.sha224()
141 elif algo == 'sha256':
142 hasher = hashlib.sha256()
143 elif algo == 'sha384':
144 hasher = hashlib.sha384()
145 elif algo == 'sha512':
146 hasher = hashlib.sha512()
147 else:
148 return ''
149 with open(filename, 'rb') as file: # open in binary mode
150 buffer = file.read(BLOCKSIZE)
151 while len(buffer) > 0:
152 hasher.update(buffer)
153 buffer = file.read(BLOCKSIZE)
154 return hasher.hexdigest()
155 else:
156 return ''
157 except Exception:
158 return ''
161 def _SF_FileSystem__Normalize(systemfilepath: str) -> str:
162 # used by SF_FileSystem.Normalize() Basic method
164 Normalize a pathname by collapsing redundant separators and up-level references so that
165 A//B, A/B/, A/./B and A/foo/../B all become A/B.
166 On Windows, it converts forward slashes to backward slashes.
168 return os.path.normpath(systemfilepath)
171 # #################################################################
172 # Platform service
173 # #################################################################
175 def _SF_Platform(propertyname: str): # used by SF_Platform Basic module
177 Switch between SF_Platform properties (read the documentation about the ScriptForge.Platform service)
179 pf = Platform()
180 if propertyname == 'Architecture':
181 return pf.Architecture
182 elif propertyname == 'ComputerName':
183 return pf.ComputerName
184 elif propertyname == 'CPUCount':
185 return pf.CPUCount
186 elif propertyname == 'CurrentUser':
187 return pf.CurrentUser
188 elif propertyname == 'Machine':
189 return pf.Machine
190 elif propertyname == 'OSName':
191 return pf.OSName
192 elif propertyname == 'OSPlatform':
193 return pf.OSPlatform
194 elif propertyname == 'OSRelease':
195 return pf.OSRelease
196 elif propertyname == 'OSVersion':
197 return pf.OSVersion
198 elif propertyname == 'Processor':
199 return pf.Processor
200 elif propertyname == 'PythonVersion':
201 return pf.PythonVersion
202 else:
203 return None
206 class Platform(object, metaclass = _Singleton):
207 @property
208 def Architecture(self): return platform.architecture()[0]
210 @property # computer's network name
211 def ComputerName(self): return platform.node()
213 @property # number of CPU's
214 def CPUCount(self): return os.cpu_count()
216 @property
217 def CurrentUser(self):
218 try:
219 return getpass.getuser()
220 except Exception:
221 return ''
223 @property # machine type e.g. 'i386'
224 def Machine(self): return platform.machine()
226 @property # system/OS name e.g. 'Darwin', 'Java', 'Linux', ...
227 def OSName(self): return platform.system().replace('Darwin', 'macOS')
229 @property # underlying platform e.g. 'Windows-10-...'
230 def OSPlatform(self): return platform.platform(aliased = True)
232 @property # system's release e.g. '2.2.0'
233 def OSRelease(self): return platform.release()
235 @property # system's version
236 def OSVersion(self): return platform.version()
238 @property # real processor name e.g. 'amdk'
239 def Processor(self): return platform.processor()
241 @property # Python major.minor.patchlevel
242 def PythonVersion(self): return 'Python ' + platform.python_version()
245 # #################################################################
246 # Session service
247 # #################################################################
249 def _SF_Session__OpenURLInBrowser(url: str): # Used by SF_Session.OpenURLInBrowser() Basic method
251 Display url using the default browser
253 try:
254 webbrowser.open(url, new = 2)
255 finally:
256 return None
259 # #################################################################
260 # String service
261 # #################################################################
263 def _SF_String__HashStr(string: str, algorithm: str) -> str: # used by SF_String.HashStr() Basic method
265 Hash a given UTF-8 string with the given hashing algorithm
266 Example
267 hash = _SF_String__HashStr('This is a UTF-8 encoded string.','MD5')
269 algo = algorithm.lower()
270 try:
271 if algo in hashlib.algorithms_guaranteed:
272 ENCODING = 'utf-8'
273 bytestring = string.encode(ENCODING) # Hashing functions expect bytes, not strings
274 if algo == 'md5':
275 hasher = hashlib.md5(bytestring)
276 elif algo == 'sha1':
277 hasher = hashlib.sha1(bytestring)
278 elif algo == 'sha224':
279 hasher = hashlib.sha224(bytestring)
280 elif algo == 'sha256':
281 hasher = hashlib.sha256(bytestring)
282 elif algo == 'sha384':
283 hasher = hashlib.sha384(bytestring)
284 elif algo == 'sha512':
285 hasher = hashlib.sha512(bytestring)
286 else:
287 return ''
288 return hasher.hexdigest()
289 else:
290 return ''
291 except Exception:
292 return ''
295 # #################################################################
296 # lists the scripts, that shall be visible inside the Basic/Python IDE
297 # #################################################################
299 g_exportedScripts = ()
301 if __name__ == "__main__":
302 print(_SF_Platform('Architecture'))
303 print(_SF_Platform('ComputerName'))
304 print(_SF_Platform('CPUCount'))
305 print(_SF_Platform('CurrentUser'))
306 print(_SF_Platform('Machine'))
307 print(_SF_Platform('OSName'))
308 print(_SF_Platform('OSPlatform'))
309 print(_SF_Platform('OSRelease'))
310 print(_SF_Platform('OSVersion'))
311 print(_SF_Platform('Processor'))
312 print(_SF_Platform('PythonVersion'))
314 print(hashlib.algorithms_guaranteed)
315 print(_SF_FileSystem__HashFile('/opt/libreoffice7.3/program/libbootstraplo.so', 'md5'))
316 print(_SF_FileSystem__HashFile('/opt/libreoffice7.3/share/Scripts/python/Capitalise.py', 'sha512'))
317 print(_SF_FileSystem__Normalize('A/foo/../B/C/./D//E'))
319 print(_SF_String__HashStr('œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ“‘åß∂ƒ©˙∆˚¬', 'MD5')) # 616eb9c513ad07cd02924b4d285b9987
321 # _SF_Session__OpenURLInBrowser('https://docs.python.org/3/library/webbrowser.html')
323 js = """
324 {"firstName": "John","lastName": "Smith","isAlive": true,"age": 27,
325 "address": {"streetAddress": "21 2nd Street","city": "New York","state": "NY","postalCode": "10021-3100"},
326 "phoneNumbers": [{"type": "home","number": "212 555-1234"},{"type": "office","number": "646 555-4567"}],
327 "children": ["Q", "M", "G", "T"],"spouse": null}
329 arr = _SF_Dictionary__ImportFromJson(js)
330 print(arr)