d86ed20927484a565becda38948790e86b0cef4e
[macros-openoffice.git] / auf-libreoffice-extension / extension / calc2moin.py
1 #!
2 # -*- coding: utf-8 -*-
3 """
4 Macro pour faciliter l'intégration des données d'une feuille de calcul
5 vers un wiki MoinMoin.
6
7 Copyright : Agence universitaire de la Francophonie
8 Licence : GNU General Public Licence, version 2
9 Auteur : Jean Christophe André
10 Date de création : septembre 2009
11 """
12 import uno
13 import unohelper
14 from com.sun.star.task import XJobExecutor
15 from com.sun.star.beans import PropertyValue
16 from com.sun.star.table.CellContentType import EMPTY, VALUE, TEXT, FORMULA
17 from com.sun.star.table.CellHoriJustify import STANDARD, LEFT, CENTER, RIGHT
18 from com.sun.star.table.CellVertJustify import STANDARD, TOP, CENTER as MIDDLE, BOTTOM
19 from com.sun.star.awt.FontWeight import DONTKNOW, NORMAL, BOLD
20
21 moinmoin_old_style = True
22
23 def getRangeSize(sheet, cursor):
24 r = cursor.getRangeAddress()
25 realRange = sheet.getCellRangeByPosition(r.StartColumn, r.StartRow,
26 r.EndColumn, r.EndRow)
27 return (realRange.Columns.Count, realRange.Rows.Count)
28
29 def getCellRealPosition(cursor, column, row):
30 r = cursor.getRangeAddress()
31 return (r.StartColumn + column, r.StartRow + row)
32
33 def cell2moin(cell):
34 return cell.getString().replace('\n','<<BR>>')
35
36 def calc2moin(ctx):
37 data = list()
38
39 # récupération du document en cours, vérification du type Spreadsheet
40 smgr = ctx.ServiceManager
41 desktop = smgr.createInstanceWithContext(
42 "com.sun.star.frame.Desktop", ctx)
43 curdoc = desktop.getCurrentComponent()
44 if not curdoc.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
45 raise RuntimeError, u"Ce n'est pas un document de type Spreadsheet (Calc)."
46 controller = curdoc.getCurrentController()
47 sheet = controller.getActiveSheet()
48
49 # localisation de la la zone déjà utilisée
50 cursor = sheet.createCursor()
51 cursor.gotoEndOfUsedArea(False)
52 cursor.gotoStartOfUsedArea(True)
53 columns, rows = getRangeSize(sheet, cursor)
54 for row in range(rows):
55 row_data = list()
56 column = 0
57 while column < columns:
58 cell = cursor.getCellByPosition(column, row)
59 cell_type = cell.getType()
60 cell_string = cell.getString()
61 # calcul de l'étendue de la cellule courante
62 if cell.getIsMerged():
63 c, r = getCellRealPosition(cursor, column, row)
64 cellRange = sheet.getCellRangeByPosition(c, r, c, r)
65 cursor2 = sheet.createCursorByRange(cellRange)
66 cursor2.collapseToMergedArea()
67 cell_colspan, cell_rowspan = getRangeSize(sheet, cursor2)
68 else:
69 cell_colspan, cell_rowspan = 1, 1
70 # traitement des attributs et styles de la cellule
71 cell_attributes = list()
72 cell_styles = list()
73 if cell_string and hasattr(cell, 'HoriJustify'):
74 horiJustify = cell.getPropertyValue('HoriJustify')
75 if horiJustify == LEFT:
76 if cell_colspan > 1 or cell_rowspan > 1:
77 text_align = 'left'
78 text_align_old = '('
79 else:
80 text_align = '' # left par défaut si span == 1
81 text_align_old = ''
82 elif horiJustify == CENTER:
83 if cell_colspan == 1 and cell_rowspan == 1:
84 text_align = 'center'
85 text_align_old = ':'
86 else:
87 text_align = '' # center par défaut si span > 1
88 text_align_old = ''
89 elif horiJustify == RIGHT:
90 text_align = 'right'
91 text_align_old = ')'
92 else:
93 if cell_type == TEXT:
94 text_align = 'left'
95 text_align_old = '('
96 elif cell_type != EMPTY:
97 text_align = 'right'
98 text_align_old = ')'
99 if text_align:
100 if moinmoin_old_style:
101 cell_attributes.append(text_align_old)
102 else:
103 cell_styles.append('text-align: ' + text_align)
104 if cell_string and hasattr(cell, 'VertJustify'):
105 vertJustify = cell.getPropertyValue('VertJustify')
106 if vertJustify == 1: #TOP(1)
107 vertical_align = 'top'
108 vertical_align_old = '^'
109 elif vertJustify == 2: #MIDDLE(2)
110 vertical_align = '' # middle par défaut
111 vertical_align_old = ''
112 else: #STANDARD(0), BOTTOM(3)
113 vertical_align = 'bottom'
114 vertical_align_old = 'v'
115 if vertical_align:
116 if moinmoin_old_style:
117 cell_attributes.append(vertical_align_old)
118 else:
119 cell_styles.append('vertical-align: ' + vertical_align)
120 if cell_string and hasattr(cell, 'CharWeight'):
121 charWeight = cell.getPropertyValue('CharWeight')
122 if charWeight == BOLD:
123 if moinmoin_old_style:
124 # FIXME: pas utilisé ensuite !!
125 cell_string = "'''%s'''" % cell_string
126 else:
127 cell_styles.append('font-weight: bold')
128 if cell_rowspan > 1:
129 cell_attributes.append('|%d' % cell_rowspan)
130 if cell_colspan > 1:
131 cell_attributes.append('-%d' % cell_colspan)
132 if hasattr(cell, 'CellBackColor'):
133 color = cell.getPropertyValue('CellBackColor')
134 if color >= 0:
135 if moinmoin_old_style:
136 cell_attributes.append('#%06x' % color)
137 else:
138 cell_styles.append('background: #%06x' % color)
139 if hasattr(cell, 'CharColor'):
140 color = cell.getPropertyValue('CharColor')
141 if color >= 0:
142 cell_styles.append('color: #%06x' % color)
143 # compilation des styles de la cellule
144 if cell_styles:
145 cell_attributes.insert(0, 'style="%s;"' % '; '.join(cell_styles))
146 # ajout de la définition de la cellule à la ligne courante
147 cell_data = list()
148 if cell_attributes:
149 cell_data.append('<' + ''.join(cell_attributes) + '>')
150 if cell_string:
151 cell_data.append(cell2moin(cell))
152 else:
153 cell_data.append(' ')
154 row_data.append(''.join(cell_data))
155 column += cell_colspan
156 # display row's code
157 data.append('||' + '||'.join(row_data) + '||')
158
159 #
160 # création d'un document Writer pour écrire le code MoinMoin
161 #
162 # ouverture d'un document Writer caché
163 hidden = PropertyValue()
164 hidden.Name = "Hidden"
165 hidden.Value = True
166 doc = desktop.loadComponentFromURL(
167 "private:factory/swriter", "_blank", 0, (hidden, ) )
168 text = doc.Text
169 textcursor = text.createTextCursor()
170 text.insertString(textcursor, '\n'.join(data) + '\n', 0)
171 # on copie ça dans le presse papier
172 dispatcher = smgr.createInstanceWithContext(
173 "com.sun.star.frame.DispatchHelper", ctx)
174 frame = doc.getCurrentController().getFrame()
175 dispatcher.executeDispatch(frame, ".uno:SelectAll", "", 0, ())
176 dispatcher.executeDispatch(frame, ".uno:Copy", "", 0, ())
177 doc.close(True)
178
179 ##############################################################################
180
181 def copier(event=False):
182 u"""Copier une feuille de calcul vers un wiki MoinMoin."""
183 ctx = uno.getComponentContext()
184 calc2moin(ctx)
185 return None
186
187 # lists the scripts, that shall be visible inside OOo. Can be omited, if
188 # all functions shall be visible, however here getNewString shall be surpressed
189 g_exportedScripts = (copier, )
190
191 ##############################################################################
192
193 class CopierJob(unohelper.Base, XJobExecutor):
194 def __init__(self, context):
195 self._context = context
196
197 def trigger(self, args):
198 calc2moin(self._context)
199
200 g_ImplementationHelper = unohelper.ImplementationHelper()
201 g_ImplementationHelper.addImplementation( \
202 CopierJob, "org.auf.openoffice.calc2moin.Copier", \
203 ("com.sun.star.task.Job",),)