-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpessheet.py
More file actions
532 lines (454 loc) · 19.4 KB
/
Copy pathpessheet.py
File metadata and controls
532 lines (454 loc) · 19.4 KB
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#!/usr/bin/python
# spreadsheet.py
from wx.lib import sheet
import wx
import wx.py.editor
from spreadsheet import SpreadSheet, SpreadSheetError
import spreadsheetgrid
def getApplicationVersion():
return '0.1.0'
def getApplicationName():
return 'PESsheet'
def getFullApplicationName():
return '%s v%s' % (getApplicationName(), getApplicationVersion())
def iconsize():
return 16
def iconbitmap(name):
return wx.Bitmap('resources/icons%d/%s' % (iconsize(), name))
def iconbitmapsize():
return (iconsize(), iconsize())
def conf_file_name(appname):
import platform
import os
if platform.system() == 'Windows':
# Get path to the application data directory and create a Todos
# subdirectory if it does not exist.
import ctypes
CSIDL_APPDATA = 0x1a
CSIDL_FLAG_CREATE = 0x8000
SHGFP_TYPE_CURRENT = 0
MAX_DATA_SIZE = 260
T = ctypes.c_wchar * MAX_DATA_SIZE
app_data = T()
f = ctypes.windll.shell32.SHGetFolderPathW
if f(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0, SHGFP_TYPE_CURRENT,
app_data):
raise RuntimeError('Failed to call SHGetFolderPathW()')
directory = os.path.join(app_data.value, appname)
if not os.path.exists(directory):
os.mkdir(directory)
else:
directory = os.path.expanduser('~')
return os.path.join(directory, '%s.conf' % appname)
class SheetPage(wx.Panel):
def __init__(self, parent, spreadsheet):
wx.Panel.__init__(self, parent, id=wx.ID_ANY)
self.SetBackgroundColour(parent.GetBackgroundColour())
cell_toolbar_line1 = wx.Panel(self)
cell_toolbar_line1_sizer = wx.BoxSizer(wx.HORIZONTAL)
cell_toolbar_line1.SetSizer(cell_toolbar_line1_sizer)
self.selected_cell_textctrl = wx.TextCtrl(cell_toolbar_line1)
self.selected_cell_textctrl.SetValue('a1')
cell_toolbar_line1_sizer.Add(self.selected_cell_textctrl, 0, wx.CENTER)
self.cell_formula_textctrl = wx.TextCtrl(cell_toolbar_line1, style=wx.TE_PROCESS_ENTER)
cell_toolbar_line1_sizer.Add(self.cell_formula_textctrl, 1, wx.CENTER)
cell_toolbar_line2 = wx.Panel(self)
cell_toolbar_line2_sizer = wx.BoxSizer(wx.HORIZONTAL)
cell_toolbar_line2.SetSizer(cell_toolbar_line2_sizer)
self.cell_value_type_textctrl = wx.TextCtrl(cell_toolbar_line2)
self.cell_value_type_textctrl.SetEditable(False)
cell_toolbar_line2_sizer.Add(self.cell_value_type_textctrl, 0, wx.CENTER)
self.cell_value_textctrl = wx.TextCtrl(cell_toolbar_line2)
self.cell_value_textctrl.SetEditable(False)
cell_toolbar_line2_sizer.Add(self.cell_value_textctrl, 1, wx.CENTER)
self.grid = spreadsheetgrid.SpreadSheetGrid(self, spreadsheet,
[self.onCellSelect])
box = wx.BoxSizer(wx.VERTICAL)
box.Add((5,10) , 0)
box.Add(cell_toolbar_line1, 0, wx.EXPAND, border=5)
box.Add(cell_toolbar_line2, 0, wx.EXPAND, border=5)
box.Add((5,10) , 0)
box.Add(self.grid, 1, wx.EXPAND)
self.SetSizer(box)
self.cell_formula_textctrl.Bind(wx.EVT_KILL_FOCUS, self.onCellFormulaLostFocus)
self.cell_formula_textctrl.Bind(wx.EVT_TEXT_ENTER, self.onCellFormulaLostFocus)
def onCellSelect(self, position, cell):
self.selected_cell_textctrl.SetValue(position)
formula = ''
value = ''
type_name = ''
if cell:
formula = cell.getFormula()
try:
value = cell.getValue()
type_name = type(value).__name__
try:
type_name += ' of len %d' % len(value)
except:
pass
except (Exception, SyntaxError, SpreadSheetError), e:
print e
value = str(e)
type_name = '(Error)'
self.cell_formula_textctrl.SetValue(formula)
self.cell_value_textctrl.SetValue(str(value))
self.cell_value_type_textctrl.SetValue(type_name)
def onCellFormulaLostFocus(self, event):
value = event.GetEventObject().GetValue()
row = self.grid.GetGridCursorRow()
col = self.grid.GetGridCursorCol()
old_value = self.grid.GetTable().GetFormula(row, col)
if value != old_value:
if value.strip():
self.grid.GetTable().SetFormula(row, col, value)
else:
self.grid.GetTable().DeleteCell(row, col)
wx.CallAfter(self.grid.ForceRefresh)
event.Skip()
class GraphImage(wx.Window):
def __init__(self, parent):
image = wx.Image('graph.gif', wx.BITMAP_TYPE_GIF)
image = image.ConvertToBitmap()
wx.Window.__init__(self, parent, wx.ID_ANY)
self.bmp = wx.StaticBitmap(parent=self, bitmap=image)
class PysApplicationWindow(wx.Frame):
def __init__(self, parent, id, title, size, call_on_destroy,
filename=None, dirname=''):
wx.Frame.__init__(self, parent, id, title, size=size)
self._filename = filename
self._dirname = dirname
self._call_on_destroy = call_on_destroy
self._additional_paths = []
self._conf_filename = conf_file_name('pessheet')
self.loadSettings()
import sys
print 'Original path: ', sys.path
print 'Additional paths: ', self._additional_paths
self._spreadsheet = SpreadSheet(self._additional_paths)
ib = wx.IconBundle()
ib.AddIconFromFile("resources/pessheet.ico", wx.BITMAP_TYPE_ANY)
self.SetIcons(ib)
self.id_export = wx.NewId()
self.SetMenuBar(self.getMenuBar())
panel = wx.Panel(self)
main_toolbar = wx.ToolBar(panel, wx.ID_ANY, style=wx.TB_HORIZONTAL)
main_toolbar.SetToolBitmapSize(iconbitmapsize()) # Needed for Windows XP
alt = main_toolbar.AddLabelTool
alt(wx.ID_NEW, '', iconbitmap('document-new.png'), shortHelp='New')
alt(wx.ID_OPEN, '', iconbitmap('document-open.png'), shortHelp='Open')
alt(wx.ID_SAVE, '', iconbitmap('document-save.png'), shortHelp='Save')
alt(wx.ID_SAVEAS, '', iconbitmap('document-save-as.png'), shortHelp='Save as')
main_toolbar.AddSeparator()
alt(wx.ID_CUT, '', iconbitmap('edit-cut.png'), shortHelp='Cut')
alt(wx.ID_COPY, '', iconbitmap('edit-copy.png'), shortHelp='Copy')
alt(wx.ID_PASTE, '', iconbitmap('edit-paste.png'), shortHelp='Paste')
#alt(-1, '', iconbitmap('edit-delete.png'), shortHelp='Delete')
#main_toolbar.AddSeparator()
#alt(wx.ID_UNDO, '', iconbitmap('edit-undo.png'), shortHelp='Undo')
#alt(wx.ID_REDO, '', iconbitmap('edit-redo.png'), shortHelp='Redo')
main_toolbar.AddSeparator()
alt(wx.ID_EXIT, '', iconbitmap('system-log-out.png'), shortHelp='Exit')
main_toolbar.Realize()
box = wx.BoxSizer(wx.VERTICAL)
box.Add(main_toolbar, 0, wx.EXPAND, border=5)
box.Add((5,5) , 0)
panel.SetSizer(box)
notebook = wx.Notebook(panel, wx.ID_ANY, style=wx.LEFT)
self._sheet_page = SheetPage(notebook, self._spreadsheet)
#graph_page = GraphImage(notebook)
script_page = wx.py.editor.EditWindow(None, notebook)
self._editor = script_page
notebook.AddPage(self._sheet_page, 'Sheet')
#notebook.AddPage(graph_page, 'Graph')
notebook.AddPage(script_page, 'Script')
box.Add(notebook, 1, wx.EXPAND)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
self.Bind(wx.EVT_MENU, self.OnFileNew, id=wx.ID_NEW)
self.Bind(wx.EVT_MENU, self.OnFileOpen, id=wx.ID_OPEN)
self.Bind(wx.EVT_MENU, self.OnFileSave, id=wx.ID_SAVE)
self.Bind(wx.EVT_MENU, self.OnFileSaveAs, id=wx.ID_SAVEAS)
self.Bind(wx.EVT_MENU, self.OnFileExport, id=self.id_export)
self.Bind(wx.EVT_MENU, self.OnEditCut, id=wx.ID_CUT)
self.Bind(wx.EVT_MENU, self.OnEditCopy, id=wx.ID_COPY)
self.Bind(wx.EVT_MENU, self.OnEditPaste, id=wx.ID_PASTE)
self.Bind(wx.EVT_MENU, self.OnOptions, id=wx.ID_PREFERENCES)
script_page.Bind(wx.EVT_KILL_FOCUS, self.onEditorLostFocus)
self.updateTitle()
self.CreateStatusBar()
self.Centre()
self.Show(True)
self._sheet_page.grid.SetFocus()
if self._filename is not None:
self.load()
def loadSettings(self):
import cPickle
try:
settings_dict = cPickle.load(open(self._conf_filename, 'r'))
self._additional_paths[:] = settings_dict.get('additional_paths',
[])[:]
except IOError, e:
pass
def saveSettings(self):
import cPickle
settings_dict = {
'additional_paths': self._additional_paths,
}
cPickle.dump(settings_dict, open(self._conf_filename, 'w'))
def getMenuBar(self):
menues = [
('&File',
[
(wx.ID_NEW, '&New...\tCtrl-N', 'Create new spreadsheet'),
(wx.ID_OPEN, '&Open...\tCtrl-O', 'Open a spreadsheet'),
None, #Separator
(wx.ID_SAVE, '&Save\tCtrl-S', 'Save current spreadsheet'),
(wx.ID_SAVEAS, 'Save As...\tCtrl-Shift-S', 'Save current spreadsheet as new file'),
None, #Separator
(self.id_export, 'Export...\tCtrl-E', 'Export current spreadsheet into other format'),
None, #Separator
#(wx.ID_ABOUT, '&About pyssheet', 'Information about this program'),
#(wx.ID_HELP, '&Help', 'Help about using this program'),
#None,
(wx.ID_EXIT, 'E&xit\tCtrl-Q', 'Terminate the program'),
]
),
('&Edit',
[
#(wx.ID_UNDO, 'Undo\tCtrl-Z', 'Undo'),
#(wx.ID_REDO, 'Redo\tCtrl-Shift-Z', 'Redo'),
#None,
(wx.ID_CUT, 'Cut\tCtrl-X', 'Cut selection into Clipboard'),
(wx.ID_COPY, 'Copy\tCtrl-C', 'Copy selection into Clipboard'),
(wx.ID_PASTE, 'Paste\tCtrl-V', 'Paste the content of the Clipboard into the sheet'),
]
),
#('&View',
#[
#(self.onShowSheet, 'Sheet', 'Show Sheet'),
##(wx.ID_ANY, 'Graph', 'Show Calculation Graph'),
#(self.onShowScript, 'Script', 'Show Script'),
#]
#),
('&Tools',
[
(wx.ID_PREFERENCES, '&Options...', 'Set options'),
]
),
]
menuBar = wx.MenuBar()
for menu_name, menu_items in menues:
menu = wx.Menu()
menuBar.Append(menu, menu_name)
for menu_item in menu_items:
if menu_item:
id, name, help = menu_item
if isinstance(id, int):
menu.Append(id, name, help)
else:
callback = id
assigned_id = menu.Append(wx.ID_ANY, name, help)
self.Bind(wx.EVT_MENU, callback, assigned_id)
else:
menu.AppendSeparator()
return menuBar
def onEditorLostFocus(self, event):
script = self._editor.GetText()
script = '\n'.join(script.splitlines())
self._spreadsheet.setScript(script)
def OnExit(self, event):
self.Close()
def OnClose(self, event):
dlg = wx.MessageDialog(self,
"Want to exit %s?" % getApplicationName(),
"Exit", wx.YES_NO | wx.ICON_QUESTION)
if dlg.ShowModal() == wx.ID_YES:
self.Destroy()
self._call_on_destroy()
dlg.Destroy()
def updateTitle(self):
if self._filename:
self.SetTitle('%s (%s) - %s' % (self._filename,
self._dirname,
getFullApplicationName()))
else:
self.SetTitle('New spreadsheet - %s' %
getFullApplicationName())
def OnFileNew(self, event):
dlg = wx.MessageDialog(self,
"Create new spreadsheet?\nThis will discard the current spreadsheet.",
"New spreadsheet", wx.YES_NO | wx.ICON_QUESTION)
if dlg.ShowModal() == wx.ID_YES:
self._filename = None
self._spreadsheet.clear()
self.Refresh()
self.SetStatusText('New spreadsheet created')
self.updateTitle()
dlg.Destroy()
def OnFileOpen(self, event):
filedialog = wx.FileDialog(self, "Open spreadsheet file",
self._dirname, '',
"%s files (*.pss)|*.pss" % getApplicationName(),
wx.OPEN)
if filedialog.ShowModal() == wx.ID_OK:
self._filename = filedialog.GetFilename()
self._dirname = filedialog.GetDirectory()
filedialog.Destroy()
self.load()
def load(self):
import os
self.SetStatusText('Loading file %s' % self._filename)
f = open(os.path.join(self._dirname, self._filename), 'r')
contents = f.read()
contents = '\n'.join(contents.splitlines())
f.close()
try:
self._spreadsheet.load(contents)
except (ImportError, SyntaxError), e:
print e
self._editor.SetText(self._spreadsheet.getScript())
self.SetStatusText('File loaded')
self.updateTitle()
self.Refresh()
def save(self):
import os
self.SetStatusText('Saving file %s' % self._filename)
f = open(os.path.join(self._dirname, self._filename), 'w')
f.write(self._spreadsheet.save())
f.close()
self.SetStatusText('File saved')
self.updateTitle()
def OnFileSave(self, event):
if self._filename:
self.save()
else:
self.OnFileSaveAs(event)
def OnFileSaveAs(self, event):
filedialog = wx.FileDialog(self, "Save spreadsheet as",
self._dirname, '',
"%s files (*.pss)|*.pss" % getApplicationName(),
wx.SAVE | wx.OVERWRITE_PROMPT)
if filedialog.ShowModal() == wx.ID_OK:
self._filename = filedialog.GetFilename()
self._dirname = filedialog.GetDirectory()
self.save()
filedialog.Destroy()
def OnFileExport(self, event):
export_formats = [
('Python script (*.py)', '.py', self.export_python),
('Graphviz dot file (*.dot)', '.dot', self.export_dot),
]
filter_string = '|'.join(d+'|*'+e for d, e, _ in export_formats)
filedialog = wx.FileDialog(self, 'Export spreadsheet as',
self._dirname, '',
filter_string,
wx.SAVE | wx.OVERWRITE_PROMPT)
if filedialog.ShowModal() == wx.ID_OK:
filter_index = filedialog.GetFilterIndex()
_, extension, export_function = export_formats[filter_index]
dirname = filedialog.GetDirectory()
filename = filedialog.GetFilename()
if not filename.endswith(extension):
filename += extension
export_function(dirname, filename)
filedialog.Destroy()
def export_python(self, dirname, filename):
import os
self.SetStatusText('Exporting to file %s' % filename)
f = open(os.path.join(dirname, filename), 'w')
f.write(self._spreadsheet.asScript())
f.close()
self.SetStatusText('Spreadsheet exported')
def export_dot(self, dirname, filename):
import os
self.SetStatusText('Exporting to file %s' % filename)
f = open(os.path.join(dirname, filename), 'w')
f.write(self._spreadsheet.asDot())
f.close()
self.SetStatusText('Spreadsheet exported')
def OnEditCut(self, event):
#print 'PysApplicationWindow.OnEditCut', event
clip_object = None
if (wx.GetActiveWindow().FindFocus().GetParent() ==
self._sheet_page.grid):
clip_object = self._sheet_page.grid.cut()
if clip_object:
text_data = wx.TextDataObject(clip_object)
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(text_data)
wx.TheClipboard.Close()
else:
event.Skip()
def OnEditCopy(self, event):
#print 'PysApplicationWindow.OnEditCopy', event
clip_object = None
if (wx.GetActiveWindow().FindFocus().GetParent() ==
self._sheet_page.grid):
clip_object = self._sheet_page.grid.copy()
if clip_object:
text_data = wx.TextDataObject(clip_object)
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(text_data)
wx.TheClipboard.Close()
else:
event.Skip()
def OnEditPaste(self, event):
text_data = wx.TextDataObject()
success = False
if wx.TheClipboard.Open():
success = wx.TheClipboard.GetData(text_data)
wx.TheClipboard.Close()
if success:
if (wx.GetActiveWindow().FindFocus().GetParent() ==
self._sheet_page.grid):
self._sheet_page.grid.paste(text_data.GetText())
else:
event.Skip()
"""
Maybe some useful stuff:
http://74.125.77.132/search?q=cache:l8ru47_-EuAJ:www.picalo.org/download/picalo-2.32/picalo/gui/Spreadsheet.py+ID_PASTE+wx+bind+TheClipBoard+grid&hl=sv&ct=clnk&cd=1&gl=se&client=firefox-a
"""
def OnOptions(self, event):
value = '\n'.join(self._additional_paths)
d = wx.TextEntryDialog(self,
'Additional paths to python packages (one per line)',
'Additional paths', value,
style=wx.OK|wx.CANCEL|wx.TE_MULTILINE)
if d.ShowModal() == wx.ID_OK:
value = str(d.GetValue()).splitlines()
self._additional_paths[:] = value[:]
self.saveSettings()
event.Skip()
def main(argv):
# Move to the location of the program!
import os
abspath = os.path.abspath(argv[0])
dname = os.path.dirname(abspath)
os.chdir(dname)
redirect = False
if argv[-1] == '-g':
redirect = True
argv.pop()
#app = wx.App()
app = wx.App(redirect=redirect)
bmp = wx.Image('resources/pes_splash.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
wx.SplashScreen(bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
1000, None, -1)
window_size = wx.GetDisplaySize()
window_size.Scale(0.8, 0.8)
path, filename = '', None
if len(argv) > 1:
import os.path
path, filename = os.path.split(argv[1])
def call_on_destroy():
if app.stdioWin:
app.stdioWin.close()
main_window = PysApplicationWindow(None, wx.ID_ANY,
'Python Scriptable SpreadSheet',
window_size, filename=filename,
dirname=path,
call_on_destroy=call_on_destroy)
app.MainLoop()
if __name__ == '__main__':
import sys
main(sys.argv)