/
main.py
376 lines (309 loc) · 12.6 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import os
import uno
import unohelper
from com.sun.star.task import XJobExecutor
from com.sun.star.beans import UnknownPropertyException
import config
import gantt
import messages
import tools
class Main(unohelper.Base, XJobExecutor):
def __init__ (self, ctx):
self.ctx = ctx
self.smgr = self.ctx.ServiceManager
self.desktop = self.ctx.ServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop",
self.ctx
)
self.db_ctx = self.smgr.createInstanceWithContext(
"com.sun.star.sdb.DatabaseContext",
self.ctx
)
self.dispatcher = self.smgr.createInstanceWithContext(
"com.sun.star.frame.DispatchHelper",
self.ctx
)
def update_indexes(self, document):
self.dispatcher.executeDispatch(document.getCurrentController(),
".uno:UpdateAll", "", 0, ())
def open_document(self, path, hidden=True, read_only=False):
struct_hidden = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
struct_hidden.Name = "Hidden"
struct_hidden.Value = hidden
struct_read_only = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
struct_read_only.Name = "ReadOnly"
struct_read_only.Value = read_only
return self.desktop.loadComponentFromURL(
uno.systemPathToFileUrl(path),
"_blank",
0,
tuple([struct_hidden, struct_read_only])
)
def update_sections_link(self, document, dst_dir):
"""For each linked section of src, replace the filename by dst_path"""
sections = document.getTextSections()
for i in range(sections.getCount()):
section = sections.getByIndex(i)
if not section.FileLink.FileURL:
continue
url = uno.systemPathToFileUrl(os.path.join(
dst_dir,
os.path.basename(section.FileLink.FileURL)
))
section.FileLink.FileURL = url
document.store()
def print_document(self, document):
if not tools.has_database(document):
messages.error(
document.CurrentController.Frame.ContainerWindow,
str("Merci de configurer l'étude."),
"Etude non configurée"
)
return
"""
if path.endswith("PC.odt"):
self.insert_project_manager_data(document)
self.insert_methodology(document)
"""
stg = document.createInstance("com.sun.star.text.DocumentSettings")
db_name = stg.CurrentDatabaseDataSource
table_name = stg.CurrentDatabaseCommand
output_folder = os.path.join(
os.path.dirname(tools.get_document_path(document)),
config.PDF_DIRNAME
)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
self.update_indexes(document)
document.store() # For the index update to be taken into account
# Fill field from db and export as PDF
mail_merge = self.smgr.createInstanceWithContext(
"com.sun.star.text.MailMerge",
self.ctx
)
mail_merge.DocumentURL = document.URL
mail_merge.DataSourceName = db_name
mail_merge.CommandType = uno.getConstantByName("com.sun.star.sdb.CommandType.TABLE")
mail_merge.Command = table_name
mail_merge.OutputType = uno.getConstantByName("com.sun.star.text.MailMergeType.FILE")
mail_merge.OutputURL = uno.systemPathToFileUrl(output_folder)
mail_merge.SaveFilter = "writer_pdf_Export"
mail_merge.SaveFilterData = tuple([])
mail_merge.execute(())
# Rename PDF file
pdf_path = os.path.join(output_folder, tools.get_document_name(document) + "0.pdf")
new_path = pdf_path.replace("0.pdf", ".pdf")
try:
os.rename(pdf_path, new_path)
except OSError: # (Windows) The file already exists
os.remove(new_path)
os.rename(pdf_path, new_path)
self.open_document(new_path, hidden=False, read_only=True)
def register_db(self, ods_path, db_path, db_name):
if os.path.isfile(db_path):
return
if self.db_ctx.hasByName(db_name):
raise ValueError("The database {} already exists.".format(db_name))
db_folder_path = os.path.dirname(ods_path)
db_url = uno.systemPathToFileUrl(db_path)
db_folder_url = uno.systemPathToFileUrl(db_folder_path)
data_src = self.smgr.createInstanceWithContext(
"com.sun.star.sdb.DataSource",
self.ctx
)
data_src.URL = "sdbc:calc:" + ods_path
data_src.DatabaseDocument.storeAsURL(db_url, ())
self.db_ctx.registerObject(db_name, data_src)
data_src.DatabaseDocument.close(True)
def link_db(self, document, db_name, table_name):
# Update db fields url
fields_enum = document.getTextFields().createEnumeration()
while fields_enum.hasMoreElements():
field = fields_enum.nextElement()
master_field = field.getTextFieldMaster()
# Conditional field
try:
cond = field.getPropertyValue("Condition")
cond = cond.split('.')
if len(cond) == 3: # db.table.field
cond[0] = db_name
field.setPropertyValue("Condition", '.'.join(cond))
except UnknownPropertyException:
pass
# Merge mail field
try:
master_field.setPropertyValue("DataBaseName", db_name)
master_field.setPropertyValue("DataTableName", table_name)
except UnknownPropertyException:
pass
# Attach the db to the document
stg = document.createInstance("com.sun.star.text.DocumentSettings")
stg.setPropertyValue("CurrentDatabaseDataSource", db_name)
stg.setPropertyValue("CurrentDatabaseCommand", table_name)
stg.setPropertyValue(
"CurrentDatabaseCommandType",
uno.getConstantByName("com.sun.star.sdb.CommandType.TABLE")
)
document.store()
def configure_project(self, document):
folder = tools.get_document_folder(document)
ods = tools.get_ods_fname(folder)
db_name_base = db_name = ods[:-4]
n = 0
# Look for an unused db name
while True:
try:
self.register_db(
os.path.join(folder, ods),
os.path.join(folder, db_name + ".odb"),
db_name
)
except ValueError:
n += 1
db_name = db_name_base + "-" + str(n)
else:
break
for tmpl in tools.get_odt_fnames(folder):
already_opened = tools.get_document_fname(document) == tmpl
odt = document if already_opened else self.open_document(os.path.join(folder, tmpl))
self.link_db(odt, db_name, tmpl[:-4])
self.update_sections_link(odt, folder)
if not already_opened:
odt.dispose()
messages.message(
document.CurrentController.Frame.ContainerWindow,
str("Les modèles ont été configurés avec succès."),
"Configuration terminée"
)
def update_gantt(self, document):
if not tools.has_database(document):
messages.error(
document.CurrentController.Frame.ContainerWindow,
str("Merci de configurer l'étude."),
"Etude non configurée"
)
return
folder = tools.get_document_folder(document)
calc = self.open_document(os.path.join(folder, tools.get_ods_fname(folder)))
try:
gantt.update(document, calc)
except Exception as e: # TODO
messages.error(
document.CurrentController.Frame.ContainerWindow,
str(e),
"Erreur Gantt"
)
else:
messages.message(
document.CurrentController.Frame.ContainerWindow,
str("Le Gantt a été mis à jour avec succès."),
"Mise à jour du Gantt terminée"
)
finally:
calc.dispose()
def update_budget_table(self, document):
folder = tools.get_document_folder(document)
calc = self.open_document(os.path.join(folder, tools.get_ods_fname(folder)))
SHEET_NAME = "Phases"
LAST_ROW_NUMBER_CELL = "J2"
LAST_COLUMN_NAME = "D"
SECTION_NAME = "BudgetEtude"
TABLE_NAME = "TableauBudgetEtude"
COL_SEP_POS_DELTAS = [900, -500, 0]
# Get data
sheet = calc.getSheets().getByName(SHEET_NAME)
last_row_number = int(sheet.getCellRangeByName(
LAST_ROW_NUMBER_CELL
).getValue())
data = sheet.getCellRangeByName("A1:{}{}".format(
LAST_COLUMN_NAME,
last_row_number
))
# Create table
if document.getTextTables().hasByName(TABLE_NAME):
table = document.getTextTables().getByName(TABLE_NAME)
table.setName(TABLE_NAME + "_")
table.dispose()
section = document.getTextSections().getByName(SECTION_NAME)
anchor = section.getAnchor()
table = document.createInstance("com.sun.star.text.TextTable")
table.setName(TABLE_NAME)
rows = data.getRows()
columns = data.getColumns()
row_count = rows.getCount()
col_count = columns.getCount()
table.initialize(row_count, col_count)
anchor.getText().insertTextContent(anchor, table, False)
# Format text
for i in range(row_count):
for j in range(col_count):
val = data.getCellByPosition(j, i).getText().getString()
cell = table.getCellByPosition(j, i)
cell.setString(val)
if i >= row_count - 2 and j == 0:
tools.superscript_cell_note(cell)
if i == 0 or i == row_count - 1 and j == 0:
tools.bold_cell(cell)
if val == "":
tools.hide_border(cell)
tools.align_cell_text(cell, row_count, i, j)
# Resize columns
pos = [
sep.value.Position + delta
for sep, delta in zip(table.TableColumnSeparators, COL_SEP_POS_DELTAS)
]
seps = [
uno.createUnoStruct("com.sun.star.text.TableColumnSeparator", p, True)
for p in pos
]
table.TableColumnSeparators = tuple(seps)
calc.dispose()
def update_methodology_table(self, document):
folder = tools.get_document_folder(document)
calc = self.open_document(os.path.join(folder, tools.get_ods_fname(folder)))
tools.update_phase_table(
document,
calc,
"TableauMéthodologie",
"VieuxTableauMéthodologie",
2
)
calc.dispose()
def update_feature_table(self, document):
folder = tools.get_document_folder(document)
calc = self.open_document(os.path.join(folder, tools.get_ods_fname(folder)))
tools.update_phase_table(
document,
calc,
"TableauFonctionnalités",
"VieuxTableauFonctionnalités",
2,
["Table Contents", "Fonctionnalités"]
)
calc.dispose()
def trigger(self, cmd):
model = self.desktop.getCurrentComponent()
try:
if cmd == "print":
self.print_document(model)
elif cmd == "configure":
self.configure_project(model)
elif cmd == "updateGantt":
self.update_gantt(model)
elif cmd == "updateBudgetTable":
self.update_budget_table(model)
elif cmd == "updateFeatureTable":
self.update_feature_table(model)
elif cmd == "updateMethodologyTable":
self.update_methodology_table(model)
else:
raise ValueError("Unknown command '{}'".format(cmd))
except Exception as e:
messages.error(
model.CurrentController.Frame.ContainerWindow,
str(e),
"System error"
)
# pythonloader looks for a static g_ImplementationHelper variable
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(Main, 'org.javelot.Main', ('com.sun.star.task.Job',),)