# # Copyright 2001, 2002 by IVA Team and contributors # # This file is part of IVA. # # IVA 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. # # IVA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with IVA; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """Contains class WordMap, which represents one working Concept map""" import AccessControl import OFS, Globals from OFS import SimpleItem import types import time import math from TraversableWrapper import Traversable from Globals import Persistent from AccessControl import ClassSecurityInfo from Cruft import Cruft from common import translate, perm_edit, perm_view, get_roles from common import get_text, get_attr import xml.dom.minidom from ImportExport import Counter, DataTable, to_utf8, Exporter, Dump import WordMapTools from WordMapTools import WordmapFolder, MapWord, MapEdge try: from PIL import Image, ImageDraw except ImportError: pass from interfaces import IWordMap from zope.interface import implements class WordMap( OFS.Folder.Folder, Persistent, AccessControl.Role.RoleManager, Traversable, Cruft ): """ Concept map """ security = AccessControl.ClassSecurityInfo() security.declareObjectPublic() implements(IWordMap) def __init__(self): "Constructor" self.meta_type="WordMap" self.initializeVariables() security.declareProtected(perm_edit, 'initializeVariables') def initializeVariables(self): "Initialize variables at startup and on cleaning" self.picturesize=[600, 500] #picture size in pixels self.planpicturesize=[200, 200] #whole map without zooming #viewing area in logical units self.viewingbounds=[0, 0, self.picturesize[0], self.picturesize[1]] self.viewingcentre=[ (self.viewingbounds[0]+self.viewingbounds[2])/2.0, (self.viewingbounds[1]+self.viewingbounds[3])/2.0, ] self.viewcoef=1 #monitor points/logical points self.zoomcoef=0.5 self.wordbackgroundcolordefaultindex=0 self.wordcolortypes=["", "", "", "", ""] # self.linecolor=(62, 96, 144) self.linecolor=(82, 91, 98) self.selectedlinecolor=(200, 0, 0) self.backgroundcolor=(255, 255, 255) self.viewingboundslinecolor=(200, 200, 200) self.selectedarealinecolor=(255, 100, 100) self.leftdistance=10 #free space from picture side in pixels self.rightdistance=10 self.topdistance=10 self.bottomdistance=10 self.movingdistanceinscreen=25 #word placing in picture. Each word have x and y coordinate #at example [[10, 10], [10, 20], [10, 30]] self.wordplaces=[] #in self.relationnumbers each element is a array, where index means starting vertex and #value point to end vertex. At example [[1], [0, 2], [1]] self.relationnumbers=[] self.wordids=[] #word object indexes in OFS self.newwordidnr=0 self.newedgeidnr=0 self.startingvertex=None #Central vertex index in graph at example 2 #self.parentarray displays way to starting vertex #at example [1, 2, -1] means, that way from vertex 0 to #startingvertex (here 2) goes (0, 1) and (1, 2). In place 2 #are value -1, because we allready are in vertex 2 self.parentarray=[] #Parent vertex in trees self.distancegrouparray=None #Each element presents list of #vertexes in same distance from start vertex #active action number #0 - horizontal tree; 1-move self.activeaction=0 self.selectedmovevertex=None #vertex selected to move self.selectedwords=[] #word indexes self.selectededge=None self.selectingdistance=5 #distance in points selecting with mouse self.selectedarea=None #[x, y, w, h] if present self.selectedareafirstclick=None #[x, y] if present self.menustates={'edit':0, 'select':0, 'zoom':0} self.picturefilenames=["wm_kursor", "wm_margistus", "wm_luuppluss", #0, 1, 2 "wm_luupmiinus", "wm_lisaseos", "wm_kustutus", #3, 4, 5 "wm_horpuu", "wm_kiirpuu", "wm_noolv", #6, 7, 8 "wm_noolp", "wm_nooly", "wm_noola", #9, 10, 11 "wm_margistusnool", "wm_margistus", "wm_margistusmaha", "wm_margistusloika", "wm_margistuskopeeri", "wm_margistuskleebi", "wm_margistusv", "wm_margistusp", "wm_margistusy", "wm_margistusa", "wm_lisaseos", "wm_margistusnool", "wm_luuppluss", #22 "wm_luuptyhi", "wm_piltsuuremaks", "wm_piltvaiksemaks" ] #which picture is with border self.pictureselections=[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #0-11 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, #12-20 ] self.menuicons=(22, 23, 24) self.additionalpictures=[] self.selectpictures=[12, 13, 14, 15, 16, 17, 18, 19, 20, 21] self.picturehints=[ "Click with mouse", "Select area", "Zoom bigger", "Zoom Smaller", "Add edge", "Delete", "Horizontal tree", "Circle tree", "View left", "Viev right", "View up", "View down", "Select multiple words", "Select area words", "Unselect all", "Cut", "Copy", "Paste", "Move left", "Move right", "Move up", "Move down", "Edit menu", "Select menu", "Zoom menu", "Zoom to bounds", "Increase picture", "Decrease picture" ] wds=self.objectValues('MapWord') for wd in wds: self._delObject(wd.id) edges=self.objectValues('MapEdge') for eg in edges: self._delObject(eg.id) self.title="" self.description="" # self.fontfiles=[None, "courB14.pil", "courB24.pil"] self.fontfiles=["cour08.pil", "courB10.pil", "courB14.pil"] self.fontindex=1 self.menutypeowner=1 #0 no menu, 1 simple, 2 bigger self.menutypevisitor=0 self.startingmap=1 #kas algne kaart, mil koik lubatud self.allowedsubmaps=1 self.wordgraphicalpropertiesallowed=0 self.equationsallowed=0 self.hyperlinksallowed=0 self.attachmentallowed=0 self.mappropertiesallowed=1 self.canchangeproperties=1 #actual self.maxwords=None self.maxedgetypes=None self.maxedgecount=None self.declaredwords=[] self.declarededges=[] self.activationstate=0 #0-mitte midagi, 1-klops vabale pinnale, 2 aktiveeritud yks moiste, #3 aktiveeritud kaks moistet, 4 aktiveeritud seos self.newconceptx=None self.newconcepty=None self.currenteditingusername="" self.currenteditingtime=None self.currenteditingsessionlength=30 #sekundit self.selectingtype='t' #tekst, pilt, valem self.picturesavingsize=150 self.visibletoothers=1 #other users can see map self.otherscanedit=0 #other users can edit map self.homeworkstatus=0 #0 - not homework, 1-Student can edit, 2-work submitted self.hwid=None self.globalMap=None self.analyzeStatus=0 #0-not analyzed, 1 analyzed self.graphType=0 # 0 central, 1 tree, 2 full graph self.automaticResolution=1 self.resolutionX=500 self.resolutionY=380 def getAutomaticResolution(self): "" if hasattr(self, 'automaticResolution'): return self.automaticResolution return 1 def getResolutionX(self): "getter" if hasattr(self, 'resolutionX'):return self.resolutionX return 500 def getResolutionY(self): "getter" if hasattr(self, 'resolutionY'): return self.resolutionY return 380 security.declareProtected(perm_view, 'getTitle') def getTitle(self): "getter" return self.title.strip() security.declareProtected(perm_view, 'getDescription') def getDescription(self): "getter" return self.description security.declareProtected(perm_view, 'getFontIndex') def getFontIndex(self): "getter" return self.fontindex security.declareProtected(perm_view, 'getWordBackgroundColorIndex') def getWordBackgroundColorIndex(self): "getter" return self.wordbackgroundcolordefaultindex security.declareProtected(perm_view, 'getWordColorTypes') def getWordColorTypes(self): "getter" return self.wordcolortypes security.declareProtected(perm_view, 'getWordColorType') def getWordColorType(self, index): "getter" try: return self.wordcolortypes[index] except: return "" security.declareProtected(perm_view, 'getMenuTypeOwner') def getMenuTypeOwner(self): "getter" return self.menutypeowner security.declareProtected(perm_view, 'getMenuTypeVisitor') def getMenuTypeVisitor(self): "getter" return self.menutypevisitor security.declareProtected(perm_view, 'getAllowedSubmaps') def getAllowedSubmaps(self): "getter" return self.allowedsubmaps security.declareProtected(perm_view, 'getActivationState') def getActivationState(self): "getter" return self.activationstate security.declareProtected(perm_view, 'getAnalyzeStatus') def getAnalyzeStatus(self): "getter" if hasattr(self, 'analyzeStatus'): return self.analyzeStatus return 0 security.declareProtected(perm_view, 'getGraphType') def getGraphType(self): "getter" if hasattr(self, 'graphType'): return self.graphType return 0 security.declareProtected(perm_view, 'isOwner') def isOwner(self, REQUEST): "katsetus" fromWeb=str(REQUEST.AUTHENTICATED_USER) inServer=str(self.getOwner()) if fromWeb==inServer: return 1 else: return 0 security.declareProtected(perm_view, 'getOwnerUserName') def getOwnerUserName(self): "Returns owner user name. Required for security rules" return str(self.getOwner()) security.declareProtected(perm_view, 'canSee') def canSee(self, REQUEST): "True if REQUEST.AUTHENTICATED_USER can see this map" if self.visibletoothers: return 1 if self.isOwner(REQUEST): return 1 if self.kas_opetaja(REQUEST): return 1 return 0 def canSeeSettings(self, REQUEST): "If user can see and set all settings" if self.kas_opetaja(REQUEST): if self.getHomeworkStatus()==2: return 0 return 1 if self.isOwner(REQUEST) and self.canchangeproperties: return 1 return 0 def canSeeSettingsButton(self, REQUEST): "If user can see and set all settings" if self.kas_opetaja(REQUEST): if self.getHomeworkStatus()==2: return 0 return 1 if self.isOwner(REQUEST): # and self.canchangeproperties: return 1 return 0 def getOwnerName(self): "Owner first and last name" return self.firstAndLast(self.getOwner()) security.declareProtected(perm_view, 'getBreadCrumbInfo') def getBreadCrumbInfo(self): "info" return self.getTitle()+" ("+str(self.getOwner())+")" def getDisplayableMenuType(self, REQUEST): "Choosing menu depending user" return self.menutypeowner security.declareProtected(perm_view, 'getWordGraphicalPropertiesAllowed') def getWordGraphicalPropertiesAllowed(self): "getter" return self.wordgraphicalpropertiesallowed security.declareProtected(perm_view, 'getEquationsAllowed') def getEquationsAllowed(self): "getter" return self.equationsallowed security.declareProtected(perm_view, 'getHyperlinksAllowed') def getHyperlinksAllowed(self): "getter" return self.hyperlinksallowed security.declareProtected(perm_view, 'getAttachmentAllowed') def getAttachmentAllowed(self): "getter" return self.attachmentallowed security.declareProtected(perm_view, 'getMapPropertiesAllowed') def getMapPropertiesAllowed(self): "getter" return self.mappropertiesallowed security.declareProtected(perm_view, 'getMaxWords') def getMaxWords(self): "getter" return self.maxwords security.declareProtected(perm_view, 'getMaxEdgeTypes') def getMaxEdgeTypes(self): "getter" return self.maxedgetypes security.declareProtected(perm_view, 'getMaxEdgeCount') def getMaxEdgeCount(self): "getter" return self.maxedgecount security.declareProtected(perm_view, 'getVisibleToOthers') def getVisibleToOthers(self): "Is map visible to other users" return self.visibletoothers security.declareProtected(perm_view, 'getOthersCanEdit') def getOthersCanEdit(self): "Can other users edit the map" return self.otherscanedit security.declareProtected(perm_view, 'getDeclaredWords') def getDeclaredWords(self): "getter" return self.declaredwords security.declareProtected(perm_view, 'getDeclaredEdges') def getDeclaredEdges(self): "getter" return self.declarededges security.declareProtected(perm_view, 'areNewEdgeAllowed') def areNewEdgeAllowed(self): "question" if not self.maxedgecount: return 1 return len(self.objectValues('MapEdge'))0 and e.text_in_line not in t: t.append(e.text_in_line) for e in self.getDeclaredEdges(): if e not in t: t.append(e) return t security.declareProtected(perm_view, 'getDeclaredWordsAsString') def getDeclaredWordsAsString(self): "getter" import string return string.join(self.declaredwords, ", ") security.declareProtected(perm_view, 'getDeclaredEdgesAsString') def getDeclaredEdgesAsString(self): "getter" import string return string.join(self.declarededges, ", ") security.declareProtected(perm_view, 'getMapWords') def getMapWords(self): "getter" return self.objectValues('MapWord') security.declareProtected(perm_view, 'getMapEdges') def getMapEdges(self): "getter" return self.objectValues('MapEdge') security.declareProtected(perm_view, 'getNewPictureURL') def getNewPictureURL(self, REQUEST): "Picture URL for Opera refreshing" import random randnr=int(100000*random.random()) if self.isOwner(REQUEST) or self.getOthersCanEdit(): return self.absolute_url()+"/getPicture?randnr="+str(randnr) else: return self.absolute_url()+"/exportPicture?randnr="+str(randnr) security.declareProtected(perm_view, 'getHomeworkStatus') def getHomeworkStatus(self): "Return status: 0, 1 or 2" return self.homeworkstatus security.declareProtected(perm_edit, 'add_new_wordmap') def add_new_wordmap(self): "we're not adding new wordmap. In class WordmapFolder returns 1" return 0 security.declareProtected(perm_edit, 'wordmaps_management_page_handler') def wordmaps_management_page_handler(self, REQUEST, title=None, description=None, font=None, colorindex=None, wordcolortype=None, menuowner=None, maxwords=None, maxedgecount=None, maxedgetypes=None, declaredwords=None, declarededges=None, resolutionx=None, resolutiony=None, automaticresolution=0, allowedsubmaps=0, wordgraphicalpropertiesallowed=0, equationsallowed=0, hyperlinksallowed=0, attachmentallowed=0, mappropertiesallowed=0, visibletoothers=0, otherscanedit=0, userLocation=0, hwid=0, redirect=1): "Data saving" self.fontindex=int(font) self.resolutionX=500 try: self.resolutionX=int(resolutionx) if self.resolutionX>2000: self.resolutionX=2000 except: pass self.resolutionY=380 try: self.resolutionY=int(resolutiony) if self.resolutionY>2000: self.resolutionY=2000 except: pass self.automaticResolution=1 if automaticresolution==0: self.automaticResolution=0 self.picturesize=[self.resolutionX, self.resolutionY] if title is not None: self.title=title self.description=description nr=len(self.wordcolortypes) self.wordcolortypes=[] for i in range(nr): self.wordcolortypes.append(wordcolortype[i]) self.wordbackgroundcolordefaultindex=int(colorindex) self.menutypeowner=int(menuowner) if allowedsubmaps: self.allowedsubmaps=1 else: self.allowedsubmaps=0 if wordgraphicalpropertiesallowed: self.wordgraphicalpropertiesallowed=1 else: self.wordgraphicalpropertiesallowed=0 if equationsallowed: self.equationsallowed=1 else: self.equationsallowed=0 if hyperlinksallowed: self.hyperlinksallowed=1 else: self.hyperlinksallowed=0 if attachmentallowed: self.attachmentallowed=1 else: self.attachmentallowed=0 if mappropertiesallowed: self.mappropertiesallowed=1 else: self.mappropertiesallowed=0 if visibletoothers: self.visibletoothers=1 else: self.visibletoothers=0 if otherscanedit: self.otherscanedit=1 else: self.otherscanedit=0 if len(maxwords.strip())>0: self.maxwords=int(maxwords.strip()) else: self.maxwords=None if len(maxedgecount.strip())>0: self.maxedgecount=int(maxedgecount.strip()) else: self.maxedgecount=None if len(maxedgetypes.strip())>0: self.maxedgetypes=int(maxedgetypes.strip()) else: self.maxedgetypes=None if len(declaredwords.strip())>0: abi=[] m=declaredwords.split(",") for x in m: abi.append(x.strip()) self.declaredwords=abi else: self.declaredwords=[] self.checkNewRequiredWords(REQUEST) if len(declarededges.strip())>0: abi=[] m=declarededges.split(",") for x in m: abi.append(x.strip()) self.declarededges=abi else: self.declarededges=[] self.selectSoloIcon(0) self.selectedwords=[] self.selectededge=None self.activationstate=0 if redirect: if not userLocation=="Management": REQUEST.RESPONSE.redirect(self.absolute_url()+'/wmapindex.html') else: REQUEST.RESPONSE.redirect(getattr(self.fle_root().courses, self.jooksva_kursuse_nr(REQUEST)).kodutood.absolute_url()+"/"+hwid+"/manage_changeAssignment") security.declareProtected(perm_view, 'countPictures') def countPictures(self): "Number of pictures in words and edges" nr=0 for e in self.objectValues(('MapWord', 'MapEdge')): if e.hasPicture(): nr+=1 return nr security.declareProtected(perm_view, 'hasGlobalMap') def hasGlobalMap(self): "Returns true, if map words and connections collective map already made" if self.globalMap: return 1 return 0 security.declareProtected(perm_view, 'getHeadMap') def getHeadMap(self): "First map in the tree" m=self while m.aq_parent.meta_type=="WordMap": m=m.aq_parent return m security.declareProtected(perm_view, 'isHeadMap') def isHeadMap(self): "Is this map first map in the tree" return self==self.getHeadMap() security.declareProtected(perm_view, 'getAdditionalPictures') def getMenuState(self, type): "Is specified menu open" return self.menustates[type] def changeMenuState(self, type): "on/off" if self.menustates[type]: self.menustates[type]=0 else: self.menustates[type]=1 security.declareProtected(perm_view, 'getNewEdgeID') def getNewEdgeID(self): "ID nr for new edge in map" self.newedgeidnr+=1 return self.newedgeidnr security.declareProtected(perm_view, 'getNewWordID') def getNewWordID(self): "ID nr for new word in map" self.newwordidnr+=1 return self.newwordidnr security.declareProtected(perm_view, 'getAdditionalPictures') def getAdditionalPictures(self): "Additional menu" return self.additionalpictures security.declareProtected(perm_view, 'getIconByNr') def getIconByNr(self, pnr): "Returns the file name" iconname='++resource++images/'+self.picturefilenames[int(pnr)] if self.isIconSelected(pnr): iconname+="_bw" return iconname+".gif" def getIconHTML(self, REQUEST, nr): "HTML for image icons" st="" t=""+translate(self, self.picturehints[nr])+"" return t security.declareProtected(perm_view, 'isIconSelected') def isIconSelected(self, pnr): "yes/no" return self.pictureselections[int(pnr)] security.declareProtected(perm_view, 'getIconHint') def getIconHint(self, pnr): "Hint to picture" return self.picturehints[int(pnr)] security.declareProtected(perm_view, 'getSelectedWords') def getSelectedWords(self): "Selected word indexes in map" return self.selectedwords security.declareProtected(perm_view, 'getSelectedWordTitle') def getSelectedWordTitle(self): "getter" if len(self.selectedwords)==1: return getattr(self, self.wordids[self.selectedwords[0]]).title return "" security.declareProtected(perm_view, 'getSelectedTwoWords') def getSelectedTwoWords(self): "getter" if len(self.selectedwords)==2: return getattr(self, self.wordids[self.selectedwords[0]]).title+"-"+getattr(self, self.wordids[self.selectedwords[1]]).title security.declareProtected(perm_view, 'getSelectedItem') def getSelectedItem(self): "Selected word or edge" if self.selectededge: return self.getSelectedEdge() if len(self.selectedwords)==1: return getattr(self, self.wordids[self.selectedwords[0]]) return 0 security.declareProtected(perm_view, 'makeCopy') def makeCopy(self): "Copy of self with same main data" import copy newmap=WordMap() newmap.wordplaces=[] for p in self.wordplaces: newmap.wordplaces.append(copy.copy(p)) newmap.relationnumbers=[] for n in self.relationnumbers: newmap.relationnumbers.append(copy.copy(n)) newmap.parentarray=copy.copy(self.parentarray) newmap.wordids=copy.copy(self.wordids) newmap.wordcolortypes=copy.copy(self.wordcolortypes) wds=self.objectValues('MapWord') for w in wds: nw=w.makeCopy() nw.id=w.id newmap._setObject(nw.id, nw) edges=self.objectValues('MapEdge') for e in edges: ne=e.makeCopy() ne.id=e.id newmap._setObject(ne.id, ne) newmap.newwordidnr=self.newwordidnr newmap.newedgeidnr=self.newedgeidnr newmap.title=self.title newmap.description=self.description newmap.fontindex=self.fontindex newmap.wordbackgroundcolordefaultindex=self.wordbackgroundcolordefaultindex newmap.maxwords=self.maxwords newmap.maxedgetypes=self.maxedgetypes newmap.maxedgecount=self.maxedgecount for wd in self.declaredwords: newmap.declaredwords.append(wd) for eg in self.declarededges: newmap.declarededges.append(eg) newmap.menutypeowner=self.menutypeowner newmap.allowedsubmaps=self.allowedsubmaps newmap.wordgraphicalpropertiesallowed=self.wordgraphicalpropertiesallowed newmap.equationsallowed=self.equationsallowed newmap.mappropertiesallowed=self.mappropertiesallowed newmap.chanchangeproperties=self.canchangeproperties newmap.maxwords=self.maxwords newmap.maxedgetypes=self.maxedgetypes for w in self.declaredwords: newmap.declaredwords.append(w) for e in self.declarededges: newmap.declarededges.append(e) self.activationstate=0 return newmap security.declareProtected(perm_view, 'addChildMap') def addChildMap(self, copying=0, wordsonly=0): "Adds child map to current map" nr=self.getNewWordMapNr() if copying: m=self.makeCopy() else: if wordsonly: m=WordMap() for wd in self.objectValues('MapWord'): m.addWord(wd.title) else: m=WordMap() m.canchangeproperties=self.mappropertiesallowed m.id='map'+str(nr) self._setObject(m.id, m) m.zoomToBounds() return m def addChildMap_handler(self, REQUEST): "Adds child map and redirects to index" self.addChildMap(copying=1) REQUEST.RESPONSE.redirect(self.absolute_url()) def collectEdgeList(self, map, wlist): "Appends edges to existing list" for eg in map.getMapEdges(): wd1=getattr(map, eg.startword).title.lower() wd2=getattr(map, eg.endword).title.lower() if wd1>wd2: temp=wd1 wd1=wd2 wd2=temp if wd2 in wlist[wd1].keys(): if eg.text_in_line.lower() not in wlist[wd1][wd2].split(','): wlist[wd1][wd2]+=","+eg.text_in_line.lower() else: wlist[wd1][wd2]=eg.text_in_line.lower() for wm in map.getChildMaps(): self.collectEdgeList(wm, wlist) def collectWordList(self, map, wlist): "Appends map and submap words to list" for w in map.getMapWords(): if w.title.lower() not in wlist.keys(): wlist[w.title.lower()]={} for wm in map.getChildMaps(): self.collectWordList(wm, wlist) def makeGlobalMap(self, REQUEST): "Yldkaart, kuhu kogutakse kokku koik selle kaardi ja ta alamkaartide moisted ja nende vahelised seosed" wordlist={} self.collectWordList(self, wordlist) self.collectEdgeList(self, wordlist) uus=WordMap() uus.readData(wordlist) uus.calculateRandomPlacement() uus.id="globalMap" self.globalMap=uus return wordlist security.declareProtected(perm_view, 'getChildMaps') def getChildMaps(self): "Child maps of current map" return self.objectValues('WordMap') security.declareProtected(perm_view, 'readData') def readData(self, kogum): """Parameetrina saadavas assotsiatiivmassiivis on votmeteks solmede ID-d iga elemendi kyljes olevas assotsiatiivmassiivis on votmeteks solmede ID-d kuhu vastavalt kohalt viidatakse ning vaartusteks seose tyybid. Salvestatase arvuline massiiv, kus iga elemendi kohal olevas massiivis on kirjas arvud, millega vastaval solmel seos""" tulemus=[] votmed=kogum.keys() votmed.sort() for i in range(len(votmed)): self.addWord(votmed[i]) for i in range(len(votmed)): #abi=[] element=votmed[i] for x in kogum[element].keys(): eg=self.addEdge(i, votmed.index(x), textinline=kogum[element][x]) for k in kogum[element][x].split(','): eg.globalweights[k]=1 self.wordplaces=[] #sonade paiknemine graafis for i in range(len(votmed)): self.wordplaces.append([0, i*10]) #algul yksteise alla security.declareProtected(perm_view, 'calculateDistances') def calculateDistances(self, nr): "Luuakse massiiv kaugused naitamaks, mitme serva kaugusel on iga tipp tipust nr" abi=[] vanem=[] for i in range(len(self.relationnumbers)): abi.append(-1) vanem.append(-1) abi[nr]=0 jarjekord=[] jarjekord.append(nr) self.distancegrouparray=[] while len(jarjekord)>0: uuritav=jarjekord.pop(0) if len(self.distancegrouparray)<=abi[uuritav]: self.distancegrouparray.append([]) self.distancegrouparray[abi[uuritav]].append(uuritav) for x in self.relationnumbers[uuritav]: if abi[x]==-1: abi[x]=abi[uuritav]+1 vanem[x]=uuritav jarjekord.append(x) self.kaugused=abi self.suurimkaugus=0 for k in self.kaugused: if k>self.suurimkaugus: self.suurimkaugus=k self.startingvertex=nr self.parentarray=vanem security.declareProtected(perm_view, 'calculateHorizontalTree') def calculateHorizontalTree(self): "Luuakse pilt, kus peaelement hakkab vasakult keskelt, alamelemendid hargnevad" self.calculateRandomPlacement() tulpadearv=len(self.distancegrouparray) tulbalaius=(self.viewingbounds[2]-self.leftdistance*1.0/self.viewcoef-self.rightdistance*1.0/self.viewcoef)/tulpadearv sonax=self.viewingbounds[0]+self.leftdistance/self.viewcoef for distance in range(len(self.distancegrouparray)): sonutulbas=len(self.distancegrouparray[distance]) reavahe=(self.viewingbounds[3]-self.topdistance*1.0/self.viewcoef-self.bottomdistance*1.0/self.viewcoef)/sonutulbas sonay=self.viewingbounds[1]+self.topdistance*1.0/self.viewcoef+reavahe*1.0/2 for sonanr in range(sonutulbas): self.wordplaces[self.distancegrouparray[distance][sonanr]]=[sonax, sonay] sonay+=reavahe sonax+=tulbalaius self.zoomToBounds() security.declareProtected(perm_view, 'calculateCircleTree') def calculateCircleTree(self): "Tree, where are central word and others around him in circles" centerx=self.viewingcentre[0] centery=self.viewingcentre[1] maxr=min(self.viewingbounds[2]-self.leftdistance*1.0/self.viewcoef-self.rightdistance*1.0/self.viewcoef, self.viewingbounds[3]-self.topdistance*1.0/self.viewcoef-self.bottomdistance*1.0/self.viewcoef)/2 r=0 dr=maxr/(len(self.distancegrouparray)-1) for distance in range(len(self.distancegrouparray)): import random startangle=random.random()*6.28 angle=startangle deltaangle=6.28/len(self.distancegrouparray[distance]) for nr in self.distancegrouparray[distance]: self.wordplaces[nr]=[centerx+r*math.cos(angle), centery+r*math.sin(angle)] angle+=deltaangle r+=dr self.zoomToBounds() security.declareProtected(perm_edit, 'calculateRandomPlacement') def calculateRandomPlacement(self): "Random placement of words" import random for nr in range(len(self.wordplaces)): self.wordplaces[nr]=[random.random()*500, random.random()*500] self.zoomToBounds(); return "ok" security.declareProtected(perm_view, 'calculateRayCircleTree') def calculateRayCircleTree(self): "Each new word will be centre of new circle" self.calculateRandomPlacement() centerx=self.viewingcentre[0] centery=self.viewingcentre[1] maxr=min(self.viewingbounds[2]-self.leftdistance*1.0/self.viewcoef-self.rightdistance*1.0/self.viewcoef, self.viewingbounds[3]-self.topdistance*1.0/self.viewcoef-self.bottomdistance*1.0/self.viewcoef)/2.0 r=0 if not self.distancegrouparray: return self.wordplaces[self.distancegrouparray[0][0]]=[centerx, centery] if len(self.distancegrouparray)==1: return dr=maxr/(len(self.distancegrouparray)-1) startangle=3.14/4 angle=startangle deltaangle=6.28/len(self.distancegrouparray[1]) angles=[0]*len(self.wordplaces) r+=dr for nr in self.distancegrouparray[1]: self.wordplaces[nr]=[centerx+r*math.cos(angle), centery+r*math.sin(angle)] angles[nr]=angle angle+=deltaangle distance=2 while distance0: deltaangle=3.14/len(v) angle=deltaangle/2-3.14/2+angles[parent] for nr in v: self.wordplaces[nr]= \ [ self.wordplaces[parent][0]+dr*math.cos(angle), self.wordplaces[parent][1]+dr*math.sin(angle) ] angles[nr]=(angles[parent]+angle)/2.0 angle+=deltaangle distance+=1 self.zoomToBounds() security.declareProtected(perm_view, 'clearPicture') def clearPicture(self, g, psize=None): "Pildile joonistatakse taustavarviga ristkylik" if psize is None: psize=self.picturesize g.setink(self.backgroundcolor) g.setfill(1) g.rectangle((0, 0, psize[0], psize[1])) g.setfill(0) security.declareProtected(perm_view, 'pictureX') def pictureX(self, worldx, vcentre=None, vcoef=None, psize=None): "From world coordinates to picture coordinates" if vcentre is None: vcentre=self.viewingcentre if vcoef is None: vcoef=self.viewcoef if psize is None: psize=self.picturesize return (worldx-vcentre[0])*vcoef+psize[0]/2.0 security.declareProtected(perm_view, 'pictureY') def pictureY(self, worldy, vcentre=None, vcoef=None, psize=None): "From world coordinates to picture coordinates" if vcentre is None: vcentre=self.viewingcentre if vcoef is None: vcoef=self.viewcoef if psize is None: psize=self.picturesize return (worldy-vcentre[1])*vcoef+psize[1]/2.0 security.declareProtected(perm_view, 'worldX') def worldX(self, picturex, vcentre=None, vcoef=None, psize=None): "From picture coordinates to world coordinates" if vcentre is None: vcentre=self.viewingcentre if vcoef is None: vcoef=self.viewcoef if psize is None: psize=self.picturesize return (picturex-psize[0]/2.0)/vcoef+vcentre[0] security.declareProtected(perm_view, 'worldY') def worldY(self, picturey, vcentre=None, vcoef=None, psize=None): "From picture coordinates to world coordinates" if vcentre is None: vcentre=self.viewingcentre if vcoef is None: vcoef=self.viewcoef if psize is None: psize=self.picturesize return (picturey-psize[1]/2.0)/vcoef+vcentre[1] security.declareProtected('View', 'drawWords') def drawWords(self, g, vcentre=None, vcoef=None, psize=None, pilt=None, withicons=1, font=None): "Koostatakse sonadest pilt" if self.newconceptx is not None: tzx=g.textsize(" ", font=font)[0] tzy=g.textsize(" ", font=font)[1] g.rectangle( ( self.pictureX(self.newconceptx, vcentre, vcoef, psize)-tzx/2, self.pictureY(self.newconcepty, vcentre, vcoef, psize)-tzy/2, self.pictureX(self.newconceptx, vcentre, vcoef, psize)+tzx/2, self.pictureY(self.newconcepty, vcentre, vcoef, psize)+tzy/2 ), fill=self.getWordBackgroundColors()[self.wordbackgroundcolordefaultindex] ) for i in range(len(self.wordids)): wd=getattr(self, self.wordids[i]) paintingword=getattr(self, self.wordids[i]).title res=self.loadFont(paintingword, self.fontindex) font=res[1] paintingword=res[0] if len(paintingword)<10: paintingword=paintingword+(10-len(paintingword))*" " tzx=g.textsize(paintingword, font=font)[0] tzy=g.textsize(paintingword, font=font)[1] if wd.hasPicture() and withicons: try: import cStringIO p=Image.open(cStringIO.StringIO(wd.getPicture())) p.thumbnail((wd.psize, wd.psize), Image.ANTIALIAS) kast=p.getbbox() if getattr(self, self.wordids[i]).title!=".": pilt.paste(p , [ int(kast[0]-tzx/2+self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)), int(kast[1]-tzy/2+self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)+tzy+5), int(kast[2]-tzx/2+self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)), int(kast[3]-tzy/2+self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)+tzy+5), ]) else: pilt.paste(p , [ int(-int(kast[2]/2)+self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)), int(-int(kast[3]/2)+self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)), int(-int(kast[2]/2)+kast[2]+self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)), int(-int(kast[3]/2)+kast[3]+self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)), ]) except ValueError, ve: pass if getattr(self, self.wordids[i]).title!="." or (not wd.hasPicture()): g.rectangle( ( self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)-tzx/2, self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)-tzy/2, self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)+tzx/2, self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)+tzy/2 ), fill=self.getWordBackgroundColors()[getattr(self, self.wordids[i]).backgroundcolorindex] ) if wd.getHyperlinkURL(): import os #linkpic=Image.open(os.path.join(Globals.INSTANCE_HOME, "Products", "iva", "ui", "skins", "default", "images", "link_gif.gif")) linkpic = Image.open(self.restrictedTraverse('++resource++images/link_gif.gif')) kast=linkpic.getbbox() pilt.paste( linkpic, ( self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)-tzx/2-kast[2], self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)-tzy/2, self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)-tzx/2, self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)-tzy/2+kast[3] ), ) if wd.getAttachmentFileName(): import os attpic=Image.open(os.path.join(Globals.INSTANCE_HOME, "Products", "iva", "ui", "skins", "default", "images", "document_gif.gif")) kast=attpic.getbbox() pilt.paste( attpic, ( self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)+tzx/2, self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)-tzy/2, self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)+tzx/2+kast[2], self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)-tzy/2+kast[3] ), ) try: g.text( ( self.pictureX(self.wordplaces[i][0], vcentre, vcoef, psize)+2-tzx/2, self.pictureY(self.wordplaces[i][1], vcentre, vcoef, psize)-tzy/2 ), #Kuna PIL ei tunnista unicodet # unicode(getattr(self, self.wordids[i]).title, 'utf-8').encode('iso-8859-1'), paintingword, fill="rgb(255, 255, 255)", font=font ) except UnicodeDecodeError, ex: pass for wi in self.selectedwords: if getattr(self, self.wordids[wi]).title!="." or (not getattr(self, self.wordids[wi]).hasPicture()): paintingword=getattr(self, self.wordids[wi]).title if len(paintingword)<10: paintingword=paintingword+(10-len(paintingword))*" " tzx=g.textsize(paintingword, font=font)[0] tzy=g.textsize(paintingword, font=font)[1] g.rectangle(( self.pictureX(self.wordplaces[wi][0], vcentre, vcoef, psize)-2-tzx/2, self.pictureY(self.wordplaces[wi][1], vcentre, vcoef, psize)-2-tzy/2, self.pictureX(self.wordplaces[wi][0], vcentre, vcoef, psize)+tzx/2+2, self.pictureY(self.wordplaces[wi][1], vcentre, vcoef, psize)+tzy/2+2 )) else: d=self.getPictureRealSize(getattr(self, self.wordids[wi])) g.rectangle(( self.pictureX(self.wordplaces[wi][0], vcentre, vcoef, psize)-int(d[0]/2), self.pictureY(self.wordplaces[wi][1], vcentre, vcoef, psize)-int(d[1]/2), self.pictureX(self.wordplaces[wi][0], vcentre, vcoef, psize)-int(d[0]/2)+d[0], self.pictureY(self.wordplaces[wi][1], vcentre, vcoef, psize)-int(d[1]/2)+d[1] )) security.declareProtected(perm_view, 'drawEdges') def drawEdges(self, g, vcentre=None, vcoef=None, psize=None, pilt=None, withicons=1, font=None): "Sonade vahele tommatakse jooned" g.setink(self.linecolor) sele=self.getSelectedEdge() for nr in range(len(self.wordids)): for sihtnr in self.relationnumbers[nr]: e=self.getEdge(self.wordids[nr], self.wordids[sihtnr]) if e.startword==self.wordids[nr]: wd1=getattr(self, self.wordids[nr]) wd2=getattr(self, self.wordids[sihtnr]) paintingword1=wd1.title paintingword2=wd2.title if len(paintingword1)<10: paintingword1=paintingword1+(10-len(paintingword1))*" " if len(paintingword2)<10: paintingword2=paintingword2+(10-len(paintingword2))*" " tzx1=g.textsize(paintingword1, font=font)[0]/self.viewcoef tzy1=g.textsize(paintingword1, font=font)[1]/self.viewcoef tzx2=g.textsize(paintingword2, font=font)[0]/self.viewcoef tzy2=g.textsize(paintingword2, font=font)[1]/self.viewcoef if wd1.title==".": d=self.getPictureWorldSize(wd1) tzx1=d[0] tzy1=d[1] if wd2.title==".": d=self.getPictureWorldSize(wd2) tzx2=d[0] tzy2=d[1] if tzx1==0: tzx1=0.0001 if tzy1==0: tzy1=0.0001 if tzx2==0: tzx2=0.0001 if tzy2==0: tzy2=0.0001 wpx1=self.wordplaces[nr][0] wpy1=self.wordplaces[nr][1] wpx2=self.wordplaces[sihtnr][0] wpy2=self.wordplaces[sihtnr][1] dx=wpx2-wpx1 dy=wpy2-wpy1 if dx==0: dx=0.0002 if dy==0: dy=0.0002 jpx1=0 jpy1=0 jpx2=0 jpy2=0 if (dx>0) and (dy>0): if dy*1.0/dx>tzy1*1.0/tzx1: jpx1=wpx1+tzy1/2/dy*dx jpy1=wpy1+tzy1/2 else: jpx1=wpx1+tzx1/2 jpy1=wpy1+tzx1/2/dx*dy if dy*1.0/dx>tzy2*1.0/tzx2: jpx2=wpx2-tzy2/2/dy*dx jpy2=wpy2-tzy2/2 else: jpx2=wpx2-tzx2/2 jpy2=wpy2-tzx2/2/dx*dy if (dy<0): if abs(dy)*1.0/dx>tzy1*1.0/tzx1: jpx1=wpx1+tzy1/2/(-dy)*dx jpy1=wpy1-tzy1/2 else: jpx1=wpx1+tzx1/2 jpy1=wpy1-tzx1/2/dx*(-dy) if abs(dy)*1.0/dx>tzy2*1.0/tzx2: jpx2=wpx2-tzy2/2/(-dy)*dx jpy2=wpy2+tzy2/2 else: jpx2=wpx2-tzx2/2 jpy2=wpy2+tzx2/2/dx*(-dy) if (dx<0) and (dy<0): dx=-dx dy=-dy if abs(dy)*1.0/abs(dx)>tzy1*1.0/tzx1: jpx1=wpx1-tzy1/2/dy*dx jpy1=wpy1-tzy1/2 else: jpx1=wpx1-tzx1/2 jpy1=wpy1-tzx1/2/dx*dy if abs(dy)*1.0/abs(dx)>tzy2*1.0/tzx2: jpx2=wpx2+tzy2/2/dy*dx jpy2=wpy2+tzy2/2 else: jpx2=wpx2+tzx2/2 jpy2=wpy2+tzx2/2/dx*dy if(dx<0) and (dy>0): if dy*1.0/abs(dx)>tzy1*1.0/tzx1: jpx1=wpx1-tzy1/2/dy*(-dx) jpy1=wpy1+tzy1/2 else: jpx1=wpx1-tzx1/2 jpy1=wpy1+tzx1/2/(-dx)*dy if dy*1.0/abs(dx)>tzy2*1.0/tzx2: jpx2=wpx2+tzy2/2/dy*(-dx) jpy2=wpy2-tzy2/2 else: jpx2=wpx2+tzx2/2 jpy2=wpy2-tzx2/2/(-dx)*dy g.setink(self.linecolor) if sele and e.startword==sele.startword and e.endword==sele.endword: g.setink(self.selectedlinecolor) if e.startword==self.wordids[nr]: if e.startarrow: self.drawArrow(g, jpx1, jpy1, jpx2, jpy2, vcentre, vcoef, psize, e.weight) if e.endarrow: self.drawArrow(g, jpx2, jpy2, jpx1, jpy1, vcentre, vcoef, psize, e.weight) self.drawWidthLine(g,jpx1, jpy1, jpx2, jpy2, e.weight, vcentre, vcoef, psize) if withicons and e.text_in_line.strip(): res=self.loadFont(e.text_in_line, self.fontindex) font=res[1] paintingword=res[0] # tzx=g.textsize(unicode(e.text_in_line, 'utf-8').encode('iso-8859-1'), font=font)[0] # tzy=g.textsize(unicode(e.text_in_line, 'utf-8').encode('iso-8859-1'), font=font)[1] tzx=g.textsize(paintingword, font=font)[0] tzy=g.textsize(paintingword, font=font)[1] g.rectangle( ( self.pictureX((self.wordplaces[nr][0]+self.wordplaces[sihtnr][0])/2, vcentre, vcoef, psize)-tzx/2, self.pictureY((self.wordplaces[nr][1]+self.wordplaces[sihtnr][1])/2, vcentre, vcoef, psize)-tzy/2, self.pictureX((self.wordplaces[nr][0]+self.wordplaces[sihtnr][0])/2, vcentre, vcoef, psize)+tzx/2, self.pictureY((self.wordplaces[nr][1]+self.wordplaces[sihtnr][1])/2, vcentre, vcoef, psize)+tzy/2 ), fill="rgb(255, 255, 255)" ) g.text( ( self.pictureX((self.wordplaces[nr][0]+self.wordplaces[sihtnr][0])/2)-tzx/2, self.pictureY((self.wordplaces[nr][1]+self.wordplaces[sihtnr][1])/2)-tzy/2 ), # unicode(e.text_in_line, 'utf-8').encode('iso-8859-1'), paintingword, font=font ) if e.hasPicture() and withicons: try: import cStringIO p=Image.open(cStringIO.StringIO(e.getPicture())) p.thumbnail((e.psize, e.psize), Image.ANTIALIAS) kast=p.getbbox() d=self.getPictureRealSize(e) pilt.paste(p , [ int(self.pictureX((self.wordplaces[nr][0]+self.wordplaces[sihtnr][0])/2, vcentre, vcoef, psize)-d[0]/2), int(self.pictureY((self.wordplaces[nr][1]+self.wordplaces[sihtnr][1])/2, vcentre, vcoef, psize)-d[1]/2), int(self.pictureX((self.wordplaces[nr][0]+self.wordplaces[sihtnr][0])/2, vcentre, vcoef, psize)-d[0]/2)+d[0], int(self.pictureY((self.wordplaces[nr][1]+self.wordplaces[sihtnr][1])/2, vcentre, vcoef, psize)-d[1]/2)+d[1], ]) except: pass security.declareProtected(perm_view, 'drawArrow') def drawArrow(self, g, px1, py1, px2, py2, vcentre=None, vcoef=None, psize=None, width=1): "Draws the arrow to px1, py1 (int world coordinates)" dx=px2-px1 dy=py2-py1 linelength=math.sqrt(dx*dx+dy*dy) arrowlength=10.0/vcoef arrowangle=3.14/10 if linelength==0: return acoef=arrowlength/linelength ax=dx*acoef ay=dy*acoef p1=self.rotatePoint(ax, ay, arrowangle) p2=self.rotatePoint(ax, ay, -arrowangle) self.drawWidthLine(g, px1, py1, px1+p1[0], py1+p1[1], width, vcentre, vcoef, psize) self.drawWidthLine(g, px1, py1, px1+p2[0], py1+p2[1], width, vcentre, vcoef, psize) security.declareProtected(perm_view, 'drawWidthLine') def drawWidthLine(self, g, x1, y1, x2, y2, w, vcentre=None, vcoef=None, psize=None): "Draws line with specified width" px1=self.pictureX(x1, vcentre, vcoef, psize) py1=self.pictureY(y1, vcentre, vcoef, psize) px2=self.pictureX(x2, vcentre, vcoef, psize) py2=self.pictureY(y2, vcentre, vcoef, psize) dx=px2-px1 dy=py2-py1 linelength=math.sqrt(dx*dx+dy*dy) step=1 if w==0: step=5 w=1 #for i in range(int(linelength)): i=0 while ib[0]+b[2]: b[2]=self.viewingbounds[0]+self.viewingbounds[2]-b[0] if self.viewingbounds[1]+self.viewingbounds[3]>b[1]+b[3]: b[3]=self.viewingbounds[1]+self.viewingbounds[3]-b[1] if self.viewingbounds[0]kast[3]: if kast[2]>wd.psize: t[0]=wd.psize t[1]=int((kast[3]*1.0/kast[2])*wd.psize) else: if kast[3]>wd.psize: t[1]=wd.psize t[0]=int((kast[2]*1.0/kast[3])*wd.psize) return t security.declareProtected(perm_view, 'getPictureWorldSize') def getPictureWorldSize(self, wd): "Getting width and height in world coordinates" t=self.getPictureRealSize(wd) t=[t[0]/self.viewcoef, t[1]/self.viewcoef] return t security.declareProtected(perm_view, 'findWordInPicture') def findWordInPicture(self, x, y): "Valitud kohal asuva sona jarjekorranumber. Puudumisel -1" from PIL import Image, ImageDraw pilt=Image.new('RGB', self.picturesize) g=ImageDraw.ImageDraw(pilt) leitud=-1 x=float(x) y=float(y) font=self.loadCurrentFont() import os #linkpic=Image.open(os.path.join(Globals.INSTANCE_HOME, "Products", "iva", "ui", "skins", "default", "images", "link_gif.gif")) link_img = self.unrestrictedTraverse('++resource++images/link_gif.gif') linkpic = Image.open(link_img.context.path) doc_img = self.unrestrictedTraverse('++resource++images/document_gif.gif') docpic=Image.open(doc_img.context.path) kast=linkpic.getbbox() kast2=docpic.getbbox() for nr in range(len(self.wordplaces)): wd=getattr(self, self.wordids[nr]) if wd.title!="." or(not wd.hasPicture()): paintingword=getattr(self, self.wordids[nr]).title if len(paintingword)<10: paintingword=paintingword+(10-len(paintingword))*" " tzx=g.textsize(paintingword, font=font)[0]/self.viewcoef tzy=g.textsize(paintingword, font=font)[1]/self.viewcoef if x>=self.wordplaces[nr][0]-tzx/2 and x<=self.wordplaces[nr][0]+tzx/2 and \ y>=self.wordplaces[nr][1]-tzy/2 and y<=self.wordplaces[nr][1]+tzy/2: leitud=nr self.selectingtype="t" if wd.getHyperlinkURL(): if x>=self.wordplaces[nr][0]-tzx/2-kast[2] and x<=self.wordplaces[nr][0]-tzx/2 and \ y>=self.wordplaces[nr][1]-tzy/2 and y<=self.wordplaces[nr][1]+tzy/2: leitud=nr self.selectingtype="l" self.activationstate=0 self.selectedwords=[] if wd.getAttachmentFileName(): if x>=self.wordplaces[nr][0]+tzx/2 and x<=self.wordplaces[nr][0]+tzx/2+kast2[2] and \ y>=self.wordplaces[nr][1]-tzy/2 and y<=self.wordplaces[nr][1]+tzy/2: leitud=nr self.selectingtype="d" self.activationstate=0 self.selectedwords=[] wd=getattr(self, self.wordids[nr]) if wd.hasPicture(): try: d=self.getPictureWorldSize(wd) if x>self.wordplaces[nr][0]-tzx/2 and xself.wordplaces[nr][1] and y0: self.selectingtype="p" if wd.latexcode: if self.equationsallowed: self.selectingtype="v" except: pass else: d=self.getPictureWorldSize(wd) if x>self.wordplaces[nr][0]-d[0]/2 and\ xself.wordplaces[nr][1]-d[1]/2 and\ y=min(x1, x2)-self.selectingdistance/self.viewcoef and x<=max(x1, x2)+self.selectingdistance/self.viewcoef and \ y>=min(y1, y2)-self.selectingdistance/self.viewcoef and y<=max(y1, y2)+self.selectingdistance/self.viewcoef: self.selectingtype="t" return [p1, p2] except: pass eg=self.getEdge(self.wordids[p1], self.wordids[p2]) if eg.text_in_line: tzx=g.textsize(eg.text_in_line, font=font)[0]/self.viewcoef tzy=g.textsize(eg.text_in_line, font=font)[1]/self.viewcoef if x>(x1+x2)/2-tzx and x<(x1+x2)/2+tzx and \ y>(y1+y2)/2-tzy and y<(y1+y2)/2+tzy: return [p1, p2] if eg.hasPicture(): d=self.getPictureWorldSize(eg) if x>(self.wordplaces[p1][0]+self.wordplaces[p2][0])/2-d[0]/2 and \ x<(self.wordplaces[p1][0]+self.wordplaces[p2][0])/2+d[0]/2 and \ y>(self.wordplaces[p1][1]+self.wordplaces[p2][1])/2-d[1]/2 and \ y<(self.wordplaces[p1][1]+self.wordplaces[p2][1])/2+d[0]/2: if self.menutypeowner>0: self.selectingtype="p" if self.equationsallowed: if eg.latexcode: self.selectingtype="v" return [p1, p2] return None security.declareProtected(perm_view, 'getPicture') def getPicture(self, REQUEST): "Pilt ekraanile" # if str(REQUEST.AUTHENTICATED_USER)!=self.getOwner(): if not self.isOwner(REQUEST): if not self.visibletoothers and not self.kas_opetaja(REQUEST): return "Pole lubatud vaadata" import cStringIO puhver=cStringIO.StringIO() if hasattr(REQUEST, 'pwidth'): self.picturesize[0]=int(REQUEST.get('pwidth')) self.picturesize[1]=int(REQUEST.get('pheight')) self.makePicture(REQUEST=REQUEST).save(puhver, 'gif') REQUEST.RESPONSE.setHeader("Content-type", "image/gif") return puhver.getvalue() security.declareProtected(perm_view, 'exportPicture') def exportPicture(self, REQUEST): "Export" self.picturesize=[600, 500] self.zoomToBounds() return self.getPicture(REQUEST) security.declareProtected(perm_view, 'getPlanPicture') def getPlanPicture(self, REQUEST): "Small picture where visible viewing area location in map" if not self.isOwner(REQUEST): if not self.visibletoothers and not self.kas_opetaja(REQUEST): return "Pole lubatud vaadata" import cStringIO puhver=cStringIO.StringIO() self.makePicture("plan").save(puhver, 'gif') REQUEST.RESPONSE.setHeader("Content-type", "image/gif") return puhver.getvalue() def savePicture(self, failinimi='pilt.gif'): "Pildi salvestus faili" self.makePicture().save(failinimi, 'gif') security.declareProtected(perm_view, 'zoomToBounds') def zoomToBounds(self): "Set all words visible" self.viewingbounds=self.getBounds() self.viewingbounds[0]-=self.leftdistance/self.viewcoef self.viewingbounds[1]-=self.topdistance/self.viewcoef self.viewingbounds[2]+=(self.leftdistance+self.rightdistance)/self.viewcoef self.viewingbounds[3]+=(self.topdistance+self.bottomdistance)/self.viewcoef self.viewingcentre[0]=self.viewingbounds[0]+self.viewingbounds[2]/2.0 self.viewingcentre[1]=self.viewingbounds[1]+self.viewingbounds[3]/2.0 self.viewcoef=min(self.picturesize[0]*1.0/self.viewingbounds[2], self.picturesize[1]*1.0/self.viewingbounds[3]) self.recalculateViewingBounds() security.declareProtected(perm_view, 'recalculateViewingBounds') def recalculateViewingBounds(self): "Recalculates viewing bounds using viewingcentre, picture size and viewcoef" self.viewingbounds=[ self.viewingcentre[0]-self.picturesize[0]/2.0/self.viewcoef, self.viewingcentre[1]-self.picturesize[1]/2.0/self.viewcoef, self.picturesize[0]*1.0/self.viewcoef, self.picturesize[1]*1.0/self.viewcoef ] security.declareProtected(perm_view, 'calculateZoomWithPoint') def calculateZoomWithPoint(self, x, y, direction='bigger'): "Calculates new displaying properties using user click data" self.viewingcentre=[x, y] if direction=="bigger": self.viewcoef*=(1+self.zoomcoef) if direction=="smaller": self.viewcoef/=(1.0+self.zoomcoef) self.recalculateViewingBounds() security.declareProtected(perm_view, 'checkPlanPlacing') def checkPlanPlacing(self, REQUEST): "If user changes location clicking to plan" if hasattr(REQUEST, 'plan1.x') and hasattr(REQUEST, 'plan1.y'): psize=self.planpicturesize b=self.getBounds() vcentre=[b[0]+b[2]/2.0, b[1]+b[3]/2] vcoef=min(psize[0]*1.0/b[2], psize[1]*1.0/b[3]) self.viewingcentre[0]=self.worldX(int(getattr(REQUEST, 'plan1.x')), vcentre, vcoef, psize) self.viewingcentre[1]=self.worldY(int(getattr(REQUEST, 'plan1.y')), vcentre, vcoef, psize) self.recalculateViewingBounds() security.declareProtected(perm_edit, 'checkNewWords') def checkNewWords(self, REQUEST): "Add new words to picture, if they exists" if hasattr(REQUEST, 'newwords'): if len(REQUEST.newwords)>0: wds=REQUEST.newwords.split(",") for wd in wds: if len(wd)>0: self.addWord(wd.strip(), creator=self.firstAndLast(str(REQUEST.AUTHENTICATED_USER))) self.selectSoloIcon(0) else: if (hasattr(REQUEST, 'valik') and getattr(REQUEST, 'valik')!="0" and getattr(REQUEST, 'valik')!="-1") \ or hasattr(REQUEST, 'pildifail') or getattr(REQUEST, 'valem1'): self.addWord(".", creator=self.firstAndLast(str(REQUEST.AUTHENTICATED_USER))) REQUEST.change="true" REQUEST.selectedword="." self.selectedwords=[len(self.wordplaces)-1,] #viimane self.wordChangeTab(REQUEST) self.activationstate=0 self.newconceptx=None self.newconcepty=None security.declareProtected(perm_edit, 'checkNewRequiredWords') def checkNewRequiredWords(self, REQUEST): "Add new words from declared words list" wds=self.objectValues('MapWord') for x in self.declaredwords: leitud=0 for wd in wds: if x==wd.title: leitud=1 if not leitud: self.addWord(x.strip(), creator='') security.declareProtected(perm_view, 'checkSampleData') def checkSampleData(self, REQUEST): "If sample data button is pressed" if hasattr(REQUEST, 'sampledata'): self.setSampleData() security.declareProtected(perm_view, 'checkClearAll') def checkClearAll(self, REQUEST): "If sample data button is pressed" if hasattr(REQUEST, 'clearall'): self.initializeVariables() security.declareProtected(perm_view, 'getPictureWidth') def getPictureWidth(self): "Picture width" return self.picturesize[0] security.declareProtected(perm_view, 'getPictureHeight') def getPictureHeight(self): "Picture height" return self.picturesize[1] security.declareProtected(perm_view, 'checkCommands') def checkCommands(self, REQUEST): "Check commands from Web page" if hasattr(REQUEST, 'actionnr'): self.setActiveAction(REQUEST.actionnr) if hasattr(REQUEST, 'pnr'): self.wmap_pichandler(REQUEST, REQUEST.pnr) if hasattr(REQUEST, 'screenwidth') and self.getAutomaticResolution(): screenwidth=int(REQUEST.get('screenwidth', 800)); screenheight=int(REQUEST.get('screenheight', 600)); pwidth=screenwidth-300 pheight=screenheight-230 if pheight<300: pheight=300 # if pwidth<600: pwidth=600 if self.getDisplayableMenuType(REQUEST)==2: pheight=pheight-20 # pheight=int(pwidth*6/11) self.picturesize=[pwidth, pheight] #self.zoomToBounds() else: self.picturesize=[self.getResolutionX(), self.getResolutionY()] self.checkPlanPlacing(REQUEST) self.checkNewWords(REQUEST) self.checkSampleData(REQUEST) self.checkClearAll(REQUEST) self.selectedarea=None security.declareProtected(perm_edit, 'wordChangeTab') def wordChangeTab(self, REQUEST): "Changing word properties" if hasattr(REQUEST, 'change'): wd=self.getSelectedItem() wd.title=getattr(REQUEST, 'selectedword') wd.backgroundcolorindex=int(getattr(REQUEST, 'colorindex', 0)) if hasattr(REQUEST, 'hyperlinkurl'): if(len(getattr(REQUEST, 'hyperlinkurl'))>7): wd.hyperlinkurl=getattr(REQUEST, 'hyperlinkurl') wd.hyperlinktitle=getattr(REQUEST, 'hyperlinktitle') if hasattr(REQUEST, 'attachment'): attachmentfile=getattr(REQUEST, 'attachment') if len(attachmentfile.filename)>0: wd.attachmentfiledata=attachmentfile.read() wd.attachmentfilename=attachmentfile.filename if hasattr(REQUEST, 'valik'): if getattr(REQUEST, 'valik')=="-1": wd.pilt=None wd.latexcode=None if getattr(REQUEST, 'valik')!="0" and getattr(REQUEST, 'valik')!="-1": ob=self.get_object_of_url(REQUEST.get('valik'), self, remove_last=0) wd.pilt=ob.pilt wd.psize=int(REQUEST.get('psize')) if hasattr(REQUEST, 'pildifail'): pildifail=getattr(REQUEST, 'pildifail') if len(pildifail.filename)>0: wd.pilt=pildifail.read() wd.latexcode="" import cStringIO p=Image.open(cStringIO.StringIO(wd.getPicture())) kast=p.getbbox() if max(kast)>self.picturesavingsize: p.thumbnail((self.picturesavingsize, self.picturesavingsize), Image.ANTIALIAS) s = cStringIO.StringIO() try: p.save(s, "JPEG", quality=100) except KeyError: p.save(s, "GIF", quality=100) s.seek(0) wd.pilt = s.read() wd.p_changed=1 t1=REQUEST.get('valem1', "") t1=t1.strip() if REQUEST.get('valik')=="-1": #et pildi kustutamisel valemit tagasi ei paneks t1="" #if t1: wd.latexcode=t1 if t1: wd.pilt=self.getLaTEXImage(REQUEST, t1) self.activationstate=0 self.selectedwords=[] security.declareProtected(perm_edit, 'wordmap_delete_selected_edge_handler') def wordmap_delete_selected_word_handler(self, REQUEST): "Deleting function" if hasattr(REQUEST, 'confirmation'): self.removeWord(self.selectedwords[0]) self.activationstate=0 self.selectedwords=[] REQUEST.RESPONSE.redirect('wmapindex.html') security.declareProtected(perm_edit, 'wordmap_delete_selected_edge_handler') def wordmap_delete_selected_edge_handler(self, REQUEST): "Deleting function" if hasattr(REQUEST, 'confirmation'): self.removeEdge(self.selectededge[0], self.selectededge[1]) self.selectededge=None self.activationstate=0 REQUEST.RESPONSE.redirect('wmapindex.html') def wmap_pichandler(self, REQUEST, pnr): "Icon click handler" pnr=int(pnr) self.additionalpictures=[] if pnr>=8 and pnr<=11: #arrows if pnr==8: self.viewingcentre[0]-=self.viewingbounds[2]/4.0 if pnr==9: self.viewingcentre[0]+=self.viewingbounds[2]/4.0 if pnr==10: self.viewingcentre[1]-=self.viewingbounds[3]/4.0 if pnr==11: self.viewingcentre[1]+=self.viewingbounds[3]/4.0 self.recalculateViewingBounds() if pnr==6: self.selectSoloIcon(6) self.activeaction=0 #Horizontal tree if pnr==7: self.selectSoloIcon(7) self.activeaction=6 #RayCircleTree if pnr==2: self.selectSoloIcon(2) if pnr==3: self.selectSoloIcon(3) if pnr==4: self.selectSoloIcon(4) self.activeaction=2 #Add edge if pnr==5: #removebuttonclick if self.selectededge: self.removeEdge(self.selectededge[0], self.selectededge[1]) self.selectededge=None else: self.hideSelectedWords() self.selectSoloIcon(5) if pnr==1: self.selectSoloIcon(1) self.activeaction=9 #Select area self.pictureselections[12]=1 if pnr==0: self.selectSoloIcon(0) self.closeMenus() self.activeaction=11 #Selecting arrow if pnr==12: self.selectSoloIcon(12) if pnr==13: #Selection area submenu self.selectSoloIcon(13) self.selectedarea=None self.selectedareafirstclick=None if pnr==14: #unselect all self.selectedwords=[] if pnr==18: #Selection move left self.moveSelection(-1, 0) if pnr==19: #Selection move right self.moveSelection( 1, 0) if pnr==20: #Selection move up self.moveSelection( 0, -1) if pnr==21: #Selection move down self.moveSelection( 0, 1) if pnr==22: #Edit menu self.closeMenus() self.pictureselections[22]=1 self.selectSoloIcon(4) if pnr==23: #Select menu self.closeMenus() self.pictureselections[23]=1 self.selectSoloIcon(12) if pnr==24: #Zoom menu self.closeMenus() self.pictureselections[24]=1 self.selectSoloIcon(2) if pnr==25: #zoom to bounds self.zoomToBounds() self.selectSoloIcon(0) def selectSoloIcon(self, pnr): "Only this icon will be selected" for i in range(len(self.pictureselections)): if i not in self.menuicons: self.pictureselections[i]=0 self.pictureselections[int(pnr)]=1 self.selectededge=None security.declareProtected(perm_view, 'closeMenus') def closeMenus(self): "All menus will be closed" for nr in self.menuicons: self.pictureselections[nr]=0 security.declareProtected(perm_edit, 'unselectAll') def unselectAll(self): "Unselects all, which is possible" self.selectededge=None self.selectedwords=[] self.newconceptx=None self.newconcepty=None self.activationstate=0 security.declareProtected(perm_view, 'getLockedTime') def getLockedTime(self): "Number of seconds to end of the lock, if editor is idle" return int(self.currenteditingsessionlength-(time.time()-self.currenteditingtime)) security.declareProtected(perm_view, 'wmapindex_handler') def wmapindex_handler(self, REQUEST): "ZPT form handler" uname=str(REQUEST.AUTHENTICATED_USER) if self.currenteditingusername and not uname==self.currenteditingusername: if self.selectededge or self.selectedwords or self.newconceptx: if time.time()-self.currenteditingtime>self.currenteditingsessionlength: self.unselectAll() self.currenteditingusername=uname self.currenteditingtime=time.time() REQUEST.RESPONSE.redirect("wmapindex.html") return else: REQUEST.RESPONSE.redirect("wmapindex.html?curuser="+self.currenteditingusername) return if not self.isOwner(REQUEST): if not self.otherscanedit: return if not self.kas_opetaja(REQUEST) and self.homeworkstatus==2: return self.currenteditingusername=uname self.currenteditingtime=time.time() self.checkCommands(REQUEST) if getattr(REQUEST, 'atype', -1)=="2": #Yks margitud sona if hasattr(REQUEST, 'delete'): return self.restrictedTraverse('message_dialog2.html')(self,REQUEST, title="Confirmation", message="Are you sure you want to delete this concept?", option1_name="cancel", option1_value="Cancel", option2_value="Delete", option2_name="confirmation", handler="wordmap_delete_selected_word_handler") self.wordChangeTab(REQUEST) if getattr(REQUEST, 'atype', -1)=="3": if not hasattr(REQUEST, 'cancel'): import string if string.strip(REQUEST.get('textinline', "")): til=REQUEST.get('textinline', "") else: til=REQUEST.get('edgetype', '') self.addEdge(self.selectedwords[0], self.selectedwords[1], creator=self.firstAndLast(str(REQUEST.AUTHENTICATED_USER)), textinline=til) self.activationstate=0 self.selectedwords=[] if getattr(REQUEST, 'atype', -1)=="4": if hasattr(REQUEST, 'delete'): return self.restrictedTraverse('message_dialog2.html')(self,REQUEST, title="Confirmation", message="Are you sure you want to delete this edge?", option1_name="cancel", option1_value="Cancel", option2_value="Delete", option2_name="confirmation", handler="wordmap_delete_selected_edge_handler") if hasattr(REQUEST, 'change'): import string if self.id!='globalMap': if string.strip(REQUEST.get('textinline', "")): self.getSelectedEdge().text_in_line=REQUEST.get('textinline') else: self.getSelectedEdge().text_in_line=REQUEST.get('edgetype', '') self.getSelectedEdge().psize=int(REQUEST.get('psize', 150)) if self.getWordGraphicalPropertiesAllowed(): self.getSelectedEdge().weight=float(REQUEST.get('weight', 1)) self.getSelectedEdge().startarrow=int(REQUEST.get('startarrow', 0)) self.getSelectedEdge().endarrow=int(REQUEST.get('endarrow', 0)) if hasattr(REQUEST, 'pildifail'): pildifail=getattr(REQUEST, 'pildifail') if len(pildifail.filename)>0: self.getSelectedEdge().pilt=pildifail.read() self.getSelectedEdge().latexcode="" import cStringIO p=Image.open(cStringIO.StringIO(self.getSelectedEdge().pilt)) maxvalue=int(REQUEST.get('psize')) kast=p.getbbox() if max(kast)>maxvalue: p.thumbnail((maxvalue, maxvalue), Image.ANTIALIAS) s = cStringIO.StringIO() try: p.save(s, "JPEG", quality=100) except KeyError: p.save(s, "GIF", quality=100) s.seek(0) self.getSelectedEdge().pilt = s.read() if hasattr(REQUEST, 'valik'): if getattr(REQUEST, 'valik')=="-1": self.getSelectedEdge().pilt=None if getattr(REQUEST, 'valik')!="-1" and getattr(REQUEST, 'valik') != "0": ob=self.get_object_of_url(REQUEST.get('valik'), self, remove_last=0) self.getSelectedEdge().pilt=ob.pilt t1=REQUEST.get('valem1', "") if t1: self.getSelectedEdge().latexcode=t1 if t1: self.getSelectedEdge().pilt=self.getLaTEXImage(REQUEST, t1) self.activationstate=0 self.selectededge=None if hasattr(REQUEST, 'map1.x') and hasattr(REQUEST, 'map1.y'): x=self.worldX(int(getattr(REQUEST, 'map1.x'))) y=self.worldY(int(getattr(REQUEST, 'map1.y'))) if self.pictureselections[6]: self.startHorizontalTreeCalculation(x, y) if self.pictureselections[4]: self.addEdgeInPicture(REQUEST, x, y) if self.pictureselections[5]: self.removeFromPicture(x, y) if self.pictureselections[7]: self.startRayCircleTreeCalculation(x, y) if self.pictureselections[2]: self.calculateZoomWithPoint(x, y, "bigger") if self.pictureselections[3]: self.calculateZoomWithPoint(x, y, "smaller") if self.pictureselections[12] or self.pictureselections[0]: self.selectingPointerClick(x, y, REQUEST) if self.selectingtype=="l" and self.selectedwords: REQUEST.RESPONSE.redirect(getattr(self, self.wordids[self.selectedwords[0]]).getHyperlinkURL()) return if self.selectingtype=="d" and self.selectedwords: REQUEST.RESPONSE.redirect(getattr(self, self.wordids[self.selectedwords[0]]).absolute_url()+"/getAttachmentFileData") return if self.pictureselections[13]: self.selectedAreaClick(x, y) if REQUEST.get('tabtype', 0): self.selectingtype=REQUEST.get('tabtype') REQUEST.RESPONSE.redirect('wmapindex.html?tabtype='+self.selectingtype) security.declareProtected(perm_edit, 'getLaTEXImage') def getLaTEXImage(self, REQUEST, text): "Makes a image from latex code" try: t="\\documentclass[12pt]{article}\n" t+="\\pagestyle{empty}\n" t+="\\begin{document}\n" t+="\\begin{displaymath}\n" t+=text+"\n" t+="\\end{displaymath}\n" t+="\\end{document}" import os failinimi=os.path.join(Globals.INSTANCE_HOME, "var", str(REQUEST.AUTHENTICATED_USER)) f=open(failinimi+".tex", "w") f.write(t) f.close() ppath = os.path.join(Globals.INSTANCE_HOME, 'Products', 'iva', 'textogif.py') #print ("python "+ppath+' '+failinimi+".tex >/dev/null 2>/dev/null") os.system("python "+ppath+' '+failinimi+".tex ") f3=open(os.path.join(Globals.INSTANCE_HOME, "var", failinimi+".gif"), "r") img=f3.read() f3.close() return img except: pass security.declareProtected(perm_edit, 'moveSelection') def moveSelection(self, dx, dy): "Move selected words" dx*=self.movingdistanceinscreen/self.viewcoef dy*=self.movingdistanceinscreen/self.viewcoef for wi in self.selectedwords: self.wordplaces[wi][0]+=dx self.wordplaces[wi][1]+=dy security.declareProtected(perm_view, 'removeFromPicture') def removeFromPicture(self, x, y): "Removing selected things" sona=self.findWordInPicture(x, y) if sona!=-1: self.removeWord(sona) if not self.selectededge: self.selectededge=self.findEdgeInPicture(x, y) if self.selectededge: self.removeEdge(self.selectededge[0], self.selectededge[1]) self.selectededge=None security.declareProtected(perm_view, 'addEdgeInPicture') def addEdgeInPicture(self, REQUEST, x, y): "Adding edge" sona=self.findWordInPicture(x, y) if sona==-1: self.selectedwords=[] return if not self.selectedwords: self.selectedwords.append(sona) return self.addEdge(self.selectedwords[0], sona, self.firstAndLast(str(REQUEST.AUTHENTICATED_USER))) self.selectedwords=[] security.declareProtected(perm_view, 'addEdge') def addEdge(self, word1, word2, creator="", textinline=""): "Adding edge data" wordmin=word1 wordmax=word2 if word1>word2: wordmin=word2 wordmax=word1 if wordmax not in self.relationnumbers[wordmin]: self.relationnumbers[wordmin].append(wordmax) if wordmin not in self.relationnumbers[wordmax]: self.relationnumbers[wordmax].append(wordmin) egid='eg'+str(self.getNewEdgeID()) eg=MapEdge(self.wordids[word1], self.wordids[word2], creator) eg.text_in_line=textinline eg.id=egid self._setObject(egid, eg) return eg security.declareProtected(perm_view, 'removeEdgeFromPicture') def removeEdgeFromPicture(self, x, y): "Removing edge in coordinaates" e=self.findEdgeInPicture(x, y) if e is None: self.selectededge=None return if e==self.selectededge: self.removeEdge(e[0], e[1]) self.selectededge=None return self.selectededge=e security.declareProtected(perm_view, 'removeEdge') def removeEdge(self, word1, word2): "Kylje eemaldus" if word1 in self.relationnumbers[word2]: self.relationnumbers[word2].remove(word1) if word2 in self.relationnumbers[word1]: self.relationnumbers[word1].remove(word2) sw=self.wordids[word1] ew=self.wordids[word2] for eg in self.objectValues('MapEdge'): if (eg.startword==sw and eg.endword==ew) or \ (eg.startword==ew and eg.endword==sw): self._delObject(eg.id) security.declareProtected(perm_view, 'getSelectedEdge') def getSelectedEdge(self): "Get selected edge from OFS or None if no edge selected" if self.selectededge: eg= self.getEdge(self.wordids[self.selectededge[0]], self.wordids[self.selectededge[1]]) return eg return None security.declareProtected(perm_view, 'hideSelectedWords') def hideSelectedWords(self): "Removing word edges and set word content empty" while self.selectedwords: wordnr=self.selectedwords.pop() self.removeWord(wordnr) security.declareProtected(perm_view, 'removeWord') def removeWord(self, wordnr): "Remove word and recalculate all edge indexes bigger the word" self.wordplaces.pop(wordnr) while self.relationnumbers[wordnr]: nr=self.relationnumbers[wordnr].pop() self.removeEdge(wordnr, nr) self.relationnumbers.pop(wordnr) for rn in self.relationnumbers: for i in range(len(rn)): if rn[i]>wordnr: rn[i]-=1 if wordnr in self.selectedwords: self.selectedwords.remove(wordnr) for i in range(len(self.selectedwords)): if self.selectedwords[i]>wordnr: self.selectedwords[i]-=1 self._delObject(self.wordids[wordnr]) self.wordids.pop(wordnr) security.declareProtected(perm_view, 'addWord') def addWord(self, word, creator=""): "Add word to graph and picture" wds=self.objectValues('MapWord') leitud=0 for wd in wds: if wd.title==word and word!=".": leitud=1 if leitud: return #see juba olemas if self.maxwords: if len(self.objectValues('MapWord'))>=self.maxwords: return #Enam ei mahu wdid='wd'+str(self.getNewWordID()) wdobj=MapWord(word, creator=creator, backgroundcolorindex=self.wordbackgroundcolordefaultindex) wdobj.id=wdid self._setObject(wdid, wdobj) self.wordids.append(wdid) self.relationnumbers.append([]) if self.newconceptx is not None: x=self.newconceptx y=self.newconcepty else: x=self.viewingbounds[0]+self.viewingbounds[2]*1.0/5 y=self.viewingbounds[1]+self.viewingbounds[3]*1.0/5 while (self.findWordInPicture(x, y)>=0) or (self.findWordInPicture(x, y+7.0/self.viewcoef)>=0) or\ (self.findWordInPicture(x, y-8.0/self.viewcoef)>=0): y+=1.0/self.viewcoef self.wordplaces.append([x, y]) return wdobj security.declareProtected(perm_view, 'startHorizontalTreeCalculation') def startHorizontalTreeCalculation(self, x, y): "Hiirevajutusest saadud andmed" sona=self.findWordInPicture(x, y) if sona!=-1: self.calculateDistances(sona) self.calculateHorizontalTree() self.selectedwords=[sona,] security.declareProtected(perm_view, 'startCircleTreeCalculation') def startCircleTreeCalculation(self, x, y): "Hiirevajutusest saadud andmed" sona=self.findWordInPicture(x, y) if sona!=-1: self.calculateDistances(sona) self.calculateCircleTree() security.declareProtected(perm_view, 'startRayCircleTreeCalculation') def startRayCircleTreeCalculation(self, x, y): "Hiirevajutusest saadud andmed" sona=self.findWordInPicture(x, y) if sona!=-1: self.calculateDistances(sona) self.calculateRayCircleTree() self.selectedwords=[sona,] security.declareProtected(perm_view, 'selectingPointerClick') def selectingPointerClick(self, x, y, REQUEST): "Mouse click, when selecting function is active" sonalisamisklops=1 if self.selectedwords or self.selectededge: sonalisamisklops=0 wi=self.findWordInPicture(x, y) if wi==-1: self.selectededge=self.findEdgeInPicture(x, y) else: self.selectededge=None if self.selectededge: self.selectedwords=[] self.activationstate=4 return if wi!=-1: if wi in self.selectedwords: self.selectedwords.remove(wi) else: if self.pictureselections[12]: #if select arrow in selection submenu self.selectedwords.append(wi) if self.pictureselections[0]: if len(self.selectedwords)==2: self.selectedwords.remove(self.selectedwords[0]) if len(self.selectedwords)==0: self.activationstate=2 self.selectedwords=[wi] else: if len(self.selectedwords)==1: self.selectedwords.append(wi) if self.getEdge(self.wordids[self.selectedwords[0]], self.wordids[self.selectedwords[1]]): self.selectededge=[self.selectedwords[0], self.selectedwords[1]] self.selectedwords=[] self.activationstate=4 else: self.activationstate=3 else: if len(self.selectedwords)>2: self.selectedwords=[wi] self.activationstate=0 else: if len(self.selectedwords)==1 and not self.selectededge: self.wordplaces[self.selectedwords[0]][0]=x self.wordplaces[self.selectedwords[0]][1]=y self.selectedwords=[] self.activationstate=0 if len(self.selectedwords)==2: self.activationstate=3 return if len(self.selectedwords)==1: self.activationstate=2 return if sonalisamisklops: self.activationstate=1 self.newconceptx=x self.newconcepty=y return if self.selectededge: self.activationstate=4 return self.activationstate=0 security.declareProtected(perm_view, 'selectedAreaClick') def selectedAreaClick(self, x, y): "Mouse click, when selecting function is active" if self.selectedareafirstclick is None and self.selectedarea is None: self.selectedareafirstclick=[x, y] return if self.selectedareafirstclick is not None and \ self.selectedarea is None: minx=min(self.selectedareafirstclick[0], x) maxx=max(self.selectedareafirstclick[0], x) miny=min(self.selectedareafirstclick[1], y) maxy=max(self.selectedareafirstclick[1], y) #self.selectedarea=[ # minx, miny, maxx-minx, maxy-miny #] self.selectedareafirstclick=None for wi in range(len(self.wordplaces)): if ( self.wordplaces[wi][0]>=minx and self.wordplaces[wi][0]<=maxx and self.wordplaces[wi][1]>=miny and self.wordplaces[wi][1]<=maxy ): if wi not in self.selectedwords: self.selectedwords.append(wi) return if self.selectedarea: if not self.isInSelectedArea(x, y): self.selectedareafirstclick=[x, y] self.selectedarea=None security.declareProtected(perm_view, 'isInSelectedArea') def isInSelectedArea(self, x, y): "test, is point in selected area" if not self.selectedarea: return 0 if x>=self.selectedarea[0] and x<=self.selectedarea[0]+self.selectedarea[2] and \ y>=self.selectedarea[1] and y<=self.selectedarea[1]+self.selectedarea[3]: return 1 return 0 security.declareProtected(perm_view, 'moveSelectedArea') def moveSelectedArea(self, x, y): "Left upper point of area to specified value. Moving all words in area" words=self.findWordsInSelectedArea() if words: dx=x-self.selectedarea[0] dy=y-self.selectedarea[1] for nr in words: self.wordplaces[nr][0]+=dx self.wordplaces[nr][1]+=dy self.selectedarea=None security.declareProtected(perm_view, 'findWordsInSelectedArea') def findWordsInSelectedArea(self): "List of word indexes" result=[] for nr in range(len(self.wordplaces)): if self.isInSelectedArea(self.wordplaces[nr][0], self.wordplaces[nr][1]): result.append(nr) return result security.declareProtected(perm_view, 'toString') def toString(self): "Vahetulemused statistika tarbeks" t= " relationnumbers:" +str(self.relationnumbers) +"\n"+\ " selectededge: "+str(self.getSelectedEdge())+"\n"+str(self.wordids)+"\n"+\ str(self.selectedwords)+"\n"+str(self.wordplaces)+"\n"+\ "viewcoef "+str(self.viewcoef)+" viewingcentre "+str(self.viewingcentre)+"\n"+\ "viewingbounds "+str(self.viewingbounds) return t def getBounds(self): "Minimal rectangle to place words. x, y, width, height" if len(self.wordplaces)==0: return [0, 0, self.picturesize[0], self.picturesize[1]] minx=maxx=self.wordplaces[0][0] miny=maxy=self.wordplaces[0][1] pilt=Image.new('RGB', [5, 5]) g=ImageDraw.ImageDraw(pilt) font=self.loadCurrentFont() for nr in range(len(self.wordplaces)): place=self.wordplaces[nr] paintingword=getattr(self, self.wordids[nr]).title if len(paintingword)<10: paintingword+=(10-len(paintingword))*" " tzx=g.textsize(paintingword, font=font)[0]*1.0/self.viewcoef tzy=g.textsize(paintingword, font=font)[1]*1.0/self.viewcoef #if place[0]maxx: maxx=place[0]+tzx/2 if place[1]-tzy/2maxy: maxy=place[1]+tzy/2 return [minx, miny, maxx-minx, maxy-miny] security.declareProtected(perm_view, 'areAllWordsVisible') def areAllWordsVisible(self): "True if something is invisible in big picture" visible=1 b=self.getBounds() vb=self.viewingbounds if b[0]vb[0]+vb[2]: visible=0 if b[1]+b[3]>vb[1]+vb[3]: visible=0 return visible # def getPictureSelections(self): # "for test" # return self.pictureselections security.declareProtected(perm_view, 'getActiveAction') def getActiveAction(self): "Current action" return "ac: "+str(self.activeaction) security.declareProtected(perm_view, 'setActiveAction') def setActiveAction(self, action): "setting property" self.activeaction=int(action) return self.activeaction def list_parents_to_top(): "For breadgrumbs" return [] security.declareProtected(perm_view, 'setSampleData') def setSampleData(self): "algandmed" gr={ "Tallinn": { "Aegviidu": "", "Valkla": "", "Maardu": "", "Rakvere": "raudtee", "Kuressaare": "", }, "Aegviidu": {}, "Valkla": {}, "Maardu":{}, "Rakvere": {"Roela": ""}, "Roela": {}, "Kuressaare":{"Kihelkonna": "", "Mustjala": ""}, "Kihelkonna": {}, "Mustjala": {"Tagala":""}, "Tagala": {}, } self.initializeVariables() self.readData(gr) self.calculateDistances(3) self.calculateHorizontalTree() self.selectedwords=[] return gr security.declareProtected(perm_view, 'getWordmapTree') def getWordmapTree(self): "Wordmaps to root" result=[] map=self while map.meta_type=='WordMap': result.append(map) map=map.aq_parent result.reverse() return result security.declareProtected(perm_view, 'get_name') def get_name(self): "name to breadgrumbs" return "" security.declareProtected(perm_view, 'canEdit') def canEdit(self, REQUEST): "Can current user edit the wordmap" return 1 security.declareProtected(perm_view, 'getEdgesStartedAtWdID') def getEdgesStartedAtWdID(self, wdid): "Returns list of edges" result=[] edges=self.objectValues('MapEdge') for e in edges: if e.startword==wdid: result.append(e) return result security.declareProtected(perm_view, 'getEdgesEndedAtWdID') def getEdgesEndedAtWdID(self, wdid): "Returns list of edges" result=[] edges=self.objectValues('MapEdge') for e in edges: if e.endword==wdid: result.append(e) return result security.declareProtected(perm_view, 'getEdgesWithWdId') def getEdgesWithWdId(self, wdid): "Edges connected to this word at start or at end" edges1=self.getEdgesStartedAtWdID(self, wdid) edges2=self.getEdgesEndedAtWdID(self, wdid) for e in edges2: edges1.append(e) return edges1 security.declareProtected(perm_view, 'getEdge') def getEdge(self, wdid1, wdid2): "Edge with this ids" edges=self.objectValues('MapEdge') for e in edges: if (wdid1==e.startword and wdid2==e.endword) or \ (wdid1==e.endword and wdid2==e.startword) : return e return None security.declareProtected(perm_view, 'getEdgeByWordTitles') def getEdgeByWordTitles(self, title1, title2): "Edge with specified words" edges=self.objectValues('MapEdge') for e in edges: if (getattr(self, e.startword).title==title1 and getattr(self, e.endword).title==title2) or \ (getattr(self, e.startword).title==title2 and getattr(self, e.endword).title==title1): return e return None security.declareProtected(perm_view, 'wordList') def wordList(self): "Words in map as text" t="id,title,description,creator,modifier\n" for w in self.objectValues('MapWord'): t+=str(w.id)+","+w.getTitle()+","+w.getDescription()+","+w.creator+","+w.modifier+"\n" return t security.declareProtected(perm_view, 'edgeList') def edgeList(self): "Edges in map as text" t="id,startword,endword,textinline,startarrow,endarrow,weight, type,creator,modifier\n" for e in self.objectValues("MapEdge"): t+=str(e.id)+","+e.getStartWordTitle()+","+e.getEndWordTitle()+","+e.getTextInLine()+","+\ str(e.getStartArrow())+","+str(e.getEndArrow())+","+str(e.getWeight())+","+\ e.getTypes()[e.getType()]+","+e.creator+","+e.modifier+"\n" return t security.declareProtected(perm_view, 'edgeList') def dataList(self): "Words and edges in map as text" return "Nodes:\n"+self.wordList()+"\nLinks:\n"+self.edgeList() def zeroEdgeCount(self): "Count of edges with zero weight" return len(self.objectValues('MapEdge'))-self.statRiPro() def statRiPro(self): "RiPro puhul loendatakse kokku koik laused, mis on saanud hinnanguks 1-3 punkti" n=0 for eg in self.objectValues('MapEdge'): if int(eg.weight)>0: n=n+1 return n def statVnet(self): "Seoste arv jagatud moistete arvuga" if len(self.objectValues('MapWord'))==0: return "No words" try: return math.floor(len(self.objectValues('MapEdge'))*1.0/len(self.objectValues('MapWord'))*100+0.5)*1.0/100 except: return "?" def statZentral(self): "Suurim seoste arv moiste kohta" n=0 for x in self.relationnumbers: if len(x)>n: n=len(x) return n def statFach(self): "Hinnangute keskmine" s=0 if self.statAlPro()==0: return "No edges" for eg in self.getMapEdges(): s+=eg.weight return math.floor((s*1.0/self.statAlPro())*100+0.5)*1.0/100 def statAlPro(self): "Seoste arv" return len(self.getMapEdges()) def statInsel(self, deletezeros=0): "Saarekeste arv" kogus=len(self.getMapWords()) if kogus==0: return 0 saared=[] for i in range(kogus): saared.append(-1) saar=0 veel=1 while veel: koht=0 while (kohtwd2: temp=wd1 wd1=wd2 wd2=temp hgm=self.getHeadMap().globalMap hgm.addWord(wd1) hgm.addWord(wd2) e=hgm.getEdgeByWordTitles(wd1, wd2) if e: e.text_in_line+=","+eg.text_in_line.lower() else: e=hgm.addEdge(hgm.getWordIDByTitle(wd1), hgm.getWordIDByTitle(wd2), eg.text_in_line.lower()) e.globalweights[eg.text_in_line.lower()]=eg.weight #hgm.calculateRandomPlacement() else: eg.weight=int(getattr(REQUEST, eg.id, 1)) self.analyzeStatus=1 self.graphType=int(getattr(REQUEST, 'graphtype')) if self.id=='globalMap': for eg in self.objectValues("MapEdge"): ks=eg.globalweights.keys() for i in range(len(ks)): eg.globalweights[ks[i]]=int(getattr(REQUEST, eg.id+'_'+str(i))) REQUEST.RESPONSE.redirect('wordmaps_assessment_results.html') def getWordIDByTitle(self, wtitle): "For searching" for wd in self.objectValues('MapWord'): if wd.title==wtitle: return self.wordids.index(wd.id) return None security.declareProtected(perm_view, 'XTMExport') def XTMExport(self): "Export to XTM XML format" from xml.dom import implementation, EMPTY_NAMESPACE from xml.dom.ext import PrettyPrint # doctype = implementation.createDocumentType("topicMap", "-//TopicMaps.Org//DTD XML Topic Map (XTM) 1.0//EN", # "http://www.topicmaps.org/xtm/#dtd") # dok=implementation.createDocument(EMPTY_NAMESPACE, "topicMap", doctype) dok=implementation.createDocument(EMPTY_NAMESPACE, "topicMap", None) juur=dok.documentElement juur.setAttribute("xmlns", "http://www.topicmaps.org/xtm/1.0/") juur.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink") mapprop=dok.createElement('topic') juur.appendChild(mapprop) mapprop.setAttribute("id", "mapprop") baseName=dok.createElement("baseName") mapprop.appendChild(baseName) baseNameString=dok.createElement("baseNameString") baseName.appendChild(baseNameString) baseNameStringData=dok.createTextNode(self.title) baseNameString.appendChild(baseNameStringData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "description") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(self.description) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "fontindex") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.fontindex)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "wordbackgroundcolordefaultindex") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.wordbackgroundcolordefaultindex)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "menutypeowner") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.menutypeowner)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "startingmap") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.startingmap)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "allowedsubmaps") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.allowedsubmaps)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "wordgraphicalpropertiesallowed") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.wordgraphicalpropertiesallowed)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "equationsallowed") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.equationsallowed)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "mappropertiesallowed") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.mappropertiesallowed)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "visibletoothers") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.visibletoothers)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "otherscanedit") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.otherscanedit)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "wordbackgroundcolordefaultindex") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.wordbackgroundcolordefaultindex)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "canchangeproperties") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.canchangeproperties)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "maxwords") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.maxwords)) resourceData.appendChild(resourceDataData) if self.maxedgetypes: occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "maxedgetypes") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.maxedgetypes)) resourceData.appendChild(resourceDataData) if self.maxedgecount: occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "maxedgecount") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.maxedgecount)) resourceData.appendChild(resourceDataData) for wd in self.declaredwords: occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "declaredword") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(wd) resourceData.appendChild(resourceDataData) for eg in self.declarededges: occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "declarededge") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(eg) resourceData.appendChild(resourceDataData) for t in self.wordcolortypes: occurence=dok.createElement("occurence") mapprop.appendChild(occurence) occurence.setAttribute("id", "wordcolortype") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(t) resourceData.appendChild(resourceDataData) for wd in self.objectValues('MapWord'): wel=dok.createElement('topic') wel.setAttribute("id", wd.id) juur.appendChild(wel) instanceOf=dok.createElement("instanceOf") wel.appendChild(instanceOf) subjectIndicatorRef=dok.createElement("subjectIndicatorRef") instanceOf.appendChild(subjectIndicatorRef) subjectIndicatorRef.setAttribute("xlink:type", "simple") subjectIndicatorRef.setAttribute("xlink:href", "http://cmap.coginst.uwf.edu/#concept") baseName=dok.createElement("baseName") wel.appendChild(baseName) baseNameString=dok.createElement("baseNameString") baseName.appendChild(baseNameString) baseNameStringData=dok.createTextNode(wd.title) baseNameString.appendChild(baseNameStringData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "description") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(wd.description) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "creator"); resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(wd.creator) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "modifier") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(wd.modifier) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "latexcode") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(wd.latexcode) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "backgroundcolorindex") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(wd.backgroundcolorindex)) resourceData.appendChild(resourceDataData) ind=self.wordids.index(wd.id) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "x") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.wordplaces[ind][0])) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "y") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(self.wordplaces[ind][1])) resourceData.appendChild(resourceDataData) if wd.hyperlinkurl: occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "hyperlinkurl") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(wd.hyperlinkurl)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "hyperlinktitle") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(wd.hyperlinktitle)) resourceData.appendChild(resourceDataData) if wd.attachmentfiledata: occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "attachmentfilename") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(wd.attachmentfilename)) resourceData.appendChild(resourceDataData) import base64 occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "attachmentfiledata") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(base64.encodestring(wd.attachmentfiledata)) resourceData.appendChild(resourceDataData) pass if wd.pilt: import base64 occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "picture") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(base64.encodestring(wd.pilt)) resourceData.appendChild(resourceDataData) for eg in self.objectValues("MapEdge"): association=dok.createElement("association") association.setAttribute("id", eg.id) juur.appendChild(association) instanceOf=dok.createElement("instanceOf") association.appendChild(instanceOf) topicRef=dok.createElement("topicRef") instanceOf.appendChild(topicRef) topicRef.setAttribute("xlink:type", "simple") topicRef.setAttribute("xlink:href", "#"+eg.id+"-topic") member=dok.createElement("member") association.appendChild(member) topicRef=dok.createElement("topicRef") member.appendChild(topicRef) topicRef.setAttribute("xlink:href", "#"+eg.startword) member=dok.createElement("member") association.appendChild(member) topicRef=dok.createElement("topicRef") member.appendChild(topicRef) topicRef.setAttribute("xlink:href", "#"+eg.endword) wel=dok.createElement('topic') wel.setAttribute("id", eg.id+"-topic") juur.appendChild(wel) baseName=dok.createElement("baseName") wel.appendChild(baseName) baseNameString=dok.createElement("baseNameString") baseName.appendChild(baseNameString) baseNameStringData=dok.createTextNode(eg.text_in_line) baseNameString.appendChild(baseNameStringData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "description") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(eg.description) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "creator"); resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(eg.creator) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "modifier") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(eg.modifier) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "latexcode") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(eg.latexcode) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "startarrow") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(eg.startarrow)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "endarrow") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(eg.endarrow)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "type") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(eg.type)) resourceData.appendChild(resourceDataData) occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "weight") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(str(eg.weight)) resourceData.appendChild(resourceDataData) if eg.pilt: import base64 occurence=dok.createElement("occurence") wel.appendChild(occurence) occurence.setAttribute("id", "picture") resourceData=dok.createElement("resourceData") occurence.appendChild(resourceData) resourceDataData=dok.createTextNode(base64.encodestring(eg.pilt)) resourceData.appendChild(resourceDataData) dump=Dump() PrettyPrint(dok, stream=dump) return dump.getdata() security.declareProtected(perm_view, 'XTMExportWWW') def XTMExportWWW(self, REQUEST): "Output to web" REQUEST.RESPONSE.setHeader("Content-type", "text/xml") return self.XTMExport() def XTMNewImportWWW(self, REQUEST, datafile, importfile=None): "For local import" m=self.addChildMap(); m.XTMImport(datafile.read()) return "ok" security.declareProtected(perm_edit, 'XTMImport') def XTMImport(self, data): "Import as XTM XML" dok=xml.dom.minidom.parseString(data) self.initializeVariables() self.wordcolortypes=[] mapprop=dok.getElementsByTagName("topic")[0] if mapprop.getAttribute("id")=="mapprop": bname=mapprop.getElementsByTagName("baseName")[0] bstr=bname.getElementsByTagName("baseNameString")[0] self.title=get_text(bstr) for oc in mapprop.getElementsByTagName("occurence"): try: rd=oc.getElementsByTagName("resourceData")[0] id=get_attr(oc, "id") txt=get_text(rd).strip() if id=="description": self.description=txt if id=="fontindex": self.fontindex=int(txt) if id=="menutypeowner": self.menutypeowner=int(txt) if id=="startingmap": self.startingmap=int(txt) if id=="allowedsubmaps": self.allowedsubmaps=int(txt) if id=="wordgraphicalpropertiesallowed": self.wordgraphicalpropertiesallowed=int(txt) if id=="equationsallowed": self.equationsallowed=int(txt) if id=="mappropertiesallowed": self.mappropertiesallowed=int(txt) if id=="visibletoothers": self.visibletoothers=int(txt) if id=="otherscanedit": self.otherscanedit=int(txt) if id=="canchangeproperties": self.canchangeproperties=int(txt) try: if id=="maxwords": self.maxwords=int(txt) except: pass if id=="maxedgetypes": self.maxedgetypes=int(txt) if id=="maxedgecount": self.maxedgecount=int(txt) if id=="declaredword": self.declaredwords.append(txt) if id=="declarededge": self.declarededges.append(txt) if id=="wordbackgroundcolordefaultindex": self.wordbackgroundcolordefaultindex=int(txt) if id=="wordcolortype": self.wordcolortypes.append(txt) except Exception, ex: pass # for t in dok.getElementsByTagName("topic"): for t in dok.childNodes[0].childNodes: if t.nodeName=="association": break if t.nodeName=="topic": if t.getAttribute("id")=="mapprop": continue bname=t.getElementsByTagName("baseName")[0] bstr=bname.getElementsByTagName("baseNameString")[0] wd=MapWord(get_text(bstr)) wd.id=str(t.getAttribute("id")) self._setObject(wd.id, wd) try: idnr=int(wd.id[2:]) if self.newwordidnr0: self.XTMImport(datafile.read()) REQUEST.RESPONSE.redirect('wmapindex.html') return self.restrictedTraverse('message_dialog_error.html')( self, REQUEST, title='No data', message='No XML data submitted', action='wordmaps_managing_page.html' ) security.declareProtected(perm_view, 'wmapindex_managing_handler') def wmapindex_managing_handler(self, REQUEST): "Buttons in bottom of page" if hasattr(REQUEST, 'addchildmap'): m=self.addChildMap(copying=1) REQUEST.RESPONSE.redirect(self.absolute_url()+'/'+m.id) return if hasattr(REQUEST, 'settings'): REQUEST.RESPONSE.redirect(self.absolute_url()+'/wordmaps_managing_page.html') return if hasattr(REQUEST, 'solveagain') and self.kas_opetaja(REQUEST): self.homeworkstatus=1 self.analyzeStatus=0 REQUEST.RESPONSE.redirect(self.fle_root().courses.absolute_url()+"/"+str(self.jooksva_kursuse_nr(REQUEST))+"/kodutood/manage_gradeAssignment") return if hasattr(REQUEST, 'assessment'): REQUEST.RESPONSE.redirect(self.absolute_url()+"/wordmaps_weight_page.html") return if hasattr(REQUEST, 'makeglobalmap'): self.getHeadMap().makeGlobalMap(REQUEST) REQUEST.RESPONSE.redirect(self.getHeadMap().globalMap.absolute_url()) return if hasattr(REQUEST, 'globalassesmentedges'): REQUEST.RESPONSE.redirect(self.absolute_url()+"/wordmaps_weight_page.html") return if hasattr(REQUEST, 'viewglobalmap'): REQUEST.RESPONSE.redirect(self.getHeadMap().globalMap.absolute_url()) return if hasattr(REQUEST, 'submittoteacher') and self.isOwner(REQUEST) and self.getHomeworkStatus()==1: return self.restrictedTraverse('message_dialog2.html')(self,REQUEST, title="Confirmation", message="Are you sure you want to submit wordmap? You cannot edit it after submitting", option1_name="cancel", option1_value="Cancel", option2_value="Submit", option2_name="confirmation", handler="wordmap_teacher_submit_handler") if hasattr(REQUEST, 'deletemap'): return self.restrictedTraverse('message_dialog2.html')(self,REQUEST, title="Confirmation", message="Are you sure you want to delete wordmap?", option1_name="cancel", option1_value="Cancel", option2_value="Delete", option2_name="confirmation", handler="wordmap_delete_handler") return "pole" security.declareProtected(perm_edit, 'wordmap_teacher_submit_handler') def wordmap_teacher_submit_handler(self, REQUEST): "deleting self" if hasattr(REQUEST, 'confirmation'): self.homeworkstatus=2 REQUEST.RESPONSE.redirect(self.fle_root().fle_users.absolute_url()+"/"+str(REQUEST.AUTHENTICATED_USER)+"/webtop/c"+self.jooksva_kursuse_nr(REQUEST)+"/portfolio") else: REQUEST.RESPONSE.redirect(self.absolute_url()) security.declareProtected(perm_edit, 'wordmap_teacher_submit_handler') def wordmap_delete_handler(self, REQUEST): "deleting self" if hasattr(REQUEST, 'confirmation'): self.aq_parent._delObject(self.id) if self.id=='globalMap': self.aq_parent.globalMap=None REQUEST.RESPONSE.redirect(self.find_course().wordmaps.absolute_url()+'/wordmaps_index.html') security.declareProtected(perm_view, 'index_html') def index_html(self, REQUEST): "Index file" if self.isOwner(REQUEST) or self.kas_opetaja(REQUEST) or self.visibletoothers: REQUEST.RESPONSE.redirect(self.absolute_url()+'/wmapindex.html') else: REQUEST.RESPONSE.redirect(self.find_course().wordmaps.absolute_url()+'/wordmaps_index.html') if __name__=="__main__": ""