Source

wxPython / samples / ide / activegrid / tool / UICommon.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
#----------------------------------------------------------------------------
# Name:         UICommon.py
# Purpose:      Shared UI stuff
#
# Author:       Matt Fryer, Morgan Hua
#
# Created:      3/10/05
# CVS-ID:       $Id: UICommon.py 38852 2006-04-20 06:26:03Z RD $
# Copyright:    (c) 2005-2006 ActiveGrid, Inc.
# License:      wxWindows License
#----------------------------------------------------------------------------

import os
import os.path
import wx
import string
import ProjectEditor
import activegrid.util.appdirs as appdirs
import activegrid.util.fileutils as fileutils
import activegrid.util.strutils as strutils
import activegrid.util.sysutils as sysutils
import activegrid.util.xmlutils as xmlutils
_ = wx.GetTranslation

def CreateDirectoryControl( parent, fileLabel=_("File Name:"), dirLabel=_("Directory:"), fileExtension="*", startingName="", startingDirectory=None, choiceDirs=None, appDirDefaultStartDir=False, returnAll=False, useDirDialog=False):

    if not choiceDirs:
        choiceDirs = []
        projectDirs = []

        if appDirDefaultStartDir:
            appDirectory = wx.ConfigBase_Get().Read(ProjectEditor.PROJECT_DIRECTORY_KEY, ProjectEditor.NEW_PROJECT_DIRECTORY_DEFAULT)
        else:
            appDirectory = wx.ConfigBase_Get().Read(ProjectEditor.PROJECT_DIRECTORY_KEY)
        if appDirectory:
            choiceDirs.append(appDirectory)
            if appDirDefaultStartDir and not startingDirectory:
                startingDirectory = appDirectory

        projectService = wx.GetApp().GetService(ProjectEditor.ProjectService)
        if projectService:
            curProjectDoc = projectService.GetCurrentProject()
            if curProjectDoc:
                homeDir = curProjectDoc.GetAppDocMgr().homeDir
                if homeDir and (homeDir not in choiceDirs):
                    choiceDirs.append(homeDir)
                if not startingDirectory:
                    startingDirectory = homeDir
                    
            for projectDoc in projectService.GetOpenProjects():
                if projectDoc == curProjectDoc:
                    continue
                homeDir = projectDoc.GetAppDocMgr().homeDir
                if homeDir and (homeDir not in projectDirs):
                    projectDirs.append(homeDir)
                projectDirs.sort(CaseInsensitiveCompare)
            for projectDir in projectDirs:
                if projectDir not in choiceDirs:
                    choiceDirs.append(projectDir)

        if startingDirectory and (startingDirectory not in choiceDirs):
            choiceDirs.insert(0, startingDirectory)
            
        if os.getcwd() not in choiceDirs:
            choiceDirs.append(os.getcwd())                
        if appdirs.getSystemDir() not in choiceDirs:
            choiceDirs.append(appdirs.getSystemDir()) 

    if not startingDirectory:
        startingDirectory = os.getcwd()
        
    nameControl = wx.TextCtrl(parent, -1, startingName, size=(-1,-1))
    nameLabelText = wx.StaticText(parent, -1, fileLabel)
    dirLabelText = wx.StaticText(parent, -1, dirLabel)
    dirControl = wx.ComboBox(parent, -1, startingDirectory, size=(-1,-1), choices=choiceDirs)
    dirControl.SetToolTipString(startingDirectory)
    button = wx.Button(parent, -1, _("Browse..."))
    allControls = [nameControl, nameLabelText, dirLabelText, dirControl, button]
    
    def OnFindDirClick(event): 
        name = ""  
        nameCtrlValue = nameControl.GetValue()
        if nameCtrlValue:
            root, ext = os.path.splitext( nameCtrlValue )
            if ext == '.' + fileExtension:
                name = nameCtrlValue
            else:
                name = _("%s.%s") % (nameCtrlValue, fileExtension)
                
        if not useDirDialog:
            dlg = wx.FileDialog(parent, _("Choose a filename and directory"),
                       defaultDir = dirControl.GetValue().strip(),
                       defaultFile = name,
                       wildcard= "*.%s" % fileExtension,
                       style=wx.SAVE|wx.CHANGE_DIR)
        else:
            dlg = wx.DirDialog(wx.GetApp().GetTopWindow(),
                        _("Choose a directory:"),
                        defaultPath=dirControl.GetValue().strip(),
                        style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
            
        if dlg.ShowModal() != wx.ID_OK:
            dlg.Destroy()
            return
        path = dlg.GetPath()
        dlg.Destroy()
        
        if path:
            if not useDirDialog:
                dir, filename = os.path.split(path)
                if dirControl.FindString(dir) == wx.NOT_FOUND:
                    dirControl.Insert(dir, 0)
                dirControl.SetValue(dir)
                dirControl.SetToolTipString(dir)
                nameControl.SetValue(filename)
            else:
                dirControl.SetValue(path)
                dirControl.SetToolTipString(path)

    parent.Bind(wx.EVT_BUTTON, OnFindDirClick, button)
    
    def Validate(allowOverwriteOnPrompt=False, infoString='', validClassName=False, ignoreFileConflicts=False):
        projName = nameControl.GetValue().strip()
        if projName == "":
            wx.MessageBox(_("Please provide a %sfile name.") % infoString, _("Provide a File Name"))            
            return False
        if projName.find(' ') != -1:
            wx.MessageBox(_("Please provide a %sfile name that does not contains spaces.") % infoString, _("Spaces in File Name"))            
            return False
        if validClassName:
            if projName[0].isdigit():
                wx.MessageBox(_("File name cannot start with a number.  Please enter a different name."), _("Invalid File Name"))            
                return False
            if projName.endswith(".agp"):
                projName2 = projName[:-4]
            else:
                projName2 = projName
            if not projName2.replace("_", "a").isalnum():  # [a-zA-Z0-9_]  note '_' is allowed and ending '.agp'.
                wx.MessageBox(_("Name must be alphanumeric ('_' allowed).  Please enter a valid name."), _("Project Name"))
                return False

        dirName = dirControl.GetValue().strip()
        if dirName == "":
            wx.MessageBox(_("No directory.  Please provide a directory."), _("Provide a Directory"))            
            return False
        if os.sep == "\\" and dirName.find("/") != -1:
            wx.MessageBox(_("Wrong delimiter '/' found in directory path.  Use '%s' as delimiter.") % os.sep, _("Provide a Valid Directory"))            
            return False
        if not os.path.exists(dirName):
            wx.MessageBox(_("That %sdirectory does not exist.  Please choose an existing directory.") % infoString, _("Provide a Valid Directory"))            
            return False
        if not ignoreFileConflicts:
            filePath = os.path.join(dirName, MakeNameEndInExtension(projName, "." + fileExtension))
            if os.path.exists(filePath):
                if allowOverwriteOnPrompt:
                    res = wx.MessageBox(_("That %sfile already exists. Would you like to overwrite it.") % infoString, "File Exists", style=wx.YES_NO|wx.NO_DEFAULT)
                    return (res == wx.YES)  
                else:                
                    wx.MessageBox(_("That %sfile already exists. Please choose a different name.") % infoString, "File Exists")
                    return False

        return True    
    HALF_SPACE = 5
    flexGridSizer = wx.FlexGridSizer(cols = 3, vgap = HALF_SPACE, hgap = HALF_SPACE)
    flexGridSizer.AddGrowableCol(1,1)
    if not useDirDialog:
        flexGridSizer.Add(nameLabelText, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT)
        flexGridSizer.Add(nameControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        flexGridSizer.Add(button, flag=wx.ALIGN_RIGHT|wx.LEFT, border=HALF_SPACE)        
        flexGridSizer.Add(dirLabelText, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT)
        flexGridSizer.Add(dirControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0)
    else:
        flexGridSizer.Add(nameLabelText, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT)
        flexGridSizer.Add(nameControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0)
        flexGridSizer.Add(dirLabelText, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT)
        flexGridSizer.Add(dirControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        flexGridSizer.Add(button, flag=wx.ALIGN_RIGHT|wx.LEFT, border=HALF_SPACE)        
        
    if returnAll:
        return nameControl, dirControl, flexGridSizer, Validate, allControls
    else:
        return nameControl, dirControl, flexGridSizer, Validate


def CreateDirectoryOnlyControl( parent, dirLabel=_("Location:"), startingDirectory=None, choiceDirs=None, appDirDefaultStartDir=False):

    if not choiceDirs:
        choiceDirs = []
        projectDirs = []

        if appDirDefaultStartDir:
            appDirectory = wx.ConfigBase_Get().Read(ProjectEditor.PROJECT_DIRECTORY_KEY, ProjectEditor.NEW_PROJECT_DIRECTORY_DEFAULT)
        else:
            appDirectory = wx.ConfigBase_Get().Read(ProjectEditor.PROJECT_DIRECTORY_KEY)
        if appDirectory:
            choiceDirs.append(appDirectory)
            if appDirDefaultStartDir and not startingDirectory:
                startingDirectory = appDirectory

        projectService = wx.GetApp().GetService(ProjectEditor.ProjectService)
        if projectService:
            curProjectDoc = projectService.GetCurrentProject()
            if curProjectDoc:
                homeDir = curProjectDoc.GetAppDocMgr().homeDir
                if homeDir and (homeDir not in choiceDirs):
                    choiceDirs.append(homeDir)
                if not startingDirectory:
                    startingDirectory = homeDir
                    
            for projectDoc in projectService.GetOpenProjects():
                if projectDoc == curProjectDoc:
                    continue
                homeDir = projectDoc.GetAppDocMgr().homeDir
                if homeDir and (homeDir not in projectDirs):
                    projectDirs.append(homeDir)
                projectDirs.sort(CaseInsensitiveCompare)
            for projectDir in projectDirs:
                if projectDir not in choiceDirs:
                    choiceDirs.append(projectDir)

        if startingDirectory and (startingDirectory not in choiceDirs):
            choiceDirs.insert(0, startingDirectory)

        if os.getcwd() not in choiceDirs:
            choiceDirs.append(os.getcwd())                
        if appdirs.getSystemDir() not in choiceDirs:
            choiceDirs.append(appdirs.getSystemDir())                
            

    if not startingDirectory:
        startingDirectory = os.getcwd()
            
    dirLabelText = wx.StaticText(parent, -1, dirLabel)
    dirControl = wx.ComboBox(parent, -1, startingDirectory, size=(-1,-1), choices=choiceDirs)
    dirControl.SetToolTipString(startingDirectory)
    button = wx.Button(parent, -1, _("Browse..."))
    
    def OnFindDirClick(event): 
            dlg = wx.DirDialog(wx.GetApp().GetTopWindow(),
                                _("Choose a directory:"),
                                defaultPath=dirControl.GetValue().strip(),
                                style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
            dlg.CenterOnParent()
            if dlg.ShowModal() == wx.ID_OK:
                dir = dlg.GetPath()
                if dirControl.FindString(dir) == wx.NOT_FOUND:
                    dirControl.Insert(dir, 0)
                dirControl.SetValue(dir)
                dirControl.SetToolTipString(dir)
            dlg.Destroy()            

    parent.Bind(wx.EVT_BUTTON, OnFindDirClick, button)
    
    def Validate(allowOverwriteOnPrompt=False):
        dirName = dirControl.GetValue().strip()
        if dirName == "":
            wx.MessageBox(_("Please provide a directory."), _("Provide a Directory"))            
            return False
        if os.sep == "\\" and dirName.find("/") != -1:
            wx.MessageBox(_("Wrong delimiter '/' found in directory path.  Use '%s' as delimiter.") % os.sep, _("Provide a Valid Directory"))            
            return False
        if not os.path.exists(dirName):
            wx.MessageBox(_("That directory does not exist. Please choose an existing directory."), _("Provide a Valid Directory"))            
            return False
        return True  
          
    HALF_SPACE = 5
    flexGridSizer = wx.FlexGridSizer(cols = 3, vgap = HALF_SPACE, hgap = HALF_SPACE)
    flexGridSizer.AddGrowableCol(1,1)
    flexGridSizer.Add(dirLabelText, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.RIGHT, border=HALF_SPACE)
    flexGridSizer.Add(dirControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border=HALF_SPACE)
    flexGridSizer.Add(button, flag=wx.ALIGN_RIGHT|wx.LEFT, border=HALF_SPACE)
        
    return dirControl, flexGridSizer, Validate


def CreateNameOnlyControl( parent, fileLabel, startingName="", startingDirectoryControl=None):

    fileLabelText = wx.StaticText(parent, -1, fileLabel)
    nameControl = wx.TextCtrl(parent, -1, startingName, size=(-1,-1))
        
    def Validate(allowOverwriteOnPrompt=False, validClassName=False):
        projName = nameControl.GetValue().strip()
        if projName == "":
            wx.MessageBox(_("Blank name.  Please enter a valid name."), _("Project Name"))            
            return False
        if projName.find(' ') != -1:
            wx.MessageBox(_("Spaces in name.  Name cannot have spaces."), _("Project Name"))            
            return False
        if validClassName:
            if projName[0].isdigit():
                wx.MessageBox(_("Name cannot start with a number.  Please enter a valid name."), _("Project Name"))            
                return False
            if projName.endswith(".agp"):
                projName2 = projName[:-4]
            else:
                projName2 = projName
            if not projName2.replace("_", "a").isalnum():  # [a-zA-Z0-9_]  note '_' is allowed and ending '.agp'.
                wx.MessageBox(_("Name must be alphanumeric ('_' allowed).  Please enter a valid name."), _("Project Name"))
                return False
        path = os.path.join(startingDirectoryControl.GetValue().strip(), projName)
        if os.path.exists(path):
            if os.path.isdir(path):
                message = _("Project '%s' already exists.  Would you like to overwrite the contents of the project?") % projName
            else: # os.path.isfile(path):
                message = _("'%s' already exists as a file.  Would you like to replace it with the project?") % nameControl.GetValue().strip()
                    
            yesNoMsg = wx.MessageDialog(wx.GetApp().GetTopWindow(),
                          message,
                          _("Project Directory Exists"),
                          wx.YES_NO|wx.ICON_QUESTION
                          )
            yesNoMsg.CenterOnParent()
            status = yesNoMsg.ShowModal()
            yesNoMsg.Destroy()
            if status == wx.ID_NO:
                return False
        return True  
          
    HALF_SPACE = 5
    flexGridSizer = wx.FlexGridSizer(cols = 2, vgap = HALF_SPACE, hgap = HALF_SPACE)
    flexGridSizer.AddGrowableCol(1,1)
    flexGridSizer.Add(fileLabelText, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.TOP|wx.RIGHT, border=HALF_SPACE)
    flexGridSizer.Add(nameControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border=HALF_SPACE)
        
    return nameControl, flexGridSizer, Validate
    

def ValidateName(name, ext=None, hint="name"):
    """ Returns an error string if there is something wrong with the name.
        Otherwise it returns None
    """
    if name == "":
        return _("Blank %s.  Please enter a valid %s.") % (hint, hint)

    if name.find(' ') != -1:
        return _("Spaces in %s.  %s cannot have spaces.") % (hint, hint.title())

    if name[0].isdigit():
        return _("%s cannot start with a number.  Please enter a valid %s.") % (hint.title(), hint)

    if ext and name.endswith(ext):  # strip extension if provided
        lenExt = len(ext)
        name = name[:-lenExt]
        
    if not name.replace("_", "a").isalnum():  # [a-zA-Z0-9_]  note '_' is allowed and ext ending.
        return _("%s must be alphanumeric ('_' allowed).  Please enter a valid %s.") % (hint.title(), hint)

    return None


def GetCurrentProject():
    projectDocument = None
    projectService = wx.GetApp().GetService(ProjectEditor.ProjectService)
    if projectService:
        projectDocument = projectService.GetCurrentProject()
    return projectDocument

def AddFilesToCurrentProject(paths, folderPath=None, types=None, names=None, save=False):
    projectService = wx.GetApp().GetService(ProjectEditor.ProjectService)
    if projectService:
        projectDocument = projectService.GetCurrentProject()
        if projectDocument:
            files = projectDocument.GetFiles()
            for path in paths:
                if path in files:
                    paths.remove(path)
            if paths:
                projectDocument.GetCommandProcessor().Submit(ProjectEditor.ProjectAddFilesCommand(projectDocument, paths, folderPath=folderPath, types=types, names=names))
                if save:
                    projectDocument.OnSaveDocument(projectDocument.GetFilename())

def AddFilesToProject(projectDocument, paths, types=None, names=None, save=False):
    if projectDocument:
        files = projectDocument.GetFiles()
        for path in paths:
            if path in files:
                paths.remove(path)
        if paths:
            projectDocument.GetCommandProcessor().Submit(ProjectEditor.ProjectAddFilesCommand(projectDocument, paths, types=types, names=names))
            if save:
                projectDocument.OnSaveDocument(projectDocument.GetFilename())


def MakeNameEndInExtension(name, extension):
    if not name:
        return name
    root, ext = os.path.splitext(name)
    if ext == extension:
        return name
    else:
        return name + extension
 

def GetPythonExecPath():
    pythonExecPath = wx.ConfigBase_Get().Read("ActiveGridPythonLocation")
    if not pythonExecPath:
        pythonExecPath = sysutils.pythonExecPath
    return pythonExecPath
    

def GetPHPExecPath():
    PHPExecPath = wx.ConfigBase_Get().Read("ActiveGridPHPLocation")
    return PHPExecPath


def GetPHPINIPath():
    PHPINIPath = wx.ConfigBase_Get().Read("ActiveGridPHPINILocation")
    return PHPINIPath


def _DoRemoveRecursive(path, skipFile=None, skipped=False):
    if path == skipFile:
        skipped = True
    elif os.path.isdir(path):
        for file in os.listdir(path):
            file_or_dir = os.path.join(path,file)
            if skipFile == file_or_dir:
                skipped = True
            elif os.path.isdir(file_or_dir) and not os.path.islink(file_or_dir):
                if _DoRemoveRecursive(file_or_dir, skipFile): # it's a directory recursive call to function again
                    skipped = True
            else:
                os.remove(file_or_dir) # it's a file, delete it
        if not skipped:
            os.rmdir(path) # delete the directory here
    else:
        os.remove(path)
        
    return skipped


def RemoveRecursive(path, skipFile=None):
    _DoRemoveRecursive(path, skipFile)    


def CaseInsensitiveCompare(s1, s2):
    """ Method used by sort() to sort values in case insensitive order """
    return strutils.caseInsensitiveCompare(s1, s2)


def GetAnnotation(model, elementName):
    """ Get an object's annotation used for tooltips """
    if hasattr(model, "_complexType"):
        ct = model._complexType
    elif hasattr(model, "__xsdcomplextype__"):
        ct = model.__xsdcomplextype__
    else:
        ct = None
            
    if ct:
        el = ct.findElement(elementName)
        if el and el.annotation:
            return el.annotation
            
    return ""


def GetDisplayName(doc, name):
    if name:
        appDocMgr = doc.GetAppDocMgr()
        if appDocMgr:
            name = appDocMgr.toDisplayTypeName(name)
        else:
            namespace, name = xmlutils.splitType(name)
            if namespace and hasattr(doc.GetModel(), "getXmlNamespaces"):
                for xmlkey, xmlval in doc.GetModel().getXmlNamespaces().iteritems():
                    if xmlval == namespace:
                        name = "%s:%s" % (xmlkey, name)
                        break                    
    
        if name:
            import activegrid.model.schema as schemalib
            baseTypeName = schemalib.mapXsdType(name)
            if baseTypeName:
                name = baseTypeName

    return name


def GetInternalName(doc, name):
    if name:
        appDocMgr = doc.GetAppDocMgr()
        if appDocMgr:
            name = appDocMgr.toInternalTypeName(name)
        else:
            namespace, name = xmlutils.splitType(name)
            if namespace and hasattr(doc.GetModel(), "getXmlNamespaces"):
                for xmlkey, xmlval in doc.GetModel().getXmlNamespaces().iteritems():
                    if xmlkey == namespace:
                        name = "%s:%s" % (xmlval, name)
                        break  
                                          
        import activegrid.model.schema as schemalib
        name = schemalib.mapAGType(name)

    return name


#----------------------------------------------------------------------------
# Methods for finding application level info
#----------------------------------------------------------------------------

def GetProjectForDoc(doc):
    """ Given a document find which project it belongs to.
        Tries to intelligently resolve conflicts if it is in more than one open project.
    """
    projectService = wx.GetApp().GetService(ProjectEditor.ProjectService)

    projectDoc = projectService.FindProjectFromMapping(doc)
    if projectDoc:
        return projectDoc

    projectDoc = projectService.GetCurrentProject()
    if not projectDoc:
        return None
    if projectDoc.IsFileInProject(doc.GetFilename()):
        return projectDoc

    projects = []
    openDocs = wx.GetApp().GetDocumentManager().GetDocuments()
    for openDoc in openDocs:
        if openDoc == projectDoc:
            continue
        if(isinstance(openDoc, ProjectEditor.ProjectDocument)):
            if openDoc.IsFileInProject(doc.GetFilename()):
                projects.append(openDoc)
                
    if projects:
        if len(projects) == 1:
            return projects[0]
        else:
            choices = [os.path.basename(project.GetFilename()) for project in projects]
            dlg = wx.SingleChoiceDialog(wx.GetApp().GetTopWindow(), _("'%s' found in more than one project.\nWhich project should be used for this operation?") % os.path.basename(doc.GetFilename()), _("Select Project"), choices, wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CENTRE)
            dlg.CenterOnParent()
            projectDoc = None
            if dlg.ShowModal() == wx.ID_OK:
                i = dlg.GetSelection()
                projectDoc = projects[i]
            dlg.Destroy()
            return projectDoc

    return None


def GetAppInfoForDoc(doc):
    """ Get the AppInfo for a given document """
    projectDoc = GetProjectForDoc(doc)
    if projectDoc:
        return projectDoc.GetAppInfo()
    return None


def GetAppDocMgrForDoc(doc):
    """ Get the AppDocMgr for a given document """
    projectDoc = GetProjectForDoc(doc)
    if projectDoc:
        return projectDoc.GetModel()
    return None


def GetAppInfoLanguage(doc=None):
    from activegrid.server.projectmodel import LANGUAGE_DEFAULT
    
    if doc:
        language = doc.GetAppInfo().language
    else:
        language = None
        
    if not language:
        config = wx.ConfigBase_Get()
        language = config.Read(ProjectEditor.APP_LAST_LANGUAGE, LANGUAGE_DEFAULT)
        
        if doc:
            doc.GetAppInfo().language = language  # once it is selected, it must be set.
        
    return language

def AddWsdlAgToProjectFromWsdlRegistration(wsdlRegistration):
    """Add wsdl ag for registry entry."""

    wsdlPath = wsdlRegistration.path
    rootPath = None
    serviceRefName = wsdlRegistration.name
    
    agwsDoc = _InitWsdlAg(wsdlPath, rootPath, serviceRefName)

    if (agwsDoc == None):
        return

    serviceRef = agwsDoc.GetModel()    
    
    serviceRef.serviceType = wsdlRegistration.type

    import activegrid.server.deployment as deployment

    if (serviceRef.serviceType == deployment.SERVICE_LOCAL):
        serviceRef.localService = deployment.LocalService(
            wsdlRegistration.codeFile)
        
    elif (serviceRef.serviceType == deployment.SERVICE_DATABASE):
        serviceRef.databaseService = deployment.DatabaseService(
            wsdlRegistration.datasourceName)
        
    elif (serviceRef.serviceType == deployment.SERVICE_SOAP):
        pass
    
    elif (serviceRef.serviceType == deployment.SERVICE_RSS):
        serviceRef.rssService = deployment.RssService(wsdlRegistration.feedUrl)
        
    elif (serviceRef.serviceType == deployment.SERVICE_REST):
        serviceRef.restService = deployment.RestService(
            wsdlRegistration.baseUrl)
    else:
        raise AssertionError("Unknown service type")

    _AddToProject(agwsDoc, addWsdl=True)
    

def AddWsdlAgToProject(wsdlPath, rootPath=fileutils.AG_SYSTEM_STATIC_VAR_REF,
                       serviceRefName=None, className=None, serviceType=None,
                       dataSourceName=None):
    """
       wsdlPath: path to wsdl from rootPath. If wsdlPath is absolute, rootPath
       is ignored. rootPath is also ignored when rootPath is set to None. 
       rootPath: defaults to ${AG_SYSTEM_STATIC}.
       serviceRefName: If None, it will be set to the wsdl file name without
       the .wsdl file extension.
       className: if not None, will be used for the the wsdlag's ClassName.
       serviceType: defaults to local.
       dataSourceName: if serviceType is deployment.DATABASE, the ds must be
       provided.
    """
    import WsdlAgEditor
    import XFormWizard
    import activegrid.model.basedocmgr as basedocmgr
    import activegrid.server.deployment as deployment

    if (serviceType == None):
        serviceType = deployment.SERVICE_LOCAL


    agwsDoc = _InitWsdlAg(wsdlPath, rootPath, serviceRefName)

    if (agwsDoc == None):
        return

    serviceRef = agwsDoc.GetModel()    
    
    serviceRef.serviceType = serviceType

    if (serviceType == deployment.SERVICE_DATABASE and dataSourceName != None):
        serviceRef.databaseService = deployment.DatabaseService(dataSourceName)
    else:
        serviceRef.localService = deployment.LocalService(className=className)

    _AddToProject(agwsDoc)
        

def _AddToProject(agwsDoc, addWsdl=False):
    import activegrid.model.basedocmgr as basedocmgr    
    projectDoc = GetCurrentProject()
    agwsDoc.OnSaveDocument(agwsDoc.GetFilename())

    files = [agwsDoc.fileName]
    types = [basedocmgr.FILE_TYPE_SERVICE]
    names = [agwsDoc.GetModel().name]
    if (addWsdl):
        m = agwsDoc.GetModel()        
        wsdlName = os.path.splitext(os.path.basename(m.filePath))[0]
        appDocMgr = projectDoc.GetAppDocMgr()
        if (appDocMgr.findService(wsdlName) == None):
            m = agwsDoc.GetModel()            
            files.append(m.filePath)
            types.append(None)
            names.append(wsdlName)
    
    ProjectEditor.ProjectAddFilesCommand(projectDoc, files, types=types,
                                         names=names).Do()
    

def _InitWsdlAg(wsdlPath, rootPath=fileutils.AG_SYSTEM_STATIC_VAR_REF,
                serviceRefName=None):

    projectDoc = GetCurrentProject()
    appDocMgr = projectDoc.GetAppDocMgr()

    if (serviceRefName == None):
        serviceRefName = os.path.splitext(os.path.basename(wsdlPath))[0]
    
    if (appDocMgr.findServiceRef(serviceRefName) != None):
        return None

    import WsdlAgEditor
    import XFormWizard
    import activegrid.server.deployment as deployment

    template = XFormWizard.GetTemplate(WsdlAgEditor.WsdlAgDocument)
    ext = template.GetDefaultExtension()
    fullPath = os.path.join(appDocMgr.homeDir, serviceRefName + ext)

    agwsDoc = template.CreateDocument(
        fullPath, flags=(wx.lib.docview.DOC_NO_VIEW|wx.lib.docview.DOC_NEW|
                         wx.lib.docview.DOC_OPEN_ONCE))
    
    serviceRef = agwsDoc.GetModel()
    serviceRef.name = serviceRefName

    if (rootPath == None or os.path.isabs(wsdlPath)):
        serviceRef.filePath = wsdlPath
    else:
        # make sure to use forward slashes for the path to the .wsdl
        wsdlPath = wsdlPath.replace("\\", "/")
        
        if not wsdlPath.startswith("/"):
            wsdlPath = "/%s" % wsdlPath
        serviceRef.filePath = "%s%s" % (rootPath, wsdlPath)

    agwsDoc.fileName = fullPath        

    return agwsDoc


def GetSchemaName(schema):
    return os.path.basename(schema.fileName)


class AGChoice(wx.Choice):
    """Extension to wx.Choice that fixes linux bug where first item of choices
    passed into ctor would be visible, but not selected."""
    def __init__(self, parent, id, choices=[]):
        super(AGChoice, self).__init__(parent=parent, id=id)
        self.AppendItems(choices)