Debian Codegraph @

src/plugins/scripting/scripts/plan2odsexport.py

raw
1 #!/usr/bin/env kross
2 # -*- coding: utf-8 -*-
3
4 """
5 Python script to export content from a Plan Project to an ods file.
6
7 (C)2012 Dag Andersen <[email protected]>
8 Licensed under LGPL v2+higher.
9 """
10
11 import sys, os, traceback
12 import Kross, Plan
13
14 T = Kross.module("kdetranslation")
15 Sheets = Kross.module("KSpread")
16 if Sheets is None:
17 raise Exception, T.i18n("Failed to start Sheets. Is Sheets installed?")
18
19 class PlanExport:
20
21 def __init__(self, scriptaction):
22 self.scriptaction = scriptaction
23 self.currentpath = self.scriptaction.currentPath()
24 self.forms = Kross.module("forms")
25 try:
26 self.start()
27 except Exception, inst:
28 self.forms.showMessageBox("Sorry", T.i18n("Error"), "%s" % inst)
29 except:
30 self.forms.showMessageBox("Error", T.i18n("Error"), "%s" % "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
31
32 def start(self):
33 writer = Sheets.writer()
34 Sheets.map().insertSheet("S1")
35 currentSheet = Sheets.map().sheetByIndex(0)
36 if not currentSheet:
37 raise Exception, T.i18n("No current sheet.")
38 if not writer.setSheet(currentSheet):
39 raise Exception, T.i18n("Invalid sheet '%1' defined.", [currentSheet])
40
41 if not writer.setCell("A1"):
42 raise Exception, T.i18n("Could not select cell 'A1'")
43
44 proj = Plan.project()
45 data = self.showDataSelectionDialog( writer, Plan )
46 if data is None:
47 return
48 if len(data) == 0:
49 raise Exception, T.i18n("No data to export")
50
51 filename = data[4]
52 if not filename:
53 raise Exception, T.i18n("You must select a file to write to")
54
55 self.writeToSheets(writer, proj, data)
56
57 if not Sheets.saveUrl(filename):
58 raise Exception, T.i18n("Could not write to file:\n%1", [filename])
59
60 self.forms.showMessageBox("Information", T.i18n("Information"), T.i18n("Data saved to file:\n%1", [filename]))
61
62 def writeToSheets(self, writer, proj, data):
63 objectType = data[0]
64 schedule = data[1]
65 props = data[2]
66 headers = data[3]
67 if len(props) == 0:
68 raise Exception, T.i18n("No properties to export")
69
70 if headers == True:
71 record = []
72 for prop in props:
73 record.append(proj.headerData( objectType, prop))
74
75 if not writer.setValue(record):
76 if self.forms.showMessageBox("WarningContinueCancel", T.i18n("Warning"), T.i18n("Failed to set all properties of '%1' to cell '%2'", [", ".join(record), writer.cell()])) == "Cancel":
77 return
78 writer.next()
79
80 if objectType == 0: # Nodes
81 self.exportValues( writer, proj, proj, props, schedule )
82 elif objectType == 1: # Resources
83 for i in range( proj.resourceGroupCount() ):
84 self.exportValues( writer, proj, proj.resourceGroupAt( i ), props, schedule )
85 elif objectType == 2: # Accounts
86 for i in range( proj.accountCount() ):
87 self.exportValues( writer, proj, proj.accountAt( i ), props, schedule )
88
89 def exportValues(self, writer, project, dataobject, props, schedule ):
90 record = []
91 for prop in props:
92 record.append(project.data(dataobject, prop, "DisplayRole", schedule))
93
94 if not writer.setValues(record):
95 if self.forms.showMessageBox("WarningContinueCancel", T.i18n("Warning"), T.i18n("Failed to set all properties of '%1' to cell '%2'", [", ".join(record), writer.cell()])) == "Cancel":
96 return
97 writer.next()
98 for i in range( dataobject.childCount() ):
99 self.exportValues( writer, project, dataobject.childAt( i ), props, schedule )
100
101 def showDataSelectionDialog(self, writer, Plan ):
102 tabledialog = self.forms.createDialog("Property List")
103 tabledialog.setButtons("Ok|Cancel")
104 tabledialog.setFaceType("List") #Auto Plain List Tree Tabbed
105
106 schedulepage = tabledialog.addPage(T.i18n("Schedules"),T.i18n("Select schedule"))
107 schedulewidget = Plan.createScheduleListView(schedulepage)
108
109 sourcepage = tabledialog.addPage(T.i18n("Data"),T.i18n("Select data"))
110 sourcewidget = Plan.createDataQueryView(sourcepage)
111
112 savepage = tabledialog.addPage(T.i18n("Save"), T.i18n("Export ods file"),"document-save")
113 self.savewidget = self.forms.createFileWidget(savepage, "kfiledialog:///odsexportsave")
114 self.savewidget.setMode("Saving")
115 self.savewidget.setFilter("*.ods|%(1)s\n*|%(2)s" % { '1' : T.i18n("Spreadsheet"), '2' : T.i18n("All Files") } )
116
117 if tabledialog.exec_loop():
118 schedule = schedulewidget.currentSchedule()
119 props = sourcewidget.selectedProperties()
120 #print "props: ", props
121 ot = sourcewidget.objectType()
122 #print "objectType: ", ot
123 filename = self.savewidget.selectedFile()
124 return [ot, schedule, props, sourcewidget.includeHeaders(), filename ]
125 return None
126
127
128 PlanExport( self )