-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstations.py
991 lines (823 loc) · 41 KB
/
stations.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
import wx, sqlite3, datetime
import os, sys, re, cPickle
import scidb
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
import wx.lib.scrolledpanel as scrolled, wx.grid
from wx.lib.wordwrap import wordwrap
ID_CBX_SEL_SITE = wx.NewId()
#ID_ADD_END_TIMESTAMP = wx.NewId()
#listPopMenuItems_byID = {ID_ADD_END_TIMESTAMP:'Add ending timestamp'}
listPopMenuItems = ['Add ending timestamp']
listPopMenuItems_byID = {}
for sItm in listPopMenuItems:
listPopMenuItems_byID[ wx.NewId() ] = sItm
class Dialog_EndTimestamp(wx.Dialog):
def __init__(self, parent, id, title = "End Timestamp", actionCode = None):
wx.Dialog.__init__(self, parent, id)
self.InitUI(actionCode)
self.SetSize((300, 200))
if actionCode[0] == 'New':
self.SetTitle("Add End Timestamp")
if actionCode[0] == 'Edit':
self.SetTitle("Edit End Timestamp")
if actionCode[0] == None:
self.SetTitle("Add or Edit End Timestamp") # overrides title passed above
def InitUI(self, actionCode):
# pnl = InfoPanel_EndTimestamp(self, wx.ID_ANY)
self.pnl = InfoPanel_EndTimestamp(self, actionCode)
def OnClose(self, event):
self.Destroy()
class InfoPanel_EndTimestamp(scrolled.ScrolledPanel):
def __init__(self, parent, actionCode):
scrolled.ScrolledPanel.__init__(self, parent, -1)
# def __init__(self, parent, id):
# wx.Panel.__init__(self, parent, id)
self.InitUI(actionCode)
def InitUI(self, actionCode):
print "Initializing EndTimestamp frame"
if actionCode[0] == 'Edit': # editing an existing record, only option so far
self.CSDict = scidb.dictFromTableID('ChannelSegments', actionCode[1])
print 'self.CSDict loaded from table:', self.CSDict
self.stEndTSLabel = 'Ending timestamp'
print "Initializing Panel_EndTimestamp ->>>>"
print "actionCode:", actionCode
self.LayoutPanel()
self.FillPanelFromDict()
def LayoutPanel(self):
wordWrapWidth = 350
self.SetBackgroundColour(wx.WHITE) # this overrides color of enclosing panel
ETPnlSiz = wx.GridBagSizer(1, 1)
gRow = 0
ETPnlSiz.Add(wx.StaticText(self, -1, self.stEndTSLabel),
pos=(gRow, 0), span=(1, 3), flag=wx.ALIGN_LEFT|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
# gRow += 1
# ETPnlSiz.Add(wx.StaticLine(self), pos=(gRow, 0), span=(1, 3), flag=wx.EXPAND)
gRow += 1
self.tcEndTimestamp = wx.TextCtrl(self)
ETPnlSiz.Add(self.tcEndTimestamp, pos=(gRow, 0), span=(1, 3),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1
stAboutET = 'Enter or Edit the ending timestamp for this Channel Segment. ' \
'The system will automtatically ' \
'create a new Channel Segment beginning when this one ends.'
stWr = wordwrap(stAboutET, wordWrapWidth, wx.ClientDC(self))
ETPnlSiz.Add(wx.StaticText(self, -1, stWr),
pos=(gRow, 0), span=(1, 3), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
gRow += 1
ETPnlSiz.Add(wx.StaticLine(self), pos=(gRow, 0), span=(1, 3),
flag=wx.EXPAND|wx.BOTTOM, border=1)
gRow += 1
self.btnSave = wx.Button(self, label="Save", size=(90, 28))
self.btnSave.Bind(wx.EVT_BUTTON, lambda evt: self.onClick_BtnSave(evt))
ETPnlSiz.Add(self.btnSave, pos=(gRow, 0), flag=wx.LEFT|wx.BOTTOM, border=5)
self.btnCancel = wx.Button(self, label="Cancel", size=(90, 28))
self.btnCancel.Bind(wx.EVT_BUTTON, lambda evt: self.onClick_BtnCancel(evt))
ETPnlSiz.Add(self.btnCancel, pos=(gRow, 1), flag=wx.LEFT|wx.BOTTOM, border=5)
self.SetSizer(ETPnlSiz)
self.SetAutoLayout(1)
self.SetupScrolling()
def FillPanelFromDict(self):
if self.CSDict['SegmentEnd'] != None:
self.tcEndTimestamp.SetValue(self.CSDict['SegmentEnd'])
def FillDictFromPanel(self):
self.CSDict['SegmentEnd'] = scidb.getDateTimeFromTC(self.tcEndTimestamp)
def onClick_BtnSave(self, event):
"""
If actionCode[0] = 'Edit', attempt to save any changes to the existing DB record
Only option so far
"""
self.FillDictFromPanel() # get all values before testing
# verify
# ending timestamp is null in not valid, any more verification needed?
recID = scidb.dictIntoTable_InsertOrReplace('ChannelSegments', self.CSDict)
# if appropriate, create the new segment starting when this one ends
if self.CSDict['SegmentEnd'] != None:
self.CSDict['ID'] = None # force new record
#self.CSDict['ChannelID'] leave the same
self.CSDict['SegmentBegin'] = self.CSDict['SegmentEnd']
self.CSDict['SegmentEnd'] = None # null means 'up till now'
self.CSDict['StationID'] = None # don't assume the same, have user assign
self.CSDict['SeriesID'] = None
recID = scidb.dictIntoTable_InsertOrReplace('ChannelSegments', self.CSDict)
parObject = self.GetParent()
if parObject.GetClassName() == "wxDialog":
parObject.EndModal(0)
def onClick_BtnCancel(self, event):
"""
This frame is shown in a Dialog, which is its parent object.
"""
parObject = self.GetParent()
if parObject.GetClassName() == "wxDialog":
parObject.EndModal(0)
class Dialog_StationDetails(wx.Dialog):
def __init__(self, parent, id, title = "Station", actionCode = None):
wx.Dialog.__init__(self, parent, id)
self.InitUI(actionCode)
self.SetSize((350, 300))
if actionCode[0] == 'New':
self.SetTitle("Add Station")
if actionCode[0] == 'Edit':
self.SetTitle("Edit Station Details")
if actionCode[0] == None:
self.SetTitle("Add or Edit Station Details") # overrides title passed above
def InitUI(self, actionCode):
# pnl = InfoPanel_StationDetails(self, wx.ID_ANY)
self.pnl = InfoPanel_StationDetails(self, actionCode)
def OnClose(self, event):
self.Destroy()
class InfoPanel_StationDetails(scrolled.ScrolledPanel):
def __init__(self, parent, actionCode):
scrolled.ScrolledPanel.__init__(self, parent, -1)
# def __init__(self, parent, id):
# wx.Panel.__init__(self, parent, id)
self.InitUI(actionCode)
def InitUI(self, actionCode):
print "Initializing StationDetails frame"
if actionCode[0] == 'New': # create a new Station record
self.StDict = scidb.dictFromTableDefaults('Stations')
print 'new default self.StDict:', self.StDict
self.stStaLabel = 'Name of Station you are adding to the database'
else: # editing an existing record
self.StDict = scidb.dictFromTableID('Stations', actionCode[1])
print 'self.StDict loaded from table:', self.StDict
self.stStaLabel = 'Station'
print "Initializing Panel_StationDetails ->>>>"
print "actionCode:", actionCode
self.LayoutPanel()
self.FillPanelFromDict()
def LayoutPanel(self):
wordWrapWidth = 350
self.SetBackgroundColour(wx.WHITE) # this overrides color of enclosing panel
shPnlSiz = wx.GridBagSizer(1, 1)
gRow = 0
shPnlSiz.Add(wx.StaticText(self, -1, self.stStaLabel),
pos=(gRow, 0), span=(1, 3), flag=wx.ALIGN_LEFT|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
# gRow += 1
# shPnlSiz.Add(wx.StaticLine(self), pos=(gRow, 0), span=(1, 3), flag=wx.EXPAND)
gRow += 1
self.tcStationName = wx.TextCtrl(self)
shPnlSiz.Add(self.tcStationName, pos=(gRow, 0), span=(1, 3),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1
stAboutLL = 'Processing requires longitude to calculate solar time (latitude is ' \
'unused). Choose Site or enter lat/lon for each station. ' \
'Within a degree is typically accurate enough.'
stWr = wordwrap(stAboutLL, wordWrapWidth, wx.ClientDC(self))
shPnlSiz.Add(wx.StaticText(self, -1, stWr),
pos=(gRow, 0), span=(1, 3), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
gRow += 1
shPnlSiz.Add(wx.StaticText(self, -1, 'Site'),
pos=(gRow, 0), span=(1, 1), flag=wx.ALIGN_RIGHT|wx.LEFT|wx.BOTTOM, border=5)
self.cbxFldSites = wx.ComboBox(self, ID_CBX_SEL_SITE, style=wx.CB_READONLY)
self.cbxFldSites.Bind(wx.EVT_COMBOBOX, self.onCbxTasks)
# txSiteLLMsg will not be emplaced till later, but needed now for fillSitesList
self.txSiteLLMsg = wx.StaticText(self, -1, label='Site lat/lon:')
self.fillSitesList()
shPnlSiz.Add(self.cbxFldSites, pos=(gRow, 1), span=(1, 1),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
SibHorizSizer = wx.BoxSizer(wx.HORIZONTAL)
btnAddSite = wx.Button(self, label="New", size=(32, 20))
btnAddSite.Bind(wx.EVT_BUTTON, lambda evt, str=btnAddSite.GetLabel(): self.onClick_BtnWorkOnSite(evt, str))
SibHorizSizer.Add(btnAddSite)
btnEditSite = wx.Button(self, label="Edit", size=(32, 20))
btnEditSite.Bind(wx.EVT_BUTTON, lambda evt, str=btnEditSite.GetLabel(): self.onClick_BtnWorkOnSite(evt, str))
SibHorizSizer.Add(btnEditSite)
shPnlSiz.Add(SibHorizSizer, pos=(gRow, 2), span=(1, 1))
gRow += 1
shPnlSiz.Add(self.txSiteLLMsg,
pos=(gRow, 0), span=(1, 3), flag=wx.ALIGN_LEFT|wx.LEFT|wx.BOTTOM, border=5)
gRow += 1
shPnlSiz.Add(wx.StaticLine(self), pos=(gRow, 0), span=(1, 3),
flag=wx.EXPAND|wx.BOTTOM, border=1)
gRow += 1
stAboutSLL = 'You only need to enter Station latitude and longitude if ' \
'you want to override the Site latitude and longitude.'
stWr1 = wordwrap(stAboutSLL, wordWrapWidth, wx.ClientDC(self))
shPnlSiz.Add(wx.StaticText(self, -1, stWr1),
pos=(gRow, 0), span=(1, 3), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
gRow += 1
shPnlSiz.Add(wx.StaticText(self, -1, 'Station latitude'),
pos=(gRow, 0), span=(1, 1), flag=wx.ALIGN_RIGHT|wx.LEFT|wx.BOTTOM, border=5)
self.tcLat = wx.TextCtrl(self)
shPnlSiz.Add(self.tcLat, pos=(gRow, 1), span=(1, 2),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1
shPnlSiz.Add(wx.StaticText(self, -1, 'Station longitude'),
pos=(gRow, 0), span=(1, 1), flag=wx.ALIGN_RIGHT|wx.LEFT|wx.BOTTOM, border=5)
self.tcLon = wx.TextCtrl(self)
shPnlSiz.Add(self.tcLon, pos=(gRow, 1), span=(1, 2),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1
self.btnSave = wx.Button(self, label="Save", size=(90, 28))
self.btnSave.Bind(wx.EVT_BUTTON, lambda evt: self.onClick_BtnSave(evt))
shPnlSiz.Add(self.btnSave, pos=(gRow, 0), flag=wx.LEFT|wx.BOTTOM, border=5)
self.btnCancel = wx.Button(self, label="Cancel", size=(90, 28))
self.btnCancel.Bind(wx.EVT_BUTTON, lambda evt: self.onClick_BtnCancel(evt))
shPnlSiz.Add(self.btnCancel, pos=(gRow, 1), flag=wx.LEFT|wx.BOTTOM, border=5)
self.SetSizer(shPnlSiz)
self.SetAutoLayout(1)
self.SetupScrolling()
def fillSitesList(self):
stSQLFieldSites = 'SELECT ID, SiteName FROM FieldSites'
scidb.fillComboboxFromSQL(self.cbxFldSites, stSQLFieldSites)
self.ShowSiteLatLon()
def onCbxTasks(self, event):
evt_id = event.GetId()
print 'in onCbxTasks, event ID:', evt_id
if evt_id == ID_CBX_SEL_SITE:
print 'about to call ShowSiteLatLon'
self.ShowSiteLatLon()
def FillPanelFromDict(self):
if self.StDict['StationName'] != None:
self.tcStationName.SetValue(self.StDict['StationName'])
scidb.setComboboxToClientData(self.cbxFldSites, self.StDict['SiteID'])
self.ShowSiteLatLon()
if self.StDict['LatitudeDecDegrees'] != None:
self.tcLat.SetValue('%.6f' % self.StDict['LatitudeDecDegrees'])
if self.StDict['LongitudeDecDegrees'] != None:
self.tcLon.SetValue('%.6f' % self.StDict['LongitudeDecDegrees'])
def ShowSiteLatLon(self):
recID = scidb.getComboboxIndex(self.cbxFldSites)
if recID == None:
stSiteLL = 'Site lat/lon: (none yet)'
else:
stSQL_SiLL = 'SELECT LatitudeDecDegrees, LongitudeDecDegrees FROM FieldSites WHERE ID = ?'
rec = scidb.curD.execute(stSQL_SiLL, (recID,))
rec = scidb.curD.fetchone() # returns one record, or None
if rec == None:
stSiteLL = 'Site lat/lon: (can not read)'
else:
stSiteLL = 'Site lat/lon: (' + ('%.6f' % rec['LatitudeDecDegrees']) + \
', ' + ('%.6f' % rec['LongitudeDecDegrees']) + ')'
self.txSiteLLMsg.SetLabel(stSiteLL)
def FillDictFromPanel(self):
# clean up whitespace; remove leading/trailing & multiples
self.StDict['StationName'] = " ".join(self.tcStationName.GetValue().split())
self.StDict['SiteID'] = scidb.getComboboxIndex(self.cbxFldSites)
try:
self.StDict['LatitudeDecDegrees'] = float(self.tcLat.GetValue())
except:
self.StDict['LatitudeDecDegrees'] = None
try:
self.StDict['LongitudeDecDegrees'] = float(self.tcLon.GetValue())
except:
self.StDict['LongitudeDecDegrees'] = None
def onClick_BtnWorkOnSite(self, event, str):
"""
"""
print "in onClick_BtnWorkOnSite, str = '" + str + '"'
if str == "New":
dia = Dialog_SiteDetails(self, wx.ID_ANY, actionCode = ['New', 0])
elif str == "Edit":
recNum = scidb.getComboboxIndex(self.cbxFldSites)
# siteItem = self.lstSites.GetFocusedItem()
if recNum == None:
wx.MessageBox('Select a Site to edit', 'No Selection',
wx.OK | wx.ICON_INFORMATION)
return
# recNum = self.lstSites.GetItemData(siteItem)
dia = Dialog_SiteDetails(self, wx.ID_ANY, actionCode = ['Edit', recNum])
else:
return
# the dialog contains an 'InfoPanel_SiteDetails' named 'pnl'
result = dia.ShowModal()
# dialog is exited using EndModal, and comes back here
print "Modal FieldSite dialog result:", result
# test of pulling things out of the modal dialog
self.siteName = dia.pnl.tcSiteName.GetValue()
print "Name of site, from the Modal:", self.siteName
dia.Destroy()
self.fillSitesList()
self.ShowSiteLatLon()
def onClick_BtnSave(self, event):
"""
If actionCode[0] = 'New', the StationDetails is being created.
Attempt to create a new record and make the new record ID available.
If actionCode[0] = 'Edit', attempt to save any changes to the existing DB record
"""
self.FillDictFromPanel() # get all values before testing
# verify
stStationName = self.StDict['StationName']
print "stStationName:", stStationName
if stStationName == '':
wx.MessageBox('Need Station Name', 'Missing',
wx.OK | wx.ICON_INFORMATION)
self.tcStationName.SetValue(stStationName)
self.tcStationName.SetFocus()
self.Scroll(0, 0) # the required controls are all at the top
return
maxLen = scidb.lenOfVarcharTableField('Stations', 'StationName')
if maxLen < 1:
wx.MessageBox('Error %d getting [Stations].[StationName] field length.' % maxLen, 'Error',
wx.OK | wx.ICON_INFORMATION)
return
if len(stStationName) > maxLen:
wx.MessageBox('Max length for Station Name is %d characters.\n\nIf trimmed version is acceptable, retry.' % maxLen, 'Invalid',
wx.OK | wx.ICON_INFORMATION)
self.tcStationName.SetValue(stStationName[:(maxLen)])
self.tcStationName.SetFocus()
self.Scroll(0, 0) # the required controls are all at the top
return
recID = scidb.dictIntoTable_InsertOrReplace('Stations', self.StDict)
parObject = self.GetParent()
if parObject.GetClassName() == "wxDialog":
parObject.EndModal(0)
def onClick_BtnCancel(self, event):
"""
This frame is shown in a Dialog, which is its parent object.
"""
parObject = self.GetParent()
if parObject.GetClassName() == "wxDialog":
parObject.EndModal(0)
class Dialog_SiteDetails(wx.Dialog):
def __init__(self, parent, id, title = "Site", actionCode = None):
wx.Dialog.__init__(self, parent, id)
self.InitUI(actionCode)
self.SetSize((350, 300))
if actionCode[0] == 'New':
self.SetTitle("Add Site")
if actionCode[0] == 'Edit':
self.SetTitle("Edit Site Details")
if actionCode[0] == None:
self.SetTitle("Add or Edit Site Details") # overrides title passed above
def InitUI(self, actionCode):
# pnl = InfoPanel_SiteDetails(self, wx.ID_ANY)
self.pnl = InfoPanel_SiteDetails(self, actionCode)
def OnClose(self, event):
self.Destroy()
class InfoPanel_SiteDetails(scrolled.ScrolledPanel):
def __init__(self, parent, actionCode):
scrolled.ScrolledPanel.__init__(self, parent, -1)
# def __init__(self, parent, id):
# wx.Panel.__init__(self, parent, id)
self.InitUI(actionCode)
def InitUI(self, actionCode):
print "Initializing SiteDetails frame"
if actionCode[0] == 'New': # create a new Site record
self.SiDict = scidb.dictFromTableDefaults('FieldSites')
print 'new default self.SiDict:', self.SiDict
self.stSiteLabel = 'Name of Site you are adding to the database'
else: # editing an existing record
self.SiDict = scidb.dictFromTableID('FieldSites', actionCode[1])
print 'self.SiDict loaded from table:', self.SiDict
self.stSiteLabel = 'Site'
print "Initializing Panel_SiteDetails ->>>>"
print "actionCode:", actionCode
self.LayoutPanel()
self.FillPanelFromDict()
def LayoutPanel(self):
wordWrapWidth = 350
self.SetBackgroundColour(wx.WHITE) # this overrides color of enclosing panel
siPnlSizer = wx.GridBagSizer(1, 1)
gRow = 0
siPnlSizer.Add(wx.StaticText(self, -1, self.stSiteLabel),
pos=(gRow, 0), span=(1, 3), flag=wx.ALIGN_LEFT|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
# gRow += 1
# siPnlSizer.Add(wx.StaticLine(self), pos=(gRow, 0), span=(1, 3), flag=wx.EXPAND)
gRow += 1
self.tcSiteName = wx.TextCtrl(self)
siPnlSizer.Add(self.tcSiteName, pos=(gRow, 0), span=(1, 3),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1
stAboutLL = 'Processing requires longitude to calculate solar time (latitude is ' \
'unused). Within a degree is typically accurate enough. Enter as ' \
'decimal degrees, negative for South latitude and West longitude.'
stWr = wordwrap(stAboutLL, wordWrapWidth, wx.ClientDC(self))
siPnlSizer.Add(wx.StaticText(self, -1, stWr),
pos=(gRow, 0), span=(1, 3), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
gRow += 1
siPnlSizer.Add(wx.StaticText(self, -1, 'Latitude'),
pos=(gRow, 0), span=(1, 1), flag=wx.ALIGN_RIGHT|wx.LEFT|wx.BOTTOM, border=5)
self.tcLat = wx.TextCtrl(self)
siPnlSizer.Add(self.tcLat, pos=(gRow, 1), span=(1, 2),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1
siPnlSizer.Add(wx.StaticText(self, -1, 'Longitude'),
pos=(gRow, 0), span=(1, 1), flag=wx.ALIGN_RIGHT|wx.LEFT|wx.BOTTOM, border=5)
self.tcLon = wx.TextCtrl(self)
siPnlSizer.Add(self.tcLon, pos=(gRow, 1), span=(1, 2),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1
siPnlSizer.Add(wx.StaticText(self, -1, 'Hour Offset (not required)\ne.g. US Central Time = -6'),
pos=(gRow, 0), span=(2, 2), flag=wx.ALIGN_RIGHT|wx.LEFT|wx.BOTTOM, border=5)
self.tcHrOffset = wx.TextCtrl(self)
siPnlSizer.Add(self.tcHrOffset, pos=(gRow, 2), span=(1, 1),
flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)
gRow += 1 # space for multiline text above
gRow += 1
self.btnSave = wx.Button(self, label="Save", size=(90, 28))
self.btnSave.Bind(wx.EVT_BUTTON, lambda evt: self.onClick_BtnSave(evt))
siPnlSizer.Add(self.btnSave, pos=(gRow, 0), flag=wx.LEFT|wx.BOTTOM, border=5)
self.btnCancel = wx.Button(self, label="Cancel", size=(90, 28))
self.btnCancel.Bind(wx.EVT_BUTTON, lambda evt: self.onClick_BtnCancel(evt))
siPnlSizer.Add(self.btnCancel, pos=(gRow, 1), flag=wx.LEFT|wx.BOTTOM, border=5)
self.SetSizer(siPnlSizer)
self.SetAutoLayout(1)
self.SetupScrolling()
def FillPanelFromDict(self):
if self.SiDict['SiteName'] != None:
self.tcSiteName.SetValue(self.SiDict['SiteName'])
if self.SiDict['LatitudeDecDegrees'] != None:
self.tcLat.SetValue('%.6f' % self.SiDict['LatitudeDecDegrees'])
if self.SiDict['LongitudeDecDegrees'] != None:
self.tcLon.SetValue('%.6f' % self.SiDict['LongitudeDecDegrees'])
if self.SiDict['UTC_Offset'] != None:
self.tcHrOffset.SetValue('%d' % self.SiDict['UTC_Offset'])
def FillDictFromPanel(self):
# clean up whitespace; remove leading/trailing & multiples
self.SiDict['SiteName'] = " ".join(self.tcSiteName.GetValue().split())
try:
self.SiDict['LatitudeDecDegrees'] = float(self.tcLat.GetValue())
except:
self.SiDict['LatitudeDecDegrees'] = None
try:
self.SiDict['LongitudeDecDegrees'] = float(self.tcLon.GetValue())
except:
self.SiDict['LongitudeDecDegrees'] = None
try:
self.SiDict['UTC_Offset'] = int(self.tcHrOffset.GetValue())
except:
self.SiDict['UTC_Offset'] = None
def onClick_BtnSave(self, event):
"""
If actionCode[0] = 'New', the SiteDetails is being created.
Attempt to create a new record and make the new record ID available.
If actionCode[0] = 'Edit', attempt to save any changes to the existing DB record
"""
self.FillDictFromPanel() # get all values before testing
# verify
stSiteName = self.SiDict['SiteName']
print "stSiteName:", stSiteName
if stSiteName == '':
wx.MessageBox('Need Site Name', 'Missing',
wx.OK | wx.ICON_INFORMATION)
self.tcSiteName.SetValue(stSiteName)
self.tcSiteName.SetFocus()
self.Scroll(0, 0) # the required controls are all at the top
return
maxLen = scidb.lenOfVarcharTableField('FieldSites', 'SiteName')
if maxLen < 1:
wx.MessageBox('Error %d getting [FieldSites].[SiteName] field length.' % maxLen, 'Error',
wx.OK | wx.ICON_INFORMATION)
return
if len(stSiteName) > maxLen:
wx.MessageBox('Max length for Site Name is %d characters.\n\nIf trimmed version is acceptable, retry.' % maxLen, 'Invalid',
wx.OK | wx.ICON_INFORMATION)
self.tcSiteName.SetValue(stSiteName[:(maxLen)])
self.tcSiteName.SetFocus()
self.Scroll(0, 0) # the required controls are all at the top
return
if self.SiDict['LatitudeDecDegrees'] == None:
wx.MessageBox('Need Latitude', 'Missing',
wx.OK | wx.ICON_INFORMATION)
self.tcLat.SetValue('')
self.tcLat.SetFocus()
self.Scroll(0, 0) # the required controls are all at the top
return
if self.SiDict['LongitudeDecDegrees'] == None:
wx.MessageBox('Need Longitude', 'Missing',
wx.OK | wx.ICON_INFORMATION)
self.tcLon.SetValue('')
self.tcLon.SetFocus()
self.Scroll(0, 0) # the required controls are all at the top
return
recID = scidb.dictIntoTable_InsertOrReplace('FieldSites', self.SiDict)
parObject = self.GetParent()
if parObject.GetClassName() == "wxDialog":
parObject.EndModal(0)
def onClick_BtnCancel(self, event):
"""
This frame is shown in a Dialog, which is its parent object.
"""
parObject = self.GetParent()
if parObject.GetClassName() == "wxDialog":
parObject.EndModal(0)
# ----------------------------------------------------------------------
# customized for drag/drop from list of Stations
# DragStationList
class DragStationList(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, *arg, **kw):
wx.ListCtrl.__init__(self, *arg, **kw)
ListCtrlAutoWidthMixin.__init__(self) # rightmost column will fill the rest of the list
self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._startDrag)
def _startDrag(self, e):
""" Put together a data object for drag-and-drop _from_ this list. """
l = ['Station']
# mostly need the ItemData, which is the record ID in the Stations table
idx = self.GetFirstSelected()
l.append(self.GetItemData(idx))
# as a convenience, pass the list row text
l.append(self.GetItemText(idx))
# and the ChannelSegment list column to put it in
l.append(0)
# Pickle the object
itemdata = cPickle.dumps(l, 1)
# create our own data format and use it in a
# custom data object
ldata = wx.CustomDataObject("RecIDandTable")
ldata.SetData(itemdata)
# Now make a data object for the item list.
data = wx.DataObjectComposite()
data.Add(ldata)
# Create drop source and begin drag-and-drop.
dropSource = wx.DropSource(self)
dropSource.SetData(data)
res = dropSource.DoDragDrop(flags=wx.Drag_DefaultMove)
# If move, we could remove the item from this list.
if res == wx.DragMove:
pass # disable removing, we only want to assign its info to the other list
# ----------------------------------------------------------------------
# customized for drag/drop from list of Series
# DragSeriesList
class DragSeriesList(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, *arg, **kw):
wx.ListCtrl.__init__(self, *arg, **kw)
ListCtrlAutoWidthMixin.__init__(self) # rightmost column will fill the rest of the list
self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._startDrag)
def _startDrag(self, e):
""" Put together a data object for drag-and-drop _from_ this list. """
l = ['Series']
# mostly need the ItemData, which is the record ID in the DataSeries table
idx = self.GetFirstSelected()
l.append(self.GetItemData(idx))
# as a convenience, pass the list row text
l.append(self.GetItemText(idx))
# and the ChannelSegment list column to put it in
l.append(1)
# Pickle the object
itemdata = cPickle.dumps(l, 1)
# create our own data format and use it in a
# custom data object
ldata = wx.CustomDataObject("RecIDandTable")
ldata.SetData(itemdata)
# Now make a data object for the item list.
data = wx.DataObjectComposite()
data.Add(ldata)
# Create drop source and begin drag-and-drop.
dropSource = wx.DropSource(self)
dropSource.SetData(data)
res = dropSource.DoDragDrop(flags=wx.Drag_DefaultMove)
# If move, we could remove the item from this list.
if res == wx.DragMove:
pass # disable removing, we only want to assign its info to the other list
# customized for drag/drop from list of ChannelSegments
# drag-TO is implemented, drag-FROM is disabled
# DragChannelSegmentList
class DragChannelSegmentList(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, *arg, **kw):
wx.ListCtrl.__init__(self, *arg, **kw)
ListCtrlAutoWidthMixin.__init__(self)
self.setResizeColumn(3) # Channel column will take up any extra spaces
dt = ListChannelSegmentDrop(self)
self.SetDropTarget(dt)
def _insert(self, x, y, lObj):
""" Target the drop to given x, y coordinates --- used with drag-and-drop. """
# Find insertion point.
index, flags = self.HitTest((x, y))
print "index from HitTest", index
print "flag from HitTest", flags
if index != wx.NOT_FOUND: # clicked on an item
ChanSegID = self.GetItemData(index)
stSQL = "UPDATE ChannelSegments SET " + lObj[0] + "ID = ? WHERE ID = ?;"
# if lObj[0] == 'Station':
# stSQL = "UPDATE ChannelSegments SET StationID = ? WHERE ID = ?;"
# if lObj[0] == 'Series':
# stSQL = "UPDATE ChannelSegments SET SeriesID = ? WHERE ID = ?;"
scidb.curD.execute(stSQL, (lObj[1], ChanSegID))
# on the next load, this change will show in the ChannelSegments list
# but for now just patch in the string
self.SetStringItem(index, lObj[3], lObj[2])
# maybe refresh entire list, but following formats are not quite right
# self.parent.fillChannelSegmentsList()
# framePanel.fillChannelSegmentsList()
# customized for drop to a list of ChannelSegments
# -----
# ListChannelSegmentDrop
class ListChannelSegmentDrop(wx.PyDropTarget):
""" Drop target for Channel Segments list.
Allows dropping Station/Series onto ChannelSegment to assign those handles
"""
def __init__(self, source):
""" Arguments:
- source: source listctrl.
"""
wx.PyDropTarget.__init__(self)
self.dv = source
# specify the type of data we will accept
self.data = wx.CustomDataObject("RecIDandTable")
self.SetDataObject(self.data)
# Called when OnDrop returns True. We need to get the data and
# do something with it.
def OnData(self, x, y, d):
# copy the data from the drag source to our data object
if self.GetData():
# convert it back to a list and give it to the viewer
ldata = self.data.GetData()
l = cPickle.loads(ldata)
self.dv._insert(x, y, l)
# what is returned signals the source what to do
# with the original data (move, copy, etc.) In this
# case we just return the suggested value given to us.
return d
class SetupStationsPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
self.InitUI()
def InitUI(self):
# improve this layout using wx.SplitterWindow instead
sizerWholeFrame = wx.GridBagSizer(5, 5)
hdr = wx.StaticText(self, label="Drag Stations and Series to assign them to Channel Segments")
sizerWholeFrame.Add(hdr, pos=(0, 0), span=(1, 2), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
hLine = wx.StaticLine(self)
sizerWholeFrame.Add(hLine, pos=(1, 0), span=(1, 3),
flag=wx.EXPAND|wx.BOTTOM, border=1)
sizerSta = wx.GridBagSizer(1, 1)
hdrStation = wx.StaticText(self, label="Stations:")
sizerSta.Add(hdrStation, pos=(0, 0), span=(1, 1),
flag=wx.ALIGN_LEFT|wx.TOP|wx.LEFT, border=1)
StbHorizSizer = wx.BoxSizer(wx.HORIZONTAL)
btnAddStation = wx.Button(self, label="New", size=(32, 20))
btnAddStation.Bind(wx.EVT_BUTTON, lambda evt, str=btnAddStation.GetLabel(): self.onClick_BtnWorkOnStation(evt, str))
StbHorizSizer.Add(btnAddStation)
btnEditStation = wx.Button(self, label="Edit", size=(32, 20))
btnEditStation.Bind(wx.EVT_BUTTON, lambda evt, str=btnEditStation.GetLabel(): self.onClick_BtnWorkOnStation(evt, str))
StbHorizSizer.Add(btnEditStation)
sizerSta.Add(StbHorizSizer, pos=(0, 1), span=(1, 1))
self.lstStations = DragStationList(self, style=wx.LC_REPORT|wx.LC_NO_HEADER|wx.LC_SINGLE_SEL)
self.lstStations.InsertColumn(0, "Station")
self.fillStationsList()
sizerSta.Add(self.lstStations, pos=(1, 0), span=(2, 2), flag=wx.EXPAND)
sizerSta.AddGrowableRow(1)
sizerSta.AddGrowableCol(1)
sizerWholeFrame.Add(sizerSta, pos=(2, 0), span=(1, 1),
flag=wx.EXPAND)
sizerSer = wx.GridBagSizer(1, 1)
hdrSeries = wx.StaticText(self, label="Series:")
sizerSer.Add(hdrSeries, pos=(0, 0), span=(1, 1),
flag=wx.ALIGN_LEFT|wx.TOP|wx.LEFT, border=1)
btnAddSeries = wx.Button(self, label="New", size=(32, 20))
btnAddSeries.Bind(wx.EVT_BUTTON, lambda evt, str=btnAddSeries.GetLabel(): self.onClick_BtnAddSeries(evt, str))
sizerSer.Add(btnAddSeries, pos=(0, 1), flag=wx.ALIGN_LEFT|wx.LEFT, border=10)
self.lstSeries = DragSeriesList(self, style=wx.LC_REPORT|wx.LC_NO_HEADER|wx.LC_SINGLE_SEL)
self.lstSeries.InsertColumn(0, "Series")
self.fillSeriesList()
sizerSer.Add(self.lstSeries, pos=(1, 0), span=(2, 2), flag=wx.EXPAND)
sizerSer.AddGrowableRow(1)
sizerSer.AddGrowableCol(1)
sizerWholeFrame.Add(sizerSer, pos=(2, 1), span=(1, 1),
flag=wx.EXPAND)
sizerChanSegs = wx.GridBagSizer(1, 1)
hdrChanSegs = wx.StaticText(self, label="Channel Segments:")
sizerChanSegs.Add(hdrChanSegs, pos=(0, 0), span=(1, 1), flag=wx.ALIGN_LEFT|wx.TOP, border=5)
self.lstChanSegs = DragChannelSegmentList(self, style=wx.LC_REPORT|wx.LC_VRULES|wx.LC_SINGLE_SEL)
self.lstChanSegs.InsertColumn(0, "Station")
self.lstChanSegs.InsertColumn(1, "Series")
self.lstChanSegs.InsertColumn(2, "Channel Segment (Col, Logger, Sensor, Type, Units, HrOffset)")
self.lstChanSegs.InsertColumn(3, "Start")
self.lstChanSegs.InsertColumn(4, "End")
self.fillChannelSegmentsList()
# 1. Register source's EVT_s to invoke pop-up menu launcher
wx.EVT_LIST_ITEM_RIGHT_CLICK(self.lstChanSegs, -1, self.lstChanSegsRightClick)
sizerChanSegs.Add(self.lstChanSegs, pos=(1, 0), span=(1, 2), flag=wx.EXPAND)
sizerChanSegs.AddGrowableRow(1)
sizerChanSegs.AddGrowableCol(1)
sizerWholeFrame.Add(sizerChanSegs, pos=(3, 0), span=(1, 3),
flag=wx.EXPAND)
sizerWholeFrame.AddGrowableCol(0)
sizerWholeFrame.AddGrowableCol(1)
sizerWholeFrame.AddGrowableRow(3)
self.SetSizerAndFit(sizerWholeFrame)
def fillStationsList(self):
scidb.fillListctrlFromSQL(self.lstStations, "SELECT ID, StationName FROM Stations;")
def fillSeriesList(self):
scidb.fillListctrlFromSQL(self.lstSeries, "SELECT ID, DataSeriesDescription FROM DataSeries;")
def fillChannelSegmentsList(self):
self.lstChanSegs.DeleteAllItems()
stSQL = """
SELECT ChannelSegments.ID,
COALESCE(Stations.StationName, '(none)') AS Station,
COALESCE( DataSeries.DataSeriesDescription, '(none)') AS Series,
DataChannels.Column || ', ' || Loggers.LoggerSerialNumber || ', ' ||
Sensors.SensorSerialNumber || ', ' || DataTypes.TypeText || ', ' ||
DataUnits.UnitsText || ', ' || DataChannels.UTC_Offset AS Channel,
COALESCE(ChannelSegments.SegmentBegin, '(open)') AS Begin,
COALESCE(ChannelSegments.SegmentEnd, '(open)') AS End
FROM ((((((ChannelSegments
LEFT JOIN Stations ON ChannelSegments.StationID = Stations.ID)
LEFT JOIN DataSeries ON ChannelSegments.SeriesID = DataSeries.ID)
LEFT JOIN DataChannels ON ChannelSegments.ChannelID = DataChannels.ID)
LEFT JOIN Loggers ON DataChannels.LoggerID = Loggers.ID)
LEFT JOIN Sensors ON DataChannels.SensorID = Sensors.ID)
LEFT JOIN DataTypes ON DataChannels.DataTypeID = DataTypes.ID)
LEFT JOIN DataUnits ON DataChannels.DataUnitsID = DataUnits.ID
ORDER BY Loggers.LoggerSerialNumber, DataChannels.Column, ChannelSegments.SegmentBegin;
"""
scidb.curD.execute(stSQL)
recs = scidb.curD.fetchall()
for rec in recs:
idx = self.lstChanSegs.InsertStringItem(sys.maxint, rec["Station"])
self.lstChanSegs.SetItemData(idx, rec["ID"])
self.lstChanSegs.SetStringItem(idx, 1, rec["Series"])
self.lstChanSegs.SetStringItem(idx, 2, rec["Channel"])
self.lstChanSegs.SetStringItem(idx, 3, rec["Begin"])
self.lstChanSegs.SetStringItem(idx, 4, rec["End"])
def onButton(self, event, strLabel):
""""""
print ' You clicked the button labeled "%s"' % strLabel
def onClick_BtnWorkOnStation(self, event, strLabel):
"""
"""
print "in onClick_BtnWorkOnStation"
if strLabel == "New":
dia = Dialog_StationDetails(self, wx.ID_ANY, actionCode = ['New', 0])
elif strLabel == "Edit":
staItem = self.lstStations.GetFocusedItem()
if staItem == -1:
wx.MessageBox('Select a Station to edit', 'No Selection',
wx.OK | wx.ICON_INFORMATION)
return
recNum = self.lstStations.GetItemData(staItem)
dia = Dialog_StationDetails(self, wx.ID_ANY, actionCode = ['Edit', recNum])
else:
return
# the dialog contains an 'InfoPanel_StationDetails' named 'pnl'
result = dia.ShowModal()
# dialog is exited using EndModal, and comes back here
print "Modal dialog result:", result
# test of pulling things out of the modal dialog
self.stationName = dia.pnl.tcStationName.GetValue()
print "Name of new station, from the Modal:", self.stationName
dia.Destroy()
self.fillStationsList()
def onClick_BtnAddSeries(self, event, strLabel):
"""
"""
dlg = wx.TextEntryDialog(None, "Name of Data Series you are adding to the database:", "New Data Series", " ")
answer = dlg.ShowModal()
if answer == wx.ID_OK:
stNewSeries = dlg.GetValue()
stNewSeries = " ".join(stNewSeries.split())
recID = scidb.assureItemIsInTableField(stNewSeries, "DataSeries", "DataSeriesDescription")
self.fillSeriesList()
else:
stNewSeries = ''
dlg.Destroy()
# def onClick_BtnNotWorkingYet(self, event, strLabel):
# wx.MessageBox('"Hello" is not implemented yet', 'Info',
# wx.OK | wx.ICON_INFORMATION)
def lstChanSegsRightClick(self, event):
# record what was clicked
self.list_item_clicked = right_click_context = event.GetText()
### 2. Launcher creates wxMenu. ###
menu = wx.Menu()
for (id,title) in listPopMenuItems_byID.items():
### 3. Launcher packs menu with Append. ###
menu.Append( id, title )
### 4. Launcher registers menu handlers with EVT_MENU, on the menu. ###
wx.EVT_MENU( menu, id, self.MenuSelectionCb )
### 5. Launcher displays menu with call to PopupMenu, invoked on the
#source component, passing event's GetPoint. ###
self.PopupMenu( menu, event.GetPoint() )
menu.Destroy() # destroy to avoid mem leak
def MenuSelectionCb( self, event ):
# do something according to what's picked in the popup
opID = event.GetId()
operation = listPopMenuItems_byID[opID]
print "operation:", operation
if operation == 'Add ending timestamp': # only one so far
print 'list_item_clicked', self.list_item_clicked
csItem = self.lstChanSegs.GetFocusedItem()
if csItem == -1:
wx.MessageBox('Right-click failed to get an item', 'No Selection',
wx.OK | wx.ICON_INFORMATION)
return
recNum = self.lstChanSegs.GetItemData(csItem)
print 'recNum', recNum
dia = Dialog_EndTimestamp(self, wx.ID_ANY, actionCode = ['Edit', recNum])
result = dia.ShowModal()
# dialog is exited using EndModal, and comes back here
print "Modal dialog result:", result
# # test of pulling things out of the modal dialog
# self.newBookName = dia.pnl.tcBookName.GetValue()
# print "Name of new book, from the Modal:", self.newBookName
# self.newRecID = dia.pnl.newRecID
# print "record ID from the Modal:", self.newRecID
dia.Destroy()
if result == 1: # new record successfully created
pass
self.fillChannelSegmentsList()
class SetupStationsFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
self.InitUI()
self.SetSize((750, 600))
# self.Centre()
self.Show(True)
def InitUI(self):
framePanel = SetupStationsPanel(self, wx.ID_ANY)
def main():
app = wx.App(redirect=False)
SetupStationsFrame(None, wx.ID_ANY, 'Assign Stations and Series')
app.MainLoop()
if __name__ == '__main__':
main()