forked from GeODinTeam/GeODinQGIS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeODinQGIS_Main.py
1900 lines (1641 loc) · 75 KB
/
GeODinQGIS_Main.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
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GeODinQGIS
A QGIS plugin
This plugin connects GeODin with QGIS
-------------------
begin : 2015-02-16
git sha : $Format:%H$
copyright : (C) 2015 by Fugro Consult GmbH
email : www.fugro.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import codecs
from ui_Files.ui_GeODinQGIS_Main import Ui_GeODinQGISMain
import os, sys, struct, time, logging, datetime, locale, ctypes, binascii, win32com.client, qgis.utils
try:
import pyodbc
except:
from pythonmodules import pypyodbc
print "Main: Can not import pyodbc maybe it is needed."
try:
import psycopg2
except:
print "Main: Can not import psycopg2 maybe it is needed."
from pythonmodules import _mysql
from pythonmodules.helpFunction import *
from _winreg import *
from GeODinQGIS_NewObject import NewObject
from GeODinQGIS_Shape import *
from GeODinQGIS_DragShp import DragShp
from GeODinQGIS_Settings import Settings
try:
from extras.layout import *
from extras.opengeodin import *
except Exception,e:
print str(e)
class GeODinQGISMain(QDockWidget, Ui_GeODinQGISMain):
def __init__(self, iface):
# setup UI and connect the buttons
QDockWidget.__init__(self)
self.iface = iface
self.setupUi(self)
self.qgisVersion = qgis.utils.QGis.QGIS_VERSION
# local path for plugin
self.pluginDirectory = os.path.dirname(__file__)
if "Users" in self.pluginDirectory:
self.userPluginDirectory = self.pluginDirectory
else:
self.userPluginDirectory = 'C:/Users/'+os.environ.get( "USERNAME" )+'/.qgis2/python/plugins/GeODinQGIS'
# path of tmp folder in home directory
self.tmpDirectory = self.userPluginDirectory+'/tmp'
self.GeODin = None
# path of log folder in home directory
self.logDirectory = self.userPluginDirectory+'/logs'
# path of config file in home directory
self.configFile = self.userPluginDirectory+'/config.cfg'
# store NewObject object
self.crd = None
self.layoutDialog = None
# actual language icon
self.activeIcon = ''
self.UserADODataBases = False
self.error = 0
self.config = ConfigParser()
# set plugin icons
self.geodinicon = QIcon(":/plugins/GeODinQGIS/icons/logo.png")
self.dbicon = QIcon(":/plugins/GeODinQGIS/icons/i_484F.png")
self.dbicon_open = QIcon(":/plugins/GeODinQGIS/icons/i_485F.png")
self.dbicon_del = QIcon(":/plugins/GeODinQGIS/icons/i_102F.png")
self.prjicon = QIcon(":/plugins/GeODinQGIS/icons/i_099F.png")
self.prjicon_open = QIcon(":/plugins/GeODinQGIS/icons/i_101F.png")
self.objicon = QIcon(":/plugins/GeODinQGIS/icons/i_126F.png")
self.objicon_type = QIcon(":/plugins/GeODinQGIS/icons/i_222F.png")
self.objicon_single = QIcon(":/plugins/GeODinQGIS/icons/i_232F.png")
self.new_obj = QIcon(":/plugins/GeODinQGIS/icons/i_100F.png")
self.docicon = QIcon(":/plugins/GeODinQGIS/icons/i_157F.png")
self.shpicon = QIcon(":/plugins/GeODinQGIS/icons/i_246F.png")
self.queryIcon = QIcon(":/plugins/GeODinQGIS/icons/i_090F.png")
self.ownQueryIcon = QIcon(":/plugins/GeODinQGIS/icons/i_0815F.png")
# set button signals
QObject.connect(self.singleImportButton, SIGNAL("clicked()"), self.loadMultipleDatabases)
QObject.connect(self.multipleImportButton, SIGNAL("clicked()"), self.loadSingleDatabase)
QObject.connect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer *)"), self.layerActivationChanged)
# tool tips
self.singleImportButton.setToolTip('Import Databases')
self.singleImportButton.setFont(QFont('OldEnglish', 10))
self.multipleImportButton.setToolTip('Load Databases')
self.multipleImportButton.setFont(QFont('OldEnglish', 10))
# set treeWidget signals
self.connect(self.treeWidget, SIGNAL("itemExpanded(QTreeWidgetItem*)"), self.expanded)
self.connect(self.treeWidget, SIGNAL("itemCollapsed(QTreeWidgetItem*)"), self.collapsed)
#self.connect(self.treeWidget, SIGNAL("itemDoubleClicked(QTreeWidgetItem*, int)"), self.buildTree)
self.connect(self.treeWidget, SIGNAL("itemSelectionChanged ()"), self.activateItem)
self.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.treeWidget.customContextMenuRequested.connect(self.treeMenu)
self.treeWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
#self.treeWidget.setDragEnabled(True)
# connect to dictionary, English language by default
self.dictionary = Dict(os.path.join(self.pluginDirectory, 'lang/all.lang'))
#self.givenObj = ''
# use language of operating system, if possible
# if not use english as default
osLanguage = locale.windows_locale[ctypes.windll.kernel32.GetUserDefaultUILanguage()].split('_')[0]
if osLanguage in self.dictionary.getLanguages():
self.lang = osLanguage
else:
self.lang = 'en'
# if plugin directory of QGIS is not set, create it
try:
if not os.path.isdir(self.userPluginDirectory):
os.makedirs(self.userPluginDirectory)
except WindowsError as e:
if e.errno == 13:
uc = UserChooser(self.dictionary.getWord(self.lang,"Choose your home directory."))
if uc.okPressed:
self.userPluginDirectory = 'C:/Users/'+uc.user+'/.qgis2/python/plugins/GeODinQGIS'
uc = None
try:
if not os.path.isdir(self.userPluginDirectory):
os.makedirs(self.userPluginDirectory)
except Exception,e:
QMessageBox.information(None,self.dictionary.getWord(self.lang,"Error"),str(e))
self.error = 1
return
# path of tmp folder in home directory
self.tmpDirectory = self.userPluginDirectory+'/tmp'
# path of tmp directory for restoring it, if lost
self.def_tmp_dir = self.tmpDirectory
# path of log folder in home directory
self.logDirectory = self.userPluginDirectory+'/logs'
# path of config file in home directory
self.configFile = self.userPluginDirectory+'/config.cfg'
# if log directory not available, create it
if not os.path.isdir(self.logDirectory):
os.makedirs(self.logDirectory)
open(self.logDirectory+'/error.log', 'a').close()
else:
open(self.logDirectory+'/error.log', 'w').close()
# create error logger
self.lgr = logging.getLogger('GeODinQGIS')
if not len(self.lgr.handlers):
self.lgr.setLevel(logging.DEBUG)
# add a file handler
fh = logging.FileHandler(self.logDirectory+'/error.log')
fh.setLevel(logging.DEBUG)
# create a formatter and set the formatter for the handler.
frmt = logging.Formatter('%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d: %(message)s', "%Y-%m-%d %H:%M:%S")
fh.setFormatter(frmt)
# add the Handler to the logger
self.lgr.addHandler(fh)
# if tmp directory not set, create it
if not os.path.isdir(self.tmpDirectory):
os.makedirs(self.tmpDirectory)
# if config file not available, create it
# set sections and default settings in config file
if not os.path.isfile(self.configFile):
self.config.add_section('Databases')
self.config.add_section('Options')
self.config.set('Options', 'lang', self.lang)
self.config.set('Options', 'project', 'tmp.qgs')
self.config.set('Options', 'geodinrootdir', self.getGeodinPath())
self.config.set('Options', 'programdata', self.getProgramData())
self.config.set('Options', 'suppressattribute', 'False')
self.config.set('Options', 'savelayer', 'True')
self.config.set('Options', 'tmpdirectory', self.tmpDirectory)
self.config.add_section('Layouts')
self.saveConfig()
self.changeLang(self.lang)
self.config.read(self.configFile)
# self.config.readfp(codecs.open(self.configFile, "r", "utf-8"))
# call config file checker
self.configChecker()
# get language option from config file
self.lang = self.config.get('Options', 'lang')
# change language according to config file
self.changeLang(self.lang)
# get root directory of GeODin installation
self.geodin_dir = self.config.get('Options', 'geodinrootdir')
self.dbs = []
# map over databases written to config file
for db in self.config.options('Databases'):
fn = self.config.get('Databases', db)
alias = fn.split('/')[-1][:-4]
if os.path.exists(fn):
options = {}
options["uname"] = ""
options["upassword"] = ""
options["connection"] = "ODBC"
database = Database(alias, fn)
database.options = options
self.newTopLevelItem(database)
else:
self.config.remove_option('Databases', db)
# check if config has the sections "Databases" and "Options"
# add content to sections
if "Databases" not in self.config.sections():
self.config.add_section('Databases')
if "Options" not in self.config.sections():
self.config.add_section('Options')
self.config.set('Options', 'lang', self.lang)
self.config.set('Options', 'project', 'tmp.qgs')
self.config.set('Options', 'geodinrootdir', self.getGeodinPath())
self.config.set('Options', 'programdata', self.getProgramData())
self.config.set('Options', 'suppressattribute', 'False')
self.config.set('Options', 'savelayer', 'True')
self.config.set('Options', 'tmpdirectory', self.tmpDirectory)
if "Layouts" not in self.config.sections():
self.config.add_section('Layouts')
self.saveConfig()
self.changeLang(self.lang)
self.saveConfig()
self.deny = 0
self.inProcess = False
def getBuild(self):
# enter registry and get GeODin build number
key = OpenKey(HKEY_CURRENT_USER, r"Software\GeODin-System\System", 0, KEY_READ)
build, dummy = QueryValueEx(key, 'Build')
CloseKey(key)
self.lgr.info('GeODin build Number: {0}'.format(build))
def checkVersion(self):
# check Python version, complying with the QGIS version
# version must be 32-bit
if struct.calcsize("P") * 8 != 32:
self.lgr.info("QGIS Python version: 64 Bit")
QMessageBox.warning(self, "Warning", "Only for 32 bit python. Databases can not be opened.")
else:
self.lgr.info("QGIS Python version: 32 Bit")
def configChecker(self):
# set default config array to check
configArray = {"Databases":{}, "Options":{"lang":self.lang, "project":'tmp.qgs', "geodinrootdir":self.getGeodinPath(), "programdata":self.getProgramData(), "suppressattribute":"False", "savelayer":"True", "tmpdirectory":self.tmpDirectory}, "Layouts":{}}
# map over config array
# check config consistency and restore if necessary
for f in configArray.keys():
if f in self.config.sections():
for i in configArray[f].keys():
if i not in self.config.options(f):
self.config.set(f, i, configArray[f][i])
else:
self.config.add_section(f)
for i in configArray[f]:
self.config.set(f, i, configArray[f][i])
self.config.set("Options", "geodinrootdir", configArray["Options"]["geodinrootdir"])
self.saveConfig()
def loadMultipleDatabases(self):
self.readGeodinini()
# access key from Windows Registry
# open main database folder
key = None
try:
key = OpenKey(HKEY_CURRENT_USER, r"Software\GeODin-System\Database", 0, KEY_READ)
# raise WindowsError
except WindowsError as e:
self.lgr.info('{0}: {1}'.format(e, r"Computer\HKEY_CURRENT_USER\Software\GeODin-System\System"))
QMessageBox.information(None,self.dictionary.getWord(self.lang,"Connection Error"),self.dictionary.getWord(self.lang,"No GeODin database connections found."))
return
# loop through subkeys
i=0
while True:
database = Database()
options = None
path = None
try:
asubkey_name = EnumKey(key,i) # numerate through folder, get subkeys (folder name = database name)
except:
break
try:
asubkey = OpenKey(key,asubkey_name) # open subkeys (database folders)
try:
if len(QueryValueEx(asubkey, "ADOConnection")[0]):
options, path = self.getConnectionOptions(QueryValueEx(asubkey, "ADOConnection")[0], "ADOConnection", asubkey_name)
except AttributeError as e:
self.lgr.error(e)
except KeyError as e:
self.lgr.error(asubkey_name+": "+str(e))
except IndexError as e:
pass
except Exception,e:
self.lgr.error(e)
pass
try:
if not options:
options, path = self.getConnectionOptions(QueryValueEx(asubkey, "FireDACConnection")[0], "FireDACConnection", asubkey_name)
except WindowsError as e:
self.lgr.error(e)
except AttributeError as e:
self.lgr.error(e)
except KeyError as e:
self.lgr.error(e)
except Exception,e:
self.lgr.error(e)
pass
database.name = asubkey_name
database.system = self.UserADODataBases
database.filepath = path.replace("\\","/")
database.options = options
if path not in [db.filepath for db in self.dbs]:
self.newTopLevelItem(database)
else:
# if database has been loaded yet, check if listed in Config and delete from there
# because it's also located in the registry
for db in self.config.options('Databases'):
fn = self.config.get('Databases', db)
if fn == path:
self.config.remove_option('Databases', db)
self.saveConfig()
except TypeError as e:
self.lgr.error(e)
pass
except UnicodeEncodeError as e:
self.lgr.error(e)
pass
except UnicodeDecodeError as e:
self.lgr.error(e)
pass
except NameError as e:
self.lgr.error(e)
pass
except AttributeError as e:
self.lgr.error(e)
pass
except Exception,e:
self.lgr.error(e)
pass
i+=1
if key:
CloseKey(key)
def getConnectionOptions(self, connectionString, key, name):
#transforms the option string from registry to dictionary
#returns a options dictionary and a file path to the database
options = {}
options["ip"] = "127.0.0.1"
options["uname"] = ""
options["upassword"] = ""
path = ""
for option in connectionString.split(';'):
try:
options[option.split('=')[0]]=option.split('=')[1]
except IndexError as e:
self.lgr.error("string '" + option + "' returns " + str(e))
pass
if key.lower() == "adoconnection":
if "Provider" in options.keys():
options["connection"] = options.pop("Provider")
if "sqloledb.1" in options["connection"].lower():
options["connection"] = "MSQL"
elif "oledb" in options["connection"].lower():
options["connection"] = "ODBC"
elif "msdaora.1" in options["connection"].lower():
options["connection"] = "Oracle"
elif "sqlserver" in options["connection"].lower():
options["connection"] = "SQLCE"
elif "msdasql" in options["connection"].lower():
options["connection"] = "DSNConnection"
if "Data Source" in options.keys():
if options["connection"].lower() == "msql":
options["ip"] = options.pop("Data Source")
elif options["connection"].lower() == "odbc" or options["connection"].lower() == "sqlce":
path = options["Data Source"]
elif options["connection"].lower() == "oracle":
options["ip"] = options["Data Source"].split('/')[0]
options["database"] = options["Data Source"].split('/')[1]
elif options["connection"].lower() == "dsnconnection":
options["DSN"] = options.pop("Data Source")
if "Initial Catalog" in options.keys():
options["database"] = options.pop("Initial Catalog")
if "User ID" in options.keys():
options["uname"] = options.pop("User ID")
if "Password" in options.keys():
options["upassword"] = options.pop("Password")
elif key.lower() == "firedacconnection":
if "DriverID" in options.keys():
options["connection"] = options.pop("DriverID")
if "msacc" in options["connection"].lower():
options["connection"] = "ODBC"
path = options["Database"]
del options["Database"]
elif "mssql" in options["connection"].lower():
options["connection"] = "MSSQL"
options["database"] = options.pop("Database")
elif "ora" in options["connection"].lower():
options["connection"] = "Oracle"
if len(options["Database"].split('/')) == 2:
options["ip"] = options["Database"].split('/')[0]
options["database"] = options["Database"].split('/')[1]
elif len(options["Database"].split('/')) == 1:
options["database"] = options["Database"].split('/')[0]
del options["Database"]
elif "mysql" in options["connection"].lower():
options["connection"] = "MySQL"
options["database"] = options.pop("Database")
elif "pg" in options["connection"].lower():
options["connection"] = "PostgreSQL"
options["database"] = options.pop("Database")
if "Server" in options.keys():
options["ip"] = options.pop("Server")
if "User_Name" in options.keys():
options["uname"] = options.pop("User_Name")
if "Password" in options.keys():
options["upassword"] = options.pop("Password")
if not len(path) and "database" in options.keys():
#if it is no local database, create a pseudo path
path = options["ip"]+'/'+name
else:
del options["ip"]
return options, path.replace('\\','/')
def saveConfig(self):
# write settings to config file to save them
with codecs.open(self.configFile, 'wb', encoding='utf-8') as configfile:
self.config.write(configfile)
# self.config.write(codecs.open(self.configFile,'wb+','utf-8'))
def loadSingleDatabase(self, database=None):
#load a local access database
try:
fileName = QFileDialog.getOpenFileName(None, self.dictionary.getWord(self.lang,"Open database"), "C:/", "Microsoft Access(*.accdb;*.mdb)")
if fileName and fileName not in [db.filepath for db in self.dbs]:
if database == None:
database = Database(fileName.split('/')[-1][:-4])
options = {}
options["uname"] = ""
options["upassword"] = ""
options["connection"] = "ODBC"
database.options = options
self.config.set('Databases', database.name, fileName)
self.saveConfig()
database.filepath = fileName.replace("\\","/")
self.newTopLevelItem(database)
return 1
except Exception,e:
self.lgr.error(e)
return 0
return 0
def getGeodinPath(self):
#get the GeODin installation path from registry
#return path or empty string
try:
key = OpenKey(HKEY_CURRENT_USER, r"Software\GeODin-System\System", 0, KEY_READ)
path, regtype = QueryValueEx(key, 'RootDir')
CloseKey(key)
except WindowsError as e:
self.lgr.info('{0}: {1}'.format(e, r"Computer\HKEY_CURRENT_USER\Software\GeODin-System\System"))
QMessageBox.information(None,self.dictionary.getWord(self.lang,"Connection Error"),self.dictionary.getWord(self.lang,"No GeODin installation found."))
return ''
return path.replace('\\','/')
def getProgramData(self):
# get the geodin program information from geodin.ini
# return path
# try:
# geodin_path = self.getGeodinPath()
# # locate geodin.ini in installation folder
# ini = geodin_path + "\\GEODIN.INI"
#
# # read geodin.ini and get path to program data
# geodinConfig = ConfigParser()
# geodinConfig.read(ini)
# path_data = geodinConfig.get('SYSTEM', 'ProgramData')
#
# except:
# print "Fehler: Program Data"
# return
#
# return path_data
#get the GeODin installation path from registry
#return path or empty string
try:
key = OpenKey(HKEY_CURRENT_USER, r"Software\GeODin-System\ChildWindows\GRFMAIN\QVLayoutFolders", 0, KEY_READ)
path_data, regtype = QueryValueEx(key, 'E0')
CloseKey(key)
except WindowsError as e:
self.lgr.info('{0}: {1}'.format(e, r"Computer\HKEY_CURRENT_USER\Software\GeODin-System\ChildWindows\GRFMAIN\QVLayoutFolders"))
return ''
return path_data
def load_db(self, database, level, project = None):
# execute queries in GeODin database
if level == 0:
#load only project names and description
query = '''SELECT DISTINCT LOCPRMGR.PRJ_ID, LOCPRMGR.PRJ_USER, LOCPRMGR.PRJ_DATE, LOCPRMGR.PRJ_ALIAS, LOCPRMGR.PRJ_NAME
FROM {0}GEODIN_LOC_LOCREG INNER JOIN {0}LOCPRMGR ON GEODIN_LOC_LOCREG.PRJ_ID = LOCPRMGR.PRJ_ID
ORDER BY LOCPRMGR.PRJ_NAME;
'''.format(database.owner)
elif level == 1:
#load information of specific project
query = """SELECT GEODIN_LOC_LOCREG.LONGNAME, GEODIN_SYS_LOCTYPES.GEN_NAME, GEODIN_LOC_LOCREG.INVID, GEODIN_LOC_LOCREG.SHORTNAME, GEODIN_LOC_LOCREG.XCOORD, GEODIN_LOC_LOCREG.YCOORD, GEODIN_LOC_LOCREG.EPSG, GEODIN_LOC_LOCREG.LOCTYPE
FROM {1}GEODIN_SYS_LOCTYPES INNER JOIN ({1}GEODIN_LOC_LOCREG INNER JOIN {1}LOCPRMGR ON GEODIN_LOC_LOCREG.PRJ_ID = LOCPRMGR.PRJ_ID) ON GEODIN_SYS_LOCTYPES.GEN_DESC = GEODIN_LOC_LOCREG.LOCTYPE
WHERE LOCPRMGR.PRJ_ID='{0}'
ORDER BY LOCPRMGR.PRJ_NAME, GEODIN_SYS_LOCTYPES.GEN_NAME;
""".format(project.id, database.owner)
try:
result = None
if database.options["connection"] == "ODBC":
#connect to local Microsoft database files (*.mdb, *.accdb)
if 'pyodbc' in sys.modules.keys():
connection = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+database.filepath+";")
else:
connection = pypyodbc.win_connect_mdb(database.filepath)
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
connection.close()
elif database.options["connection"] == "DSNConnection":
#connect to DSN connection
try:
if 'pyodbc' in sys.modules.keys():
connection = pyodbc.connect("DSN="+database.options["DSN"])
else:
connection = pypyodbc.connect("DSN="+database.options["DSN"])
except Exception,e:
QMessageBox.warning(self, 'Error', str(e))
self.lgr.error('path='+database.filepath+', name='+database.name + ', error=' +str(e))
return 1
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
connection.close()
elif database.options["connection"] == "MSSQL":
#connect to DSN connection
if not database.options["uname"] or not database.options["upassword"]:
login = Login(database.options["uname"], database.options["upassword"])
try:
database.options["uname"] = login.uname
database.options["upassword"] = login.upassword
if 'pyodbc' in sys.modules.keys():
connection = pyodbc.connect("DRIVER={SQL Server};SERVER="+database.options["ip"]+";DATABASE="+database.options["database"]+";UID="+database.options["uname"]+";PWD="+database.options["upassword"])
else:
return 1
del login
except:
del login
QMessageBox.warning(self, 'Error', 'Bad user or password')
database.options["upassword"] = ""
return 1
else:
if 'pyodbc' in sys.modules.keys():
connection = pyodbc.connect("DRIVER={SQL Server};SERVER="+database.options["ip"]+";DATABASE="+database.options["database"]+";UID="+database.options["uname"]+";PWD="+database.options["upassword"])
else:
return 1
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
connection.close()
elif database.options["connection"] == "MySQL":
#connect to MySQL databases
if not database.options["uname"] or not database.options["upassword"]:
login = Login(database.options["uname"], database.options["upassword"])
try:
database.options["uname"] = login.uname
database.options["upassword"] = login.upassword
connection = _mysql.connect(database.options["ip"], database.options["uname"], database.options["upassword"], database.options["database"])
login.close()
del login
except:
login.close()
del login
QMessageBox.warning(self, 'Error', 'Bad user or password')
database.options["upassword"] = ""
return 1
else:
try:
connection = _mysql.connect(database.options["ip"], database.options["uname"], database.options["upassword"], database.options["database"])
except Exception,e:
QMessageBox.warning(self, 'Error', str(e))
return 1
connection.query(query)
r = connection.use_result()
row = r.fetch_row()
result=[]
while row:
result.append(row)
row = r.fetch_row()
connection.close()
elif database.options["connection"] == "PostgreSQL":
#connect to PostgreSQL databases
if 'psycopg2' in sys.modules.keys():
if not database.options["uname"] or not database.options["upassword"]:
#if no user name or password in registry open a login dialog
login = Login(database.options["uname"], database.options["upassword"])
try:
database.options["uname"] = login.uname
database.options["upassword"] = login.upassword
connection = psycopg2.connect("dbname={0} user={1} host={2} password={3}".format(database.options["database"], database.options["uname"], database.options["ip"], database.options["upassword"]))
del login
except:
del login
QMessageBox.warning(self, 'Error', 'Bad user or password')
database.options["upassword"] = ""
return 1
else:
#otherwise login with given data
connection = psycopg2.connect("dbname={0} user={1} host={2} password={3}".format(database.options["database"], database.options["uname"], database.options["ip"], database.options["upassword"]))
else:
return 1
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
connection.close()
# elif database.options["connection"] == "Oracle":
# if 'pyodbc' in sys.modules.keys():
# if not database.options["uname"] or not database.options["upassword"]:
# #if no user name or password in registry open a login dialog
# login = Login(database.options["uname"], database.options["upassword"])
# try:
# database.options["uname"] = login.uname
# database.options["upassword"] = login.upassword
# #connection = psycopg2.connect("dbname={0} user={1} host={2} password={3}".format(database.options["database"], database.options["uname"], database.options["ip"], database.options["upassword"]))
# print database.options
# connection = pyodbc.connect('Driver={4};Server={2}/{0}.{2};uid={1};pwd={3}'.format(database.options["database"], database.options["uname"], database.options["ip"], database.options["upassword"], '{Microdsoft ODBC for Oracle}'))
# del login
# except:
# del login
# QMessageBox.warning(self, 'Error', 'Bad user or password')
# database.options["upassword"] = ""
# return 1
# else:
# #otherwise login with given data
# #connection = psycopg2.connect("dbname={0} user={1} host={2} password={3}".format(database.options["database"], database.options["uname"], database.options["ip"], database.options["upassword"]))
# connection = pyodbc.connect('Driver={4};Server={2}/{0};uid={1};pwd={3}'.format(database.options["database"], database.options["uname"], database.options["ip"], database.options["upassword"], '{Microdsoft ODBC for Oracle}'))
# else:
# return 1
# cursor = connection.cursor()
# cursor.execute(query)
# result = cursor.fetchall()
# cursor.close()
# connection.close()
else:
QMessageBox.information(None, database.options["connection"], self.dictionary.getWord(self.lang,"no appropriate database drivers"))
return
if level == 0:
for row in result:
#store the results in the specific arrays
project = Project(None, database)
project.id = row[0]
project.user = row[1]
project.date = row[2]
project.alias = row[3]
project.name = row[4]
database.projects.append(project)
elif level == 1:
for row in result:
#store the results in the specific arrays
object = Object(None, project)
object.name = row[0]
object.locname = row[1]
object.invid = row[2]
object.shortname = row[3]
object.coordinates = (row[4], row[5])
object.epsg = row[6]
object.loctype = row[7]
project.objects.append(object)
result = None
except NameError as e:
self.lgr.error('Name Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except KeyError as e:
self.lgr.error('Key Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except psycopg2.ProgrammingError as e:
self.lgr.error('psycopg2 Programming Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except pyodbc.OperationalError as e:
self.lgr.error('pyodbc Operational Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except pyodbc.DataError as e:
self.lgr.error('pyodbc Data Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except pyodbc.IntegrityError as e:
self.lgr.error('pyodbc Integrity Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except pyodbc.ProgrammingError as e:
self.lgr.error('pyodbc Programming Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except pyodbc.NotSupportedError as e:
self.lgr.error('pyodbc Not Supported Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except pyodbc.DatabaseError as e:
self.lgr.error('pyodbc Database Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except pyodbc.Error as e:
self.lgr.error('pyodbc Error, path={0}, alias={1}, error={2}'.format(database.filepath, database.name, str(e)))
return 1
except:
self.lgr.error('path='+database.filepath+', alias='+database.name + ', error=' +str(sys.exc_info()[0]))
return 1
return 0
#return 0
def newTopLevelItem(self, database):
#create a TopLevelItem in QTreeWidget (database item)
self.dbs.append(database)
item = TreeWidgetItem([database.name])
item.setIcon(0, self.dbicon)
item.setToolTip(0, database.filepath)
item.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
item.itemType = DATABASEITEM
item.extraInformation = database
item.normalString = database.name
self.treeWidget.addTopLevelItem(item)
def buildTree(self, clickedItem = None, clickedColumn = None):
#build the QTreeWidget:
#1. possibility: the clicked item is a database item and has currently no child items
#2. possibility: the clicked item is a project item and has currently no child items
#3. possibility: the clicked item is a query item and has currently no child items
if not clickedItem:
#expand database item with right click menu
try:
clickedItem = self.treeWidget.itemFromIndex(self.treeWidget.selectedIndexes()[0])
except Exception,e:
# self.lgr.error('name='+prj.name+', id='+prj.id+ ', user='+prj.user+', alias='+prj.alias+', error=' +str(e))
print str(e)
if clickedItem and clickedItem.itemType == DATABASEITEM and clickedItem.childCount() == 0:
#load projects and documents
try:
#get database with the name of the TreeWidgetItem
database = clickedItem.extraInformation
except:
return
if self.load_db(database, 0):
#if loading database returns with errors
self.error = 1
return
self.error = 0
for prj in database.projects:
#add all projects to tree
item_prj = TreeWidgetItem([prj.name])
item_prj.setIcon(0, self.prjicon)
item_prj.setData(0, Qt.WhatsThisRole, prj.id)
item_prj.extraInformation = prj
item_prj.itemType = PROJECTITEM
item_prj.normalString = prj.name
item_prj.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
try:
if prj.alias != None:
proj_tip = prj.id + "\n" + prj.user + "\n" + str(prj.date) + "\n" + prj.alias
else:
proj_tip = prj.id + "\n" + prj.user + "\n" + str(prj.date)
item_prj.setToolTip(0, proj_tip)
except Exception,e :
self.lgr.error('name='+prj.name+', id='+prj.id+ ', user='+prj.user+', alias='+prj.alias+', error=' +str(e))
clickedItem.addChild(item_prj)
clickedItem.sortChildren(0,Qt.AscendingOrder)
query_name = self.getDBQueries(database)
if query_name:
for query in query_name:
queryObject = Query(query, database)
item_query = TreeWidgetItem([query])
item_query.setIcon(0, self.queryIcon)
item_query.extraInformation = queryObject
item_query.itemType = DBQUERYITEM
item_query.normalString = query
clickedItem.addChild(item_query)
database.queries.append(queryObject)
data_name, data_path = self.getDBLayer(database)
if data_name:
item_doc = TreeWidgetItem([self.dictionary.getWord(self.lang,"Documents")])
item_doc.setIcon(0, self.docicon)
item_doc.extraInformation = "Documents"
item_doc.itemType = DOCUMENTITEM
item_doc.normalString = "Documents"
clickedItem.addChild(item_doc)
for i, shape_path_string in enumerate(data_path):
try:
#shape_path = shape_path_string.replace("$%DBROOT$",self.config.get('Options', 'geodinrootdir')).replace("C:\\Program Files (x86)\\GeODin\\","C:\\ProgramData\\Fugro\\GeODin\\").split('\\')
shape_path = shape_path_string.split('\\')
children = [item_doc]
for j in range(1,len(shape_path)):
if children[j-1].child(0)!= None and children[j-1].child(0).text(0)==shape_path[j]:
#if the last item already has a child node and the text of this child is equal to the current element add it to list
children.append(children[j-1].child(0))
else:
#if not: create a new item and add it as child to the last node
item_shp = TreeWidgetItem([shape_path[j]])
item_shp.setIcon(0, self.shpicon)
item_shp.setToolTip(0, shape_path_string)
#item_shp.normalString = ("/").join(database.filepath.split("/")[:-1]+shape_path[1:])
item_shp.normalString = shape_path_string.replace("$%DBROOT$",self.config.get('Options', 'geodinrootdir')).replace('C:/Program Files (x86)/GeODin/','C:/ProgramData/Fugro/GeODin/').replace('\\','/').replace('//','/')
item_shp.itemType = DOCUMENTITEM
children.append(item_shp)
children[j-1].addChild(children[j])
except Exception,e:
p = ("/").join(database.filepath.split("/")[:-1]+shape_path[1:])
self.lgr.error('path='+p+', name='+data_name[i] + ', error=' +str(e[1]))
elif clickedItem and clickedItem.itemType == PROJECTITEM and clickedItem.childCount() == 0:
#add all objects of selected project to tree
try:
#get database with the name of the TreeWidgetItem
database=self.dbs[[db.name for db in self.dbs].index(clickedItem.parent().text(0))]
except:
return
if self.load_db(database, 1, clickedItem.extraInformation):
#if loading database returns without errors
clickedItem.setExpanded(False)
return
self.buildProjects(database, clickedItem)
elif clickedItem and clickedItem.itemType == QUERYITEM and clickedItem.childCount() == 0:
self.runQuery()
else:
return
if clickedColumn==None:
clickedItem.setExpanded(True)
def buildProjects(self, database, item_prj):
project = item_prj.extraInformation
item_obj = TreeWidgetItem([self.dictionary.getWord(self.lang,"Objects")])
item_obj.setIcon(0, self.objicon)
item_obj.extraInformation = "Objects"
item_obj.normalString = "Objects"
item_obj.itemType = 999
item_prj.addChild(item_obj)
item_all = TreeWidgetItem([self.dictionary.getWord(self.lang,"All Objects")])
item_all.setIcon(0, self.objicon_type)
item_all.extraInformation = ObjectType("All Objects", project)
item_all.itemType = OBJECTTYPEITEM
item_all.normalString = "All Objects"
thisObjectType = project.objects[0].locname
objectType = ObjectType(project.objects[0].locname, project)
objectType.gen_desc = project.objects[0].loctype
item_loc = TreeWidgetItem([project.objects[0].locname])
item_loc.setIcon(0, self.objicon_type)
item_loc.itemType = OBJECTTYPEITEM
item_loc.normalString = project.objects[0].locname
item_loc.extraInformation = objectType
item_obj.addChild(item_loc)
for i in range(len(project.objects)):
item_new_obj = TreeWidgetItem([project.objects[i].name])
item_new_obj.setIcon(0, self.objicon_single)
item_new_obj.normalString = project.objects[i].name
item_new_obj.extraInformation = project.objects[i]
item_new_obj.itemType = OBJECTITEM
item_all_obj = TreeWidgetItem([project.objects[i].name])
item_all_obj.setIcon(0, self.objicon_single)
item_all_obj.normalString = project.objects[i].name
item_all_obj.extraInformation = project.objects[i]
item_all.extraInformation.objects.append(project.objects[i])
item_all_obj.itemType = OBJECTITEM
item_all.addChild(item_all_obj)
if (project.objects[i].locname==thisObjectType):
item_loc.addChild(item_new_obj)
item_loc.setToolTip(0, str(item_loc.childCount()) + " " + self.dictionary.getWord(self.lang,"Objects"))
objectType.objects.append(project.objects[i])
else:
thisObjectType = project.objects[i].locname
objectType = ObjectType(project.objects[i].locname, project)
objectType.objects.append(project.objects[i])
objectType.gen_desc = project.objects[i].loctype
item_loc = TreeWidgetItem([project.objects[i].locname])
item_loc.setIcon(0, self.objicon_type)
item_loc.itemType = OBJECTTYPEITEM
item_loc.normalString = project.objects[i].locname
item_loc.extraInformation = objectType
item_obj.addChild(item_loc)
item_loc.addChild(item_new_obj)
item_loc.setToolTip(0, str(item_loc.childCount()) + " " + self.dictionary.getWord(self.lang,"Objects"))
item_prj.sortChildren(0,Qt.AscendingOrder)
item_obj.sortChildren(0,Qt.AscendingOrder)
item_obj.insertChild(0,item_all)
for i in range(item_obj.childCount()):
item_obj.child(i).sortChildren(0,Qt.AscendingOrder)
try:
#user queries
query = """SELECT GEODIN_SYS_PRJDEFS.OBJ_NAME
FROM {1}GEODIN_SYS_PRJDEFS
WHERE GEODIN_SYS_PRJDEFS.PRJ_ID = '{0}' AND GEODIN_SYS_PRJDEFS.OBJ_DESC = 'LOCQUERY' """.format(item_prj.extraInformation.id, database.owner)
result = self.connectToDatabase(database, query)
for row in result:
queryObject = Query(row[0], project)
project.queries.append(queryObject)
queryItem = TreeWidgetItem([row[0]])
queryItem.setIcon(0, self.queryIcon)
queryItem.extraInformation = queryObject
queryItem.itemType = DBQUERYITEM
queryItem.normalString = row[0]
item_obj.addChild(queryItem)
except:
pass
try:
#qgis based user queries