def _loadOnlineClassIndex(self, classCode): if not Settings.siteServerUrl(): return False if self._ark is None: self._createArkSession() if self._ark is None: return False response = self._ark.getItems(classCode + '_cd') if response.error: self._plugin.logMessage(response.url) self._plugin.logMessage(response.message) self._plugin.logMessage(response.raw) else: lst = response.data[classCode] items = set() for record in lst: item = Item(record['ste_cd'], classCode, record[classCode + '_no']) if item.isValid(): items.add(item) self.items[classCode] = sorted(items) self._plugin.logMessage('ARK Items ' + classCode + ' = ' + str(len(self.items[classCode]))) if (len(self.items[classCode]) > 0): self._indexLoaded = True return True return False
def childrenItem(self, parentItem): if not parentItem or parentItem.isInvalid() or not Config.fields[parentItem.classCode()]['group']: return Item() childIdSet = set() for parent in parentItem.toList(): children = self.childItems(parent) for child in children: childIdSet.add(child.itemId()) return Item(parentItem.siteCode(), Config.fields[parentItem.classCode()]['child'], childIdSet)
def _findContext(self, context=Item()): self._clearSchematicFilters() if not context.isValid(): context = self._dock.contextItem() self._plugin.filter().applySchematicFilter(context, self._filterAction) self.applyItemActions(context, self._mapAction, FilterAction.NoFilterAction, self._drawingAction) haveArk, contextType, contextDescription = self._arkStatus(context) haveFeature = self._featureStatus(context, True) if haveFeature == SearchStatus.NotFound: polyRequest = self._notCategoryRequest(context, 'sch') haveFeature = SearchStatus.Found try: self.collection().layer('polygons').getFeatures(polyRequest).next() except StopIteration: haveFeature = SearchStatus.NotFound haveSchematic = self._schematicStatus(context) scsRequest = self._categoryRequest(context, 'scs') haveSectionSchematic = SearchStatus.Found try: self.collection().layer('polygons').getFeatures(scsRequest).next() except StopIteration: haveSectionSchematic = SearchStatus.NotFound self._dock.setContext(context, haveArk, contextType, contextDescription, haveFeature, haveSchematic, haveSectionSchematic) self.metadata.setItemId(context.itemId())
def nextItem(self, item): idx = -1 if item.isValid(): idx = bisect.bisect(self.items[item.classCode()], item) if idx >= 0 and idx < len(self.items[item.classCode()]) - 1: return self.items[item.classCode()][idx] return Item()
def _getAllSchematicItems(self): features = self._getAllSchematicFeatures() items = set() for feature in features: item = Item(feature) items.add(item) return sorted(items)
def canvasReleaseEvent(self, e): self._reset() if e.button() != Qt.LeftButton: return mapPoint = self.toMapCoordinates(e.pos()) self._vertexMarker.setCenter(mapPoint) layers = [ self.collection().layer('points'), self.collection().layer('lines'), self.collection().layer('polygons') ] results = self.identify(e.x(), e.y(), layers, QgsMapToolIdentify.TopDownAll) if (len(results) < 1): return # Build the set of unique items identified items = set() for result in results: feature = result.mFeature siteCode = feature.attribute('site') classCode = feature.attribute('class') itemId = feature.attribute('id') items.add(Item(siteCode, classCode, itemId)) action = QAction('Plan Items', self._menu) action.setData('top') self._menu.addAction(action) site = '' for item in sorted(items): if item.siteCode() != site: site = item.siteCode() self._menu.addSeparator() action = QAction('Site ' + site + ':', self._menu) action.setData('top') self._menu.addAction(action) action = IdentifyItemAction(item, self._plugin, self._menu) action.setData('top') action.zoomToItemSelected.connect(self._zoom) action.panToItemSelected.connect(self._pan) action.filterItemSelected.connect(self._filterItem) action.excludeFilterItemSelected.connect(self._excludeFilterItem) action.highlightItemSelected.connect(self._highlightItem) action.addHighlightItemSelected.connect(self._addHighlightItem) action.editItemSelected.connect(self._editInBuffers) action.deleteItemSelected.connect(self._delete) action.openDrawingsSelected.connect(self._openDrawings) self._actions.append(action) self._menu.addAction(action) self._menu.addSeparator() action = ClipboardAction('Map: ', mapPoint.toString(3), self._menu) action.setData('top') self._menu.addAction(action) if self._plugin.grid().mapTransformer is not None: localPoint = self._plugin.grid().mapTransformer.map(mapPoint) self._menu.addAction( ClipboardAction('Local: ', localPoint.toString(3), self._menu)) menuPos = QPoint(e.globalX() + 100, e.globalY() - 50) selected = self._menu.exec_(menuPos) self._reset(resetVertex=False)
def configure(self): wizard = ProjectWizard(self._plugin.iface.mainWindow()) ok = wizard.exec_() if ok: if wizard.newProject(): if Project.exists(): Project.write() Project.clear() projectFolderPath = os.path.join(wizard.projectFolder(), 'project') if not QDir(projectFolderPath).mkpath('.'): return False projectFilePath = os.path.join(projectFolderPath, wizard.projectFilename() + '.qgs') Project.setFileName(projectFilePath) Settings.setProjectCode(wizard.project().projectCode()) Settings.setProjectName(wizard.project().projectName()) Settings.setSiteCode(wizard.project().siteCode()) if not Project.title(): Project.setTitle(wizard.project().projectCode() + ' - ' + wizard.project().projectName()) self._initialised = Project.write() if self._initialised: # We always want the site collection self._addCollection('site') self.collection('site').loadCollection() # Add the Site Location if entered location = wizard.projectLocation() if not location.isEmpty(): siteCode = wizard.project().siteCode() if wizard.project().siteCode() else wizard.project().projectCode() item = Item(siteCode, 'site', siteCode) source = Source('other', item) audit = Audit(Settings.userFullName(), utils.timestamp()) itemFeature = ItemFeature(item, 'loc', None, source, 'New Project Wizard', audit) layer = self.collection('site').layer('points') feature = QgsFeature(layer.pendingFields(), 0) feature.setGeometry(QgsGeometry(location)) attributes = itemFeature.toFeature(feature) layers.addFeatures([feature], layer) # Temp load of other collection, later do on demand self._addCollection('plan') self.collection('plan').loadCollection() self._addCollection('section') self.collection('section').loadCollection() self._addCollection('grid') self.collection('grid').loadCollection() # self._configureDrawing('context') # self._configureDrawing('plan') # self._configureDrawing('section') Settings.setProjectConfigured() return ok
def _showSchematicReport(self): features = set() for feature in self.collection().layer('points').getFeatures(): features.add(Item(feature)) for feature in self.collection().layer('lines').getFeatures(): features.add(Item(feature)) for feature in self.collection().layer('polygons').getFeatures(): features.add(Item(feature)) schRequest = self._featureRequest(self._categoryClause('sch')) scsRequest = self._featureRequest(self._categoryClause('scs')) schematics = set() for feature in self.collection().layer('polygons').getFeatures(schRequest): schematics.add(Item(feature)) for feature in self.collection().layer('polygons').getFeatures(scsRequest): schematics.add(Item(feature)) missing = [] contexts = self._plugin.data().items['context'] for context in contexts: if context not in schematics: row = {} row['Site Code'] = context.siteCode() row['Context'] = context.itemId() itemData = self._plugin.data().getItemData(context) try: row['Type'] = itemData['context_type'] except Exception: row['Type'] = '' try: vals = self._plugin.data().getItemFields(context, ['conf_field_cxttype']) row['Type'] = vals[u'conf_field_cxttype'] except Exception: row['Type'] = '' if context in features: row['GIS'] = 'Y' else: row['GIS'] = 'N' missing.append(row) text = '<html><head/><body><p><span style=" font-weight:600;">Missing Schematics:</span></p><p>There are ' + \ str(len(contexts)) + ' Contexts in ARK, of which ' + \ str(len(missing)) + ' are missing schematics.<br/></p></body></html>' dialog = TableDialog('Missing Schematics', text, ['Site Code', 'Context', 'Type', 'GIS'], { 'Site Code': '', 'Context': '', 'Type': '', 'GIS': ''}, self._dock) dialog.addRows(missing) dialog.exec_()
def prevItem(self, item): idx = -1 try: if item.isValid(): idx = bisect.bisect_left(self.items[item.classCode()], item) - 1 if idx >= 0 and idx < len(self.items[item.classCode()]) - 1: return self.items[item.classCode()][idx] except Exception: pass return Item()
def _findSource(self, source=Item()): if not source.isValid(): source = self._dock.sourceItem() self._plugin.filter().applySchematicFilter(source, self._filterAction) self.applyItemActions(source, self._mapAction, FilterAction.NoFilterAction, self._drawingAction) haveArk, contextType, contextDescription = self._arkStatus(source) haveFeature = self._featureStatus(source) haveSchematic = self._schematicStatus(source) self._dock.setSourceContext(source, haveArk, contextType, contextDescription, haveFeature, haveSchematic)
def __init__(self, filePath, keyFields, parent=None): super(ItemModel, self).__init__(parent) if QFile.exists(filePath): with open(filePath) as csvFile: reader = csv.DictReader(csvFile) self._fields = reader.fieldnames self._nullRecord = {} for field in self._fields: self._nullRecord[field] = '' for record in reader: item = Item(record[keyFields.siteCode], record[keyFields.classCode], record[keyFields.itemId]) self._addItem(item, record)
def _getOnlineLinks(self, item, linkClassCode): if not Settings.siteServerUrl(): return [] xmi = unicode('conf_field_' + item.classCode() + linkClassCode + 'xmi') data = self.getItemFields(item, [xmi]) items = [] try: for link in data[xmi]: itemkey = link[u'xmi_itemkey'] itemvalue = link[u'xmi_itemvalue'].split(u'_') item = Item(itemvalue[0], itemkey[:3], itemvalue[1]) items.append(item) except Exception: return [] return items
def __init__(self, plugin): super(DataModule, self).__init__(plugin) self.items = {} # {classCode: [Item]} # Internal variables self._classDataModels = {} # {classCode: ItemModel()} self._classDataProxyModels = {} # {classCode: QSortFilterProxyModel()} self._linkModel = ParentChildModel() self._ark = None self._indexLoaded = False self._dataMode = '' self._prevItem = Item() self._mapAction = MapAction.MoveMap self._filterAction = FilterAction.ExclusiveHighlightFilter self._drawingAction = DrawingAction.NoDrawingAction
def _mergeBuffers(self, collection): # Check the layers are writable name = collection.settings.collectionGroupName if not collection.isWritable(): self._plugin.showCriticalMessage( name + ' layers are not writable! Please correct the permissions and log out.', 0) return # Check the buffers contain valid data errors = self._preMergeBufferCheck(collection.buffer('points')) errors.extend(self._preMergeBufferCheck(collection.buffer('lines'))) errors.extend(self._preMergeBufferCheck(collection.buffer('polygons'))) if len(errors) > 0: dialog = ItemFeatureErrorDialog() dialog.loadErrors(errors) dialog.exec_() if not dialog.ignoreErrors(): return # Update the audit attributes timestamp = utils.timestamp() user = Settings.userFullName() self._preMergeBufferUpdate(collection.buffer('points'), timestamp, user) self._preMergeBufferUpdate(collection.buffer('lines'), timestamp, user) self._preMergeBufferUpdate(collection.buffer('polygons'), timestamp, user) # Finally actually merge the data if collection.mergeBuffers('Merge data', timestamp): self._plugin.showInfoMessage(name + ' data successfully merged.') # TODO pass current Item... self._logItemAction(Item(), 'Merge Buffers', timestamp) # TODO Signal out layers merged for schematic dock to catch # if self._editSchematic: # self._editSchematic = False # self._dock.activateSchematicCheck() # self._findContext() else: self._plugin.showCriticalMessage( name + ' data merge failed! Some data has not been saved, please check your data.', 5)
def getFilterItems(self, filterId): items = [] if self._ark is None: return items response = self._ark.getFilterSet(filterId) if response.error: utils.logMessage(response.url) utils.logMessage(response.message) utils.logMessage(response.raw) else: for item in response.data: res = response.data[item] item = Item() item.fromArkKey(res['itemkey'], res['itemval']) utils.logMessage(item.debug()) if item.isValid(): items.append(item) return sorted(items)
def _itemLinkClicked(self, url): item_key = '' item_value = [] if 'download.php' in url.toString(): # web = QWebView() # web.load(url) self._dock.widget.itemDataView.load(url) return if url.hasQueryItem('item_key'): item_key = url.queryItemValue('item_key') item_value = url.queryItemValue(item_key).split('_') elif url.hasQueryItem('itemkey'): item_key = url.queryItemValue('itemkey') item_value = url.queryItemValue(item_key).split('_') else: parts = url.path().split('/') if len(parts) >= 2: item_key = parts[-2] item_value = parts[-1].split('_') if item_key and len(item_value) == 2: item = Item(item_value[0], item_key[:3], item_value[1]) if self.haveItem(item): self._dock.setItem(item) self._itemChanged()
def clause(self): cl = FilterClause() cl.item = Item(self.siteCode(), self.classCode(), self.filterRange()) cl.action = self.filterType() cl.color = self.color() return cl
def lastItem(self, classCode): try: return self.items[classCode][-1] except KeyError: return Item()
def _sourceItem(self): return Item(self._siteCode(), self._sourceClass(), self._sourceId())
def resetSourceContext(self): self.setSourceContext(Item())
def sourceItem(self): return Item(self.siteCode(), 'context', self.sourceContext())
def resetContext(self): self.setContext(Item())
def item(self): return Item(self.siteCode(), self.classCode(), self.itemId())
def contextItem(self): return Item(self.siteCode(), 'context', self.context())