LeenO computo metrico con LibreOffice  3.22.0
Il software libero per la gestione di computi metrici e contabilità lavori.
LeenoDebug.py
Vai alla documentazione di questo file.
1 '''
2 Modulo di debug per LeenO
3 permette il debug attraverso l' IDE Eric6 (o simili)
4 '''
5 import sys
6 import os
7 import inspect
8 import subprocess
9 import time
10 import atexit
11 
12 import importlib
13 
14 from os import listdir
15 from os.path import isfile, join
16 
17 import uno
18 from com.sun.star.connection import NoConnectException
19 
20 # openoffice path
21 # adapt to your system
22 if sys.platform == 'linux' or sys.platform == 'darwin':
23  _sofficePath = '/usr/lib/libreoffice/program'
24  calc = 'scalc'
25 else:
26  _sofficePath = 'C:\\Program Files\\LibreOffice\\program'
27  calc = 'scalc.exe'
28 
29 OPENOFFICE_PORT = 8100
30 OPENOFFICE_PATH = _sofficePath
31 OPENOFFICE_BIN = os.path.join(OPENOFFICE_PATH, calc)
32 OPENOFFICE_LIBPATH = OPENOFFICE_PATH
33 
34 class OORunner:
35  """
36  Start, stop, and connect to OpenOffice.
37  """
38  def __init__(self, port=OPENOFFICE_PORT):
39  """ Create OORunner that connects on the specified port. """
40  self.port = port
41 
42 
43  def connect(self, no_startup=False):
44  """
45  Connect to OpenOffice.
46  If a connection cannot be established try to start OpenOffice.
47  """
48  localContext = uno.getComponentContext()
49  resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
50  context = None
51  did_start = False
52 
53  n = 0
54  while n < 6:
55  try:
56  context = resolver.resolve("uno:socket,host=localhost,port=%d;urp;StarOffice.ComponentContext" % self.port)
57  break
58  except NoConnectException:
59  pass
60 
61  # If first connect failed then try starting OpenOffice.
62  if n == 0:
63  # Exit loop if startup not desired.
64  if no_startup:
65  break
66  self.startup()
67  did_start = True
68 
69  # Pause and try again to connect
70  time.sleep(1)
71  n += 1
72 
73  if not context:
74  raise Exception("Failed to connect to OpenOffice on port %d" % self.port)
75 
76  desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
77 
78  if not desktop:
79  raise Exception("Failed to create OpenOffice desktop on port %d" % self.port)
80 
81  if did_start:
82  _started_desktops[self.port] = desktop
83 
84  return {'context': context, 'desktop': desktop}
85 
86 
87  def startup(self):
88  """
89  Start a headless instance of OpenOffice.
90  """
91  args = [OPENOFFICE_BIN,
92  '--accept=socket,host=localhost,port=%d;urp;StarOffice.ServiceManager' % self.port,
93  '--norestore',
94  '--nofirststartwizard',
95  '--nologo',
96  #` '--headless',
97  ]
98  env = os.environ.copy()
99  # env = {'PATH' : '/bin:/usr/bin:%s' % OPENOFFICE_PATH, 'PYTHONPATH' : OPENOFFICE_LIBPATH, }
100 
101  try:
102  # Open connection to server
103  child = subprocess.Popen(args=args, env=env, start_new_session=False)
104  except Exception as e:
105  raise Exception("Failed to start OpenOffice on port %d: %s" % (self.port, e))
106 
107  #if pid <= 0:
108  if child is None:
109  raise Exception("Failed to start OpenOffice on port %d" % self.port)
110 
111 
112 
113  def shutdown(self):
114  """
115  Shutdown OpenOffice.
116  """
117  try:
118  if _started_desktops.get(self.port):
119  _started_desktops[self.port].terminate()
120  del _started_desktops[self.port]
121  except Exception:
122  pass
123 
124 
125 
126 # Keep track of started desktops and shut them down on exit.
127 _started_desktops = {}
128 
129 def _shutdown_desktops():
130  """ Shutdown all OpenOffice desktops that were started by the program. """
131  for port, desktop in _started_desktops.items():
132  try:
133  if desktop:
134  desktop.terminate()
135  except Exception:
136  pass
137 
138 atexit.register(_shutdown_desktops)
139 
140 # builtins dictionary in portable way... sigh
141 if type(__builtins__) == type(sys):
142  bDict = __builtins__.__dict__
143 else:
144  bDict = __builtins__
145 
146 
148  '''
149  This function reload all Leeno modules found in pythonpath
150  '''
151  # get our pythonpath
152  myPath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
153  myPath = os.path.join(myPath, "pythonpath")
154 
155  # we need a listing of modules. We look at pythonpath ones
156  pythonFiles = [f[: -3] for f in listdir(myPath) if isfile(join(myPath, f)) and f.endswith(".py")]
157  for f in pythonFiles:
158  print("Loading module:", f)
159  module = importlib.import_module(f)
160 
161  # add to global dictionary, so it's available everywhere
162  bDict[f] = module
163 
164  # reload the module
165  importlib.reload(module)
166 
167 
168 
169 # create the runner object
170 runner = OORunner()
171 
172 # start libreoffice and get its context and desktop objects
173 lo = runner.connect()
174 
175 # add our path and pythonpath subpath to our python path
176 leenoPath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
177 sys.path.append(leenoPath)
178 leenoPath = os.path.join(leenoPath, "pythonpath")
179 sys.path.append(leenoPath)
180 
181 # if we don't do so, we'll get a null current document
182 frames = lo['desktop'].getFrames()
183 if len(frames) > 0:
184  frames[0]. activate()
185 
186 '''
187 Poi sembra strano quando dico che il python è stato studiato con i piedi...
188 
189 By default, when in the __main__ module, __builtins__ is the built-in module __builtin__ (note: no 's'); when in any other module,
190 __builtins__ is an alias for the dictionary of the __builtin__ module itself.
191 Note that in Python3, the module __builtin__ has been renamed to builtins to avoid some of this confusion.
192 '''
193 
194 # setup our context for LeenO
195 bDict['__global_context__'] = lo['context']
196 
197 # load LeenO modules
199 
200 desktop = lo['desktop']
201 
202 
203 
204 def loadDocument(filename):
205  url = uno.systemPathToFileUrl(filename)
206  oDoc = desktop.loadComponentFromURL(url, "_blank", 0, tuple())
207  return oDoc
208 
209 # ############################################################################
210 from io import StringIO
211 import xml.etree.ElementTree as ET
212 import LeenoImport
213 
214 #filename = "/storage/Scaricati/COMPUTI_METRICI/LEENO/TESTS/prezzario2019standardsix.xml"
215 
216 filename = "/storage/Scaricati/COMPUTI_METRICI/LEENO/TESTS/TestPdfExport.ods"
217 oDoc = loadDocument(filename)
218 
219 sheet = oDoc.Sheets[0]
220 pageStyleName = sheet.PageStyle
221 pageStyles = oDoc.StyleFamilies.getByName('PageStyles')
222 pageStyle = pageStyles.getByName(pageStyleName)
223 footer = pageStyle.RightPageFooterContent
224 rightText = footer.RightText
225 
226 pattern = '[PAGINA]'
227 pos = rightText.String.find(pattern)
228 cursor = rightText.createTextCursor()
229 cursor.collapseToStart()
230 cursor.goRight(pos, False)
231 cursor.goRight(len(pattern), True)
232 cursor.String = ''
233 oField = oDoc.createInstance("com.sun.star.text.TextField.PageCount")
234 cursor.collapseToStart()
235 rightText.insertTextContent(cursor, oField, False)
236 
237 #fields = rightText.TextFields
238 #field0 = fields[0]
239 #anchor = field0.Anchor
240 
241 #oField = oDoc.createInstance("com.sun.star.text.TextField.DateTime")
242 #oField.IsFixed = True
243 #oField.NumberFormat = FindCreateNumberFormatStyle("DD. MMMM YYYY", oDoc)
244 #rightText.insertTextContent(rightText.getEnd(), oField, False)
245 
246 pageStyle.RightPageFooterContent = footer
247 
248 
249 
250 
251 
252 import LeenoSettings
254 
255 print("\nDONE\n")
python.LeenoDebug.OORunner.startup
def startup(self)
Definition: LeenoDebug.py:87
python.LeenoDebug.loadDocument
def loadDocument(filename)
Definition: LeenoDebug.py:204
python.LeenoDebug.reloadLeenoModules
def reloadLeenoModules()
Definition: LeenoDebug.py:147
python.LeenoDebug.OORunner.shutdown
def shutdown(self)
Definition: LeenoDebug.py:113
python.LeenoDebug.OORunner.connect
def connect(self, no_startup=False)
Definition: LeenoDebug.py:43
LeenoSettings.MENU_PrintSettings
def MENU_PrintSettings()
Definition: LeenoSettings.py:277
python.LeenoDebug.OORunner.__init__
def __init__(self, port=OPENOFFICE_PORT)
Definition: LeenoDebug.py:38
python.LeenoDebug.OORunner
Definition: LeenoDebug.py:34
python.LeenoDebug.OORunner.port
port
Definition: LeenoDebug.py:40