-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcxn_editor.py
More file actions
executable file
·617 lines (552 loc) · 19.9 KB
/
cxn_editor.py
File metadata and controls
executable file
·617 lines (552 loc) · 19.9 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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import json
import os
import sys
from pathlib import Path
import cryptography
import dabo
from dabo import application
from dabo import db
from dabo import settings
from dabo import ui
from dabo.application import dApp
from dabo.lib import utils
from dabo.lib.connParser import createXML
from dabo.lib.connParser import importConnections
from dabo.lib.utils import ustr
from dabo.localization import _
from dabo.ui import dButton
from dabo.ui import dDropdownList
from dabo.ui import dForm
from dabo.ui import dGridSizer
from dabo.ui import dLabel
from dabo.ui import dPanel
from dabo.ui import dSizer
from dabo.ui import dTextBox
import home_directory_status_bar
dabo_module = settings.get_dabo_package()
def flushValues(fnc):
def _wrapped(self, *args, **kwargs):
self.updtFromForm()
return fnc(self, *args, **kwargs)
return _wrapped
class EditorForm(dForm):
connFile = None
def afterSetMenuBar(self):
self.createMenu()
def beforeInit(self):
self.StatusBarClass = home_directory_status_bar.HomeDirectoryStatusBar
def afterInit(self):
self.Size = (600, 400)
self.newFileName = "Untitled"
self.fileExtension = "cnxml"
self.defDbPorts = {
"MySQL": 3306,
"Firebird": 3050,
"PostgreSQL": 5432,
"MsSQL": 1433,
"SQLite": None,
}
self.connDict = {}
self._origConnDict = {}
self.connKeys = [
"name",
"host",
"dbtype",
"port",
"database",
"user",
"password",
]
self.currentConn = self._defaultConnName()
# Make sure that they are defined as form attributes
for ck in self.connKeys:
setattr(self, ck, None)
# If we're opening a cnxml file that was saved with a CryptoKey, this
# flag will indicate that the user should be prompted.
self._opening = False
# all set up; now add stuff!
self.createControls()
# temp hack to be polymorphic with dEditor (dIDE):
self.editor = self
def createMenu(self):
mb = self.MenuBar
fm = mb.getMenu("base_file")
fm.prepend(
_("Open Connection File..."),
HotKey="Ctrl+O",
OnHit=self.onOpenFile,
ItemID="file_open",
help=_("Open an existing connection file"),
)
def onOpenFile(self, evt):
self.openFile()
def createControls(self):
self._set_title()
self.bg = dPanel(self, BackColor="LightSteelBlue")
gbsz = dGridSizer(VGap=12, HGap=5, MaxCols=2)
# Add the fields
# Connection Dropdown
cap = dLabel(self.bg, Caption=_("Connection"))
ctl = dDropdownList(
self.bg,
Choices=list(self.connDict.keys()),
RegID="connectionSelector",
OnHit=self.onConnectionChange,
)
btn = dButton(self.bg, Caption=_("Edit Name"), RegID="cxnEdit", OnHit=self.onCxnEdit)
hsz = dSizer("h")
hsz.append(ctl)
hsz.appendSpacer(10)
hsz.append(btn)
btn = dButton(
self.bg,
Caption=_("Delete This Connection"),
RegID="cxnDelete",
DynamicEnabled=self.hasMultipleConnections,
OnHit=self.onCxnDelete,
)
hsz.appendSpacer(10)
hsz.append(btn)
gbsz.append(cap, halign="right", valign="middle")
gbsz.append(hsz, valign="middle")
# Backend Type
cap = dLabel(self.bg, Caption=_("Database Type"))
ctl = dDropdownList(
self.bg,
RegID="DbType",
Choices=["MySQL", "Firebird", "PostgreSQL", "MsSQL", "SQLite"],
DataSource="form",
DataField="dbtype",
OnHit=self.onDbTypeChanged,
)
gbsz.append(cap, halign="right")
gbsz.append(ctl)
self.dbTypeSelector = ctl
# Host
cap = dLabel(self.bg, Caption=_("Host"))
ctl = dTextBox(self.bg, DataSource="form", DataField="host")
gbsz.append(cap, halign="right")
gbsz.append(ctl, "expand")
self.hostText = ctl
# Port
cap = dLabel(self.bg, Caption=_("Port"))
ctl = dTextBox(self.bg, DataSource="form", DataField="port")
gbsz.append(cap, halign="right")
gbsz.append(ctl, "expand")
self.portText = ctl
# Database
cap = dLabel(self.bg, Caption=_("Database"))
ctl = dTextBox(self.bg, DataSource="form", DataField="database")
hsz = dSizer("h")
self.btnDbSelect = dButton(
self.bg,
Caption=" ... ",
RegID="btnDbSelect",
Visible=False,
OnHit=self.onDbSelect,
)
hsz.append1x(ctl)
hsz.appendSpacer(2)
hsz.append(self.btnDbSelect, 0, "x")
gbsz.append(cap, halign="right")
gbsz.append(hsz, "expand")
self.dbText = ctl
# Username
cap = dLabel(self.bg, Caption=_("User Name"))
ctl = dTextBox(self.bg, DataSource="form", DataField="user")
gbsz.append(cap, halign="right")
gbsz.append(ctl, "expand")
self.userText = ctl
# Password
cap = dLabel(self.bg, Caption=_("Password"))
ctl = dTextBox(self.bg, PasswordEntry=True, DataSource="form", DataField="password")
gbsz.append(cap, halign="right")
gbsz.append(ctl, "expand")
self.pwText = ctl
# Open Button
btnSizer1 = dSizer("h")
btnSizer2 = dSizer("h")
btnTest = dButton(self.bg, RegID="btnTest", Caption=_("Test..."), OnHit=self.onTest)
btnSave = dButton(self.bg, RegID="btnSave", Caption=_("Save"), OnHit=self.onSave)
btnNewConn = dButton(
self.bg,
RegID="btnNewConn",
Caption=_("New Connection"),
OnHit=self.onNewConn,
)
btnNewFile = dButton(
self.bg, RegID="btnNewFile", Caption=_("New File"), OnHit=self.onNewFile
)
btnOpen = dButton(self.bg, RegID="btnOpen", Caption=_("Open File..."), OnHit=self.onOpen)
btnSizer1.append(btnTest, 0, border=3)
btnSizer1.append(btnSave, 0, border=3)
btnSizer2.append(btnNewConn, 0, border=3)
btnSizer2.append(btnNewFile, 0, border=3)
btnSizer2.append(btnOpen, 0, border=3)
gbsz.setColExpand(True, 1)
self.gridSizer = gbsz
sz = self.bg.Sizer = dSizer("v")
sz.append(gbsz, 0, "expand", border=20)
sz.append(btnSizer1, 0, halign="center")
sz.append(btnSizer2, 0, halign="center")
self.cryptoKeyButton = dButton(self.bg, Caption=_("Set Crypto Key"), OnHit=self.onSetCrypto)
btnSizer1.append(self.cryptoKeyButton, 0, border=3)
self.Sizer = dSizer("h")
self.Sizer.append(self.bg, 1, "expand", halign="center")
self.Layout()
def hasMultipleConnections(self):
return len(self.connDict) > 1
def onCxnDelete(self, evt):
if not ui.areYouSure(
_("Delete this connection?"),
title=_("Confirm Deletion"),
cancelButton=False,
):
return
cs = self.connectionSelector
delkey = cs.StringValue
pos = cs.PositionValue
del self.connDict[delkey]
cs.Choices = list(self.connDict.keys())
cs.PositionValue = min(pos, len(self.connDict) - 1)
self.currentConn = cs.StringValue
self.enableControls()
self.updtToForm()
self.update()
def onCxnEdit(self, evt):
chc = self.connectionSelector.Choices
idx = self.connectionSelector.PositionValue
orig = chc[idx]
new = ui.getString(
_("Enter the name for the connection"),
caption=_("Connection Name"),
defaultValue=orig,
)
if new is not None:
if new != orig:
chc[idx] = new
self.connectionSelector.Choices = chc
# Update the connection dict, too
oldVal = self.connDict[orig]
self.connDict[new] = oldVal
del self.connDict[orig]
self.connDict[new]["name"] = new
self.currentConn = new
self.name = new
self.connectionSelector.PositionValue = idx
self._set_title()
def onSetCrypto(self, evt):
key = self._askForKey()
if key:
self.Application.CryptoKey = key
self.updtFromForm()
def _set_title(self):
conn_name = Path(self.connFile).stem if self.connFile else self._defaultConnName()
self.Caption = _(f"Dabo Connection Editor: {conn_name}")
def _askForKey(self):
pw = ui.getString(
_("Enter the cryptographic password for your application"),
caption=_("Crypto Password"),
Width=240,
)
salt = ui.getString(
_("Enter the cryptographic salt value for your application"),
caption=_("Crypto Salt"),
Width=240,
)
return (pw, salt)
def onTest(self, evt):
self.testConnection()
@flushValues
def onOpen(self, evt):
# Now open the file
self.openFile()
@flushValues
def onNewFile(self, evt):
# See if the user wants to save changes (if any)
if not self.confirmChanges():
return
self.newFile()
@flushValues
def onNewConn(self, evt):
# Create the new connection
self.newConnection()
def onSave(self, evt):
self.saveFile()
@flushValues
def onDbTypeChanged(self, evt):
self.enableControls()
if self.defDbPorts[self.dbtype] is None:
self.port = ""
else:
self.port = self.defDbPorts[self.dbtype]
self.update()
def isFileBasedBackend(self, dbtype):
return dbtype in ("SQLite",)
def enableControls(self):
dbt = self.dbtype
isFileBased = self.isFileBasedBackend(dbt)
self.hostText.Visible = not isFileBased
self.portText.Visible = not isFileBased
self.userText.Visible = not isFileBased
self.pwText.Visible = not isFileBased
self.btnDbSelect.Visible = isFileBased
if isFileBased:
self.dbText.setFocus()
self.layout()
def onDbSelect(self, evt):
dbFile = ui.getFile()
if dbFile:
self.database = dbFile
self.update()
@flushValues
def testConnection(self):
# Create a connection object.
ci = db.dConnectInfo(connInfo=self.connDict[self.currentConn])
mb = ui.stop
mbTitle = _("Connection Test")
try:
conn = ci.getConnection()
conn.close()
msg = _("The connection was successful!")
mb = ui.info
except ImportError as e:
msg = _("Python Import Error: %s") % e
mbTitle += _(": FAILED!")
except Exception as e:
msg = _("Could not connect to the database: %s") % e
mbTitle += _(": FAILED!")
mb(message=msg, title=mbTitle)
def updtFromForm(self):
"""Grab the current values from the form, and update
the connection dictionary with them.
"""
# Make sure that changes to the current control are used.
self.activeControlValid()
if self.currentConn is not None:
dd = self.connDict.get(self.currentConn, {})
for fld in list(dd.keys()):
val = getattr(self, fld)
if fld == "password":
try:
origVal = self.Application.decrypt(dd[fld])
except ValueError:
# Original crypto key not available
origVal = None
else:
origVal = dd[fld]
if val == origVal:
continue
if fld == "password":
dd[fld] = self.Application.encrypt(val)
else:
dd[fld] = val
def updtToForm(self):
"""Populate the current values from the connection dictionary."""
if self.currentConn is not None:
dd = self.connDict[self.currentConn]
for fld in list(dd.keys()):
val = dd[fld]
if fld == "password":
try:
val = self.Application.decrypt(dd[fld])
except (ValueError, cryptography.fernet.InvalidToken):
# Original crypto key not available
if self._opening:
ui.callAfter(self._getCryptoKey, dd[fld])
continue
else:
val = ""
setattr(self, fld, val)
def _getCryptoKey(self, crypted):
# Give them a chance to set the CryptoKey
val = ""
key = self._askForKey()
if key:
self.Application.CryptoKey = key
val = self.Application.decrypt(crypted)
setattr(self, "password", val)
self.update()
def _blankConnection(self):
return dict.fromkeys(self.connKeys)
def _defaultConnName(self):
return "Connection_" + ustr(len(list(self.connDict.keys())) + 1)
def newFile(self):
self.connFile = self.newFileName
self.currentConn = self._defaultConnName()
self.newConnection()
self._origConnDict = copy.deepcopy(self.connDict)
# Set the form caption
self._set_title()
# Fill the controls
self.populate()
@flushValues
def newConnection(self):
# Get the current dbtype
currDbType = None
if (self.currentConn is not None) and (self.currentConn in self.connDict):
currDbType = self.connDict[self.currentConn]["dbtype"]
if not currDbType:
currDbType = "MySQL"
newName = self._defaultConnName()
self.connDict[newName] = {
"dbtype": currDbType,
"name": newName,
"host": "",
"database": "",
"user": "",
"password": "",
"port": self.defDbPorts[currDbType],
}
self.currentConn = newName
self.connectionSelector.Choices = list(self.connDict.keys())
self.populate()
@flushValues
def saveFile(self):
if self._origConnDict != self.connDict:
self.writeChanges()
self._origConnDict = copy.deepcopy(self.connDict)
def onConnectionChange(self, evt):
newConn = self.connectionSelector.StringValue
if newConn != self.currentConn:
# Update the values
self.updtFromForm()
self.currentConn = newConn
self.populate()
def setFieldVal(self, fld, val):
"""This will get called when the control detects a changed value. We
need to update the current dict with the new value.
"""
try:
dd = self.connDict[self.currentConn]
if fld == "password":
if val != self.Application.decrypt(dd["password"]):
dd[fld] = self.Application.encrypt(val)
else:
dd[fld] = val
except Exception as e:
print(_("Can't update:"), e)
def populate(self):
self.updtToForm()
self.update()
conn = self.currentConn
cs = self.connectionSelector
if conn not in cs.Choices:
cs.Choices.append(conn)
self.connectionSelector.Value = conn
@flushValues
def openFile(self, connFile=None):
# See if the user wants to save changes (if any)
if not self.confirmChanges():
return
self.connFile = Path(connFile)
# Read in the connection def file
if self.connFile:
# Make sure that the passed file exists!
if not self.connFile.exists():
dabo_module.log_error(_(f"The connection file '{self.connFile}' does not exist."))
self.connFile = None
if self.connFile is None:
f = ui.getFile(
self.fileExtension,
message=_("Select a file..."),
defaultPath=Path().cwd(),
)
if f is not None:
self.connFile = f
if self.connFile is not None:
self.connFile = ustr(self.connFile)
# Read the XML into a local dictionary
self.connDict = importConnections(self.connFile)
# Save a copy for comparison
self._origConnDict = copy.deepcopy(self.connDict)
# Populate the connection names
self.connectionSelector.Choices = list(self.connDict.keys())
# Set the current connection
self.currentConn = list(self.connDict.keys())[0]
# Set the form caption
self._set_title()
# Fill the controls
self._opening = True
self.populate()
self._opening = False
# Show/hide controls as needed
self.enableControls()
self.layout()
return True
else:
return False
@flushValues
def confirmChanges(self):
if self._origConnDict != self.connDict:
# Could be relative path differences
self.relPaths(list(self.connDict.values()))
if self._origConnDict != self.connDict:
response = ui.areYouSure(_("Do you wish to save your changes?"), cancelButton=True)
if response is None:
return False
elif response:
self.writeChanges()
return True
def writeChanges(self):
if self.connFile == self.newFileName:
# Ask for a file name
pth = ui.getSaveAs(message=_("Save File As..."), wildcard=self.fileExtension)
if pth is None:
return
else:
pth = Path(pth)
pthName = pth.stem
pthExt = pth.suffix.replace(".", "")
if not pthExt == self.fileExtension:
# Add the extension
pth = Path(f"{pthName}.{self.fileExtension}")
self.connFile = pth
self.connFile = Path(self.connFile)
# Get the values from the connDict, and adjust any pathing to be relative
vals = self.relPaths(list(self.connDict.values()))
v0 = vals[0]
if self.isFileBasedBackend(v0["dbtype"]):
# Previous values from the form might still be in the dict.
# Blank them out, as they are not valid for file-based backends.
v0["host"] = v0["user"] = v0["password"] = v0["port"] = ""
xml = createXML(vals, encoding="utf-8")
self.connFile.write_text(xml)
with open(self.connFile, "w") as ff:
ff.write(xml)
# Write to JSON
self.json_file = self.connFile.with_suffix(".json")
self.json_file.write_text(json.dumps(vals))
ui.callAfter(self.bringToFront)
def relPaths(self, vals):
for val in vals:
if self.isFileBasedBackend(val["dbtype"]):
db = val["database"]
if os.path.exists(db):
val["database"] = utils.relativePath(db, self.Application.HomeDirectory)
return vals
def run_editor(filepaths=None):
app = dApp(ignoreScriptDir=True)
app.BasePrefKey = "CxnEditor"
app.MainFormClass = None
app.setup()
if not filepaths:
# The form can either edit a new file, or the user can open the file
# from the form
frm = EditorForm()
frm.newFile()
frm.show()
else:
for pth in filepaths:
frm = EditorForm()
frm.openFile(pth)
if frm.connFile:
frm.show()
else:
frm.close()
app.start()
if __name__ == "__main__":
run_editor(filepaths=sys.argv[1:])