def InitProjectLocation(projecturi): """ Initialises the folder structure on disk for a Project. If no project is provided, a new one is created. Otherwise the given project is essentially moved to the new location. Parameters: projecturi -- the filesystem location for the new Project. Currently, only file:// URIs are considered valid. Returns: the given Project, or the newly created Project object. """ if not projecturi: raise CreateProjectError(4) (scheme, domain,folder, params, query, fragment) = urlparse.urlparse(projecturi, "file", False) folder = PlatformUtils.url2pathname(folder) if scheme != "file": # raise "The URI scheme used is invalid." message raise CreateProjectError(5) filename = "project.jokosher" folder_name_template = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M") projectdir = os.path.join(folder, folder_name_template) try: project = Project.Project() except gst.PluginNotFoundError, e: Globals.debug("Missing Gstreamer plugin:", e) raise CreateProjectError(6, str(e))
def SetProperties(self): """ Sets basic Event properties like location, start, duration, etc. """ if self.file: if self.single_decode_bin: self.gnlsrc.remove(self.single_decode_bin) self.single_decode_bin.set_state(gst.STATE_NULL) Globals.debug("creating SingleDecodeBin") caps = gst.caps_from_string("audio/x-raw-int;audio/x-raw-float") f = PlatformUtils.pathname2url(self.GetAbsFile()) Globals.debug("file uri is:", f) self.single_decode_bin = SingleDecodeBin(caps=caps, uri=f) self.gnlsrc.add(self.single_decode_bin) Globals.debug("setting event properties:") propsDict = { "caps": caps, "start": long(self.start * gst.SECOND), "duration": long(self.duration * gst.SECOND), "media-start": long(self.offset * gst.SECOND), "media-duration": long(self.duration * gst.SECOND), "priority": 2, } for prop, value in propsDict.iteritems(): self.gnlsrc.set_property(prop, value) Globals.debug("\t", prop, "=", value)
def AddEventsFromList(self, start, fileList, copyFile=False, undoAction=None): """ Adds multiple files to an instrument one after another starting at the given start position. Parameters: start -- the offset time in seconds for the first event. fileList -- URIs to the Event files. copyfile -- True = copy the files to Project's audio directory. False = don't copy the files to the Project's audio directory. """ if not fileList: return if not undoAction: undoAction = self.project.NewAtomicUndoAction() for uri in fileList: # Parse the uri, and continue only if it is pointing to a local file (scheme, domain, file, params, query, fragment) = urlparse.urlparse(uri, "file", False) if scheme == "file": file = PlatformUtils.url2pathname(file) event = self.addEventFromFile(start, file, copyFile, _undoAction_=undoAction) else: event = self.addEventFromURL(start, uri, _undoAction_=undoAction) if event: event.MoveButDoNotOverlap(event.start) event.SetProperties() start += event.duration
def SetProperties(self): """ Sets basic Event properties like location, start, duration, etc. """ if self.file: if self.single_decode_bin: self.gnlsrc.remove(self.single_decode_bin) self.single_decode_bin.set_state(gst.STATE_NULL) Globals.debug("creating SingleDecodeBin") caps = gst.caps_from_string("audio/x-raw-int;audio/x-raw-float") f = PlatformUtils.pathname2url(self.GetAbsFile()) Globals.debug("file uri is:", f) self.single_decode_bin = SingleDecodeBin(caps=caps, uri=f) self.gnlsrc.add(self.single_decode_bin) Globals.debug("setting event properties:") propsDict = { "caps": caps, "start": long(self.start * gst.SECOND), "duration": long(self.duration * gst.SECOND), "media-start": long(self.offset * gst.SECOND), "media-duration": long(self.duration * gst.SECOND), "priority": 2 } for prop, value in propsDict.iteritems(): self.gnlsrc.set_property(prop, value) Globals.debug("\t", prop, "=", value)
def openDB(self): ''' Открыть БД и отобразить список пациентов ''' # Подчищаем старые данные self.closeDB() # Создаём новый список экспортных пациентов self.patLst = pr.ExportProbes() # Получаем имя базы в системной кодировке filename = pu.convert(QtGui.QFileDialog.getOpenFileName(self, u'Выберете файл базы данных', QtCore.QDir.homePath(), u"Базы данных (*.gdb *.GDB)")) if filename != '': # Подключаемся к базе global base try: base = db.DBAccess(filename) # Получаем список пациентов patients = base.getAllPatients() # Выводим его for id in patients.keys(): # Порядок полей: ID, ФИО, дата рождения, пол item = QtGui.QTreeWidgetItem([ str(id), patients[id][0], str(patients[id][1]), patients[id][2] ]) item.setCheckState(0, QtCore.Qt.Unchecked) self.ui.trePatients.addTopLevelItem(item) self.statusBar().showMessage(u'База данных загружена. Найдено ' + str(len(patients)) + u' пациентов.') except UnicodeDecodeError: self.statusBar().showMessage(u'Ошибка: слишком длинный путь до базы данных.')
def exportProbes(self): ''' Экспортирование съемов ''' # Запрашиваем дирректорию сохраниения съемов в системной кодировке dirName = pu.convert(QtGui.QFileDialog.getExistingDirectory(self, u'Выберете дирректорию сохранения')) if dirName != '': # Получаем список съемов, приготовленнных к экспорту exportLst = self.patLst.getAllProbes() # Для каждого пациента в списке экспортных съемов for patient in exportLst.keys(): # Для каждого съема конкретного пациента for date in exportLst[patient].keys(): # Получаем дату съема trueDate = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') # преобразуем её в строку особого вида dateStr = trueDate.strftime('%Y-%m-%d-%H-%M-%S') # Получаем Ф.И.О пациента в нужной кодировке patientName = pu.convert(base.getPatientName(patient)) # Суммируем полученные ранее переменные в полное имя файла fileName = os.path.join(dirName, patientName + '_' + dateStr + '.txt') # Открываем файл на запись tmpFile = open(fileName, "w") # Получаем матрицы съема lMatr, rMatr = base.getMatrix(patient, date) # Пишем матрицы по очереди в файл (Формат Новосибирска) for i in xrange(35): for j in xrange(24): tmpFile.write(str(lMatr[i][j])) tmpFile.write('; ') tmpFile.write('\n') for i in xrange(35): for j in xrange(24): tmpFile.write(str(rMatr[i][j])) tmpFile.write('; ') tmpFile.write('\n') # Закрываем файл tmpFile.close() # Информируем пользователя self.statusBar().showMessage(u'Экспорт прошёл успешно')
def OnOK(self, button): """ Tries to create and set a new Project with the user input name, author and location. If the process fails, a message is issued to the user stating the error. Parameters: button -- reserved for GTK callbacks, don't use it explicitly. """ name = self.name.get_text() if not name: name = _("New Project") author = self.author.get_text() if not author: author = _("Unknown Author") # CreateNewProject expects a URI folder = PlatformUtils.pathname2url(self.folder.get_filename()) # Save the selected folder as the default folder Globals.settings.general["projectfolder"] = folder Globals.settings.write() if not folder: folder = "~" try: project = ProjectManager.CreateNewProject(folder, name, author) except ProjectManager.CreateProjectError, e: if e.errno == 1: message = _("Could not initialize project.") elif e.errno == 2: message = _( "A file or folder with this name already exists. Please choose a different project name and try again." ) elif e.errno == 3: message = _("The file or folder location is write-protected.") elif e.errno == 4: message = _("Invalid name or author.") elif e.errno == 5: message = _( "The URI scheme given is either invalid or not supported") elif e.errno == 6: message = "%s %s" % ( _("Unable to load required Gstreamer plugin:"), e.message) # show the error dialog with the relavent error message dlg = gtk.MessageDialog( self.dlg, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("Unable to create project.\n\n%s") % message) dlg.run() dlg.destroy()
def OnOK(self, button): """ Tries to create and set a new Project with the user input name, author and location. If the process fails, a message is issued to the user stating the error. Parameters: button -- reserved for GTK callbacks, don't use it explicitly. """ name = self.name.get_text() if not name: name = _("New Project") author = self.author.get_text() if not author: author = _("Unknown Author") # CreateNewProject expects a URI folder = PlatformUtils.pathname2url(self.folder.get_filename()) # Save the selected folder as the default folder Globals.settings.general["projectfolder"] = folder Globals.settings.write() if not folder: folder = "~" try: project = ProjectManager.CreateNewProject(folder, name, author) except ProjectManager.CreateProjectError, e: if e.errno == 1: message = _("Could not initialize project.") elif e.errno == 2: message = _("A file or folder with this name already exists. Please choose a different project name and try again.") elif e.errno == 3: message = _("The file or folder location is write-protected.") elif e.errno == 4: message = _("Invalid name or author.") elif e.errno == 5: message = _("The URI scheme given is either invalid or not supported") elif e.errno == 6: message = "%s %s" % (_("Unable to load required Gstreamer plugin:"), e.message) # show the error dialog with the relavent error message dlg = gtk.MessageDialog(self.dlg, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("Unable to create project.\n\n%s") % message) dlg.run() dlg.destroy()
def CreateEventFromFile(self, event=None): """ Called when "Import Audio File..." is selected from the right-click context menu. Opens up a file chooser dialog to import an Event. Parameters: event -- reserved for GTK callbacks, don't use it explicitly. """ filenames, copyfile = self.mainview.ShowImportFileChooser() #filename will be None is the user cancelled the dialog if filenames: start = 0 if event: #if we we're called from a mouse click, use the mouse position as the start start = (self.mouseDownPos[0]/self.project.viewScale) + self.project.viewStart uris = [PlatformUtils.pathname2url(filename) for filename in filenames] self.instrument.AddEventsFromList(start, uris)
def CreateEventFromFile(self, event=None): """ Called when "Import Audio File..." is selected from the right-click context menu. Opens up a file chooser dialog to import an Event. Parameters: event -- reserved for GTK callbacks, don't use it explicitly. """ filenames, copyfile = self.mainview.ShowImportFileChooser() #filename will be None is the user cancelled the dialog if filenames: start = 0 if event: #if we we're called from a mouse click, use the mouse position as the start start = (self.mouseDownPos[0] / self.project.viewScale) + self.project.viewStart uris = [ PlatformUtils.pathname2url(filename) for filename in filenames ] self.instrument.AddEventsFromList(start, uris)
def LoadProjectFile(uri): """ Loads a Project from a saved file on disk. Parameters: uri -- the filesystem location of the Project file to load. Currently only file:// URIs are considered valid. Returns: the loaded Project object. """ (scheme, domain, projectfile, params, query, fragment) = urlparse.urlparse(uri, "file", False) if scheme != "file": # raise "The URI scheme used is invalid." message raise OpenProjectError(1, scheme) projectfile = PlatformUtils.url2pathname(projectfile) Globals.debug("Attempting to open:", projectfile) if not os.path.exists(projectfile): raise OpenProjectError(4, projectfile) try: try: gzipfile = gzip.GzipFile(projectfile, "r") doc = xml.parse(gzipfile) except IOError, e: if e.message == "Not a gzipped file": # starting from 0.10, we accept both gzipped xml and plain xml file_ = open(projectfile, "r") doc = xml.parse(file_) else: raise e except Exception, e: Globals.debug(e.__class__, e) # raise "This file doesn't unzip" message raise OpenProjectError(2, projectfile)
def InitProjectLocation(projecturi, name, project=None): """ Initialises the folder structure on disk for a Project. If no project is provided, a new one is created. Otherwise the given project is essentially moved to the new location. Parameters: projecturi -- the filesystem location for the new Project. Currently, only file:// URIs are considered valid. name -- the name of the Project. project -- the project to init, or None is a new project should be created. Returns: the given Project, or the newly created Project object. """ if name == "" or projecturi == "": raise CreateProjectError(4) (scheme, domain,folder, params, query, fragment) = urlparse.urlparse(projecturi, "file", False) folder = PlatformUtils.url2pathname(folder) if scheme != "file": # raise "The URI scheme used is invalid." message raise CreateProjectError(5) filename = name + ".jokosher" projectdir = os.path.join(folder, name) if not project: try: project = Project.Project() except gst.PluginNotFoundError, e: Globals.debug("Missing Gstreamer plugin:", e) raise CreateProjectError(6, str(e)) except Exception, e: Globals.debug("Could not initialize project object:", e) raise CreateProjectError(1)
def CreateNewProject(name, author, projecturi=None): """ Creates a new Project. Parameters: name -- the name of the Project. author - the name of the Project's author. projecturi -- the filesystem location for the new Project. Currently, only file:// URIs are considered valid. Returns: the newly created Project object. """ if not projecturi: projecturi = PlatformUtils.pathname2url(Globals.PROJECTS_PATH) project = InitProjectLocation(projecturi) project.name = name project.author = author project.SaveProjectFile(project.projectfile) return project
class Settings: """ Handles loading/saving settings from/to a file on disk. """ # the different settings in each config block general = { # increment each time there is an incompatible change with the config file "version": "1", "recentprojects": "value", "startupaction": "value", "projectfolder": "", "windowheight": 550, "windowwidth": 900, "addinstrumentwindowheight": 350, "addinstrumentwindowwidth": 300, "instrumenteffectwindowheight": 450, "instrumenteffectwindowwidth": 650, } recording = { "fileformat": "flacenc", "file_extension": "flac", "samplerate": "0", # zero means, autodetect sample rate (ie use any available) "audiosrc": "gconfaudiosrc", "device": "default" } # Overwrite with platform specific settings recording.update(PlatformUtils.GetRecordingDefaults()) playback = { "devicename": "default", "device": "default", "audiosink": "autoaudiosink" } # Overwrite with platform specific settings playback.update(PlatformUtils.GetPlaybackDefaults()) extensions = {"extensions_blacklist": ""} sections = { "General": general, "Recording": recording, "Playback": playback, "Extensions": extensions } #_____________________________________________________________________ def __init__(self): self.filename = os.path.join(JOKOSHER_CONFIG_HOME, "config") self.config = ConfigParser.ConfigParser() self.read() #_____________________________________________________________________ def read(self): """ Reads configuration settings from the config file and loads then into the Settings dictionaries. """ self.config.read(self.filename) for section in self.sections: if not self.config.has_section(section): self.config.add_section(section) for section, section_dict in self.sections.iteritems(): for key, value in self.config.items(section): if value == "None": value = None section_dict[key] = value #_____________________________________________________________________ def write(self): """ Writes configuration settings to the Settings config file. """ for section, section_dict in self.sections.iteritems(): for key, value in section_dict.iteritems(): self.config.set(section, key, value) file = open(self.filename, 'w') self.config.write(file) file.close()
def __init__(self, parent): """ Creates a new instance of NewProjectDialog. The dialog is used to create a new Project based on the user's input. Parameters: parent -- reference to the MainApp Jokosher window. """ self.parent = parent self.res = gtk.glade.XML(Globals.GLADE_PATH, "NewProjectDialog") self.signals = { "on_OK_clicked": self.OnOK, "on_Cancel_clicked": self.OnCancel, "on_editbutton_clicked": self.OnEdit, "on_Template_toggled": self.TemplateCheckboxToggled } self.res.signal_autoconnect(self.signals) self.dlg = self.res.get_widget("NewProjectDialog") self.sideimage = self.res.get_widget("sideimage") self.sideimage.set_from_file( os.path.join(Globals.IMAGE_PATH, "newproject.png")) self.name = self.res.get_widget("name") self.name.set_activates_default(True) self.author = self.res.get_widget("author") self.author.set_activates_default(True) self.template = ProjectTemplate.ProjectTemplate() self.template_checkbox = self.res.get_widget("template_checkbox") self.templatehbox = self.res.get_widget("template_hbox") self.templatehbox.set_sensitive(False) self.templatecombo = self.res.get_widget("template_combo") self.templatecombo.clear() self.templatemodel = gtk.ListStore(str) for files in self.template.LoadDictionaryOfInstrumentsFromTemplateFile( ).iterkeys(): self.templatemodel.append((files, )) self.templatecombo.set_model(self.templatemodel) text = gtk.CellRendererText() self.templatecombo.pack_start(text) self.templatecombo.add_attribute(text, "text", 0) self.templatecombo.set_active(0) # Default author to name of currently logged in user self.author.set_text(PlatformUtils.getFullName()) self.okbutton = self.res.get_widget("okButton") self.okbutton.set_flags(gtk.CAN_DEFAULT) self.okbutton.grab_default() self.folder = gtk.FileChooserButton(_("Select A Folder")) self.folder.set_local_only(True) self.folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) self.res.get_widget("table5").attach(self.folder, 1, 2, 1, 2) self.folder.show() # Set the default folder of 'folder' (a FileChooserButton) if os.path.exists(Globals.settings.general["projectfolder"]): self.folder.set_current_folder( Globals.settings.general["projectfolder"]) else: self.folder.set_current_folder(os.path.expanduser("~")) self.dlg.resize(350, 300) self.dlg.set_icon(self.parent.icon) self.dlg.set_transient_for(self.parent.window)
def __init__(self, instrument, file=None, id=None, filelabel=None): """ Creates a new instance of Event. Parameters: instrument -- Instrument associated with this Event. file -- the file this Event should play. id -- unique ID for this Event. If it's taken, a new one will be generated. filelabel -- label to print in error messages. It can be different from the file parameter. """ gobject.GObject.__init__(self) self.id = instrument.project.GenerateUniqueID( id) #check is id is already taken, then set it. self.start = 0.0 # Time in seconds at which the event begins self.duration = 0.0 # Duration in seconds of the event # The file this event should play (without escaped characters) # If you need characters escaped, please do self.file.replace(" ", "\ ") # but **do not** assign it to this variable. self.file = file if self.file and os.path.isabs(self.file) and \ PlatformUtils.samefile(instrument.project.audio_path, os.path.dirname(self.file)): # If the file is in the audio dir, just include the filename, not the absolute path Globals.debug("Event() given absolute file, should be relative:", self.file) self.file = os.path.basename(self.file) # levels_file is a filename only, no directory information for levels here. basename = os.path.basename(self.file or "Unknown") self.levels_file = "%s_%d%s" % (basename, self.id, self.LEVELS_FILE_EXTENSION) # the label is the filename to print in error messages # if it differs from the real filename (i.e its been copied into the project) if filelabel != None: self.filelabel = filelabel else: self.filelabel = file self.isSelected = False # True if the event is currently selected self.name = "New Event" # Name of this event self.selection = [ 0, 0 ] # List start and end of selection (for fades, etc) measured in seconds self.levels_list = LevelsList.LevelsList( ) # LevelsList class containing array of audio levels to be drawn for this event self.instrument = instrument # The parent instrument self.gnlsrc = None # The gstreamer gnlsource object. self.single_decode_bin = None # The gstreamer file decoder element. self.offset = 0.0 # Offset through the file in seconds self.isLoading = False # True if the event is currently loading level data self.isDownloading = False # True if the event is currently loading from a remote source. self.isRecording = False # True if the event is currently loading level data from a live recording self.loadingLength = 0 # The length of the file in seconds as its being rendered self.lastEnd = 0 # The last length of the loading file - used to minimise redraws self.loadingPipeline = None # The Gstreamer pipeline used to load the waveform self.bus = None # The bus to monitor messages on the loadingPipeline self.CreateFilesource() # a private dictionary containing the audio fade point times as keys # and the volume for that point between 0 and 1 as the values. # this is private, so if someone else wants a list of audio fade points # they must use the sorted list below. self.__fadePointsDict = {} # A list of control points for the audio fades # where each tuple is (<time in seconds>, <volume between 0 and 1>) # The list *must* be ordered by time-in-seconds, so when you update it from # the dictionary using dict.items(), be sure to sort it again. self.audioFadePoints = [] #Just like self.levels_list except with all the levels scaled according to the #points in self.audioFadePoints. self.fadeLevels = LevelsList.LevelsList()
def __init__(self, instrument, file=None, id=None, filelabel=None): """ Creates a new instance of Event. Parameters: instrument -- Instrument associated with this Event. file -- the file this Event should play. id -- unique ID for this Event. If it's taken, a new one will be generated. filelabel -- label to print in error messages. It can be different from the file parameter. """ gobject.GObject.__init__(self) self.id = instrument.project.GenerateUniqueID(id) # check is id is already taken, then set it. self.start = 0.0 # Time in seconds at which the event begins self.duration = 0.0 # Duration in seconds of the event # The file this event should play (without escaped characters) # If you need characters escaped, please do self.file.replace(" ", "\ ") # but **do not** assign it to this variable. self.file = file if ( self.file and os.path.isabs(self.file) and PlatformUtils.samefile(instrument.project.audio_path, os.path.dirname(self.file)) ): # If the file is in the audio dir, just include the filename, not the absolute path Globals.debug("Event() given absolute file, should be relative:", self.file) self.file = os.path.basename(self.file) # levels_file is a filename only, no directory information for levels here. basename = os.path.basename(self.file or "Unknown") self.levels_file = "%s_%d%s" % (basename, self.id, self.LEVELS_FILE_EXTENSION) # the label is the filename to print in error messages # if it differs from the real filename (i.e its been copied into the project) if filelabel != None: self.filelabel = filelabel else: self.filelabel = file self.isSelected = False # True if the event is currently selected self.name = "New Event" # Name of this event self.selection = [0, 0] # List start and end of selection (for fades, etc) measured in seconds self.levels_list = ( LevelsList.LevelsList() ) # LevelsList class containing array of audio levels to be drawn for this event self.instrument = instrument # The parent instrument self.gnlsrc = None # The gstreamer gnlsource object. self.single_decode_bin = None # The gstreamer file decoder element. self.offset = 0.0 # Offset through the file in seconds self.isLoading = False # True if the event is currently loading level data self.isDownloading = False # True if the event is currently loading from a remote source. self.isRecording = False # True if the event is currently loading level data from a live recording self.loadingLength = 0 # The length of the file in seconds as its being rendered self.lastEnd = 0 # The last length of the loading file - used to minimise redraws self.loadingPipeline = None # The Gstreamer pipeline used to load the waveform self.bus = None # The bus to monitor messages on the loadingPipeline self.CreateFilesource() # a private dictionary containing the audio fade point times as keys # and the volume for that point between 0 and 1 as the values. # this is private, so if someone else wants a list of audio fade points # they must use the sorted list below. self.__fadePointsDict = {} # A list of control points for the audio fades # where each tuple is (<time in seconds>, <volume between 0 and 1>) # The list *must* be ordered by time-in-seconds, so when you update it from # the dictionary using dict.items(), be sure to sort it again. self.audioFadePoints = [] # Just like self.levels_list except with all the levels scaled according to the # points in self.audioFadePoints. self.fadeLevels = LevelsList.LevelsList()
class Settings: """ Handles loading/saving settings from/to a file on disk. """ # the different settings in each config block general = { # increment each time there is an incompatible change with the config file "version": "1", "recentprojects": "", #deprecated "startupaction": "value", "projectfolder": "", "windowheight": 550, "windowwidth": 900, "addinstrumentwindowheight": 350, "addinstrumentwindowwidth": 300, "instrumenteffectwindowheight": 450, "instrumenteffectwindowwidth": 650, } recording = { "fileformat": "vorbisenc bitrate=%(bitrate)d ! oggmux", "file_extension": "ogg", "samplerate": "0", # zero means, autodetect sample rate (ie use any available) "bitrate": "131072", "audiosrc": "gconfaudiosrc", "device": "default" } # Overwrite with platform specific settings recording.update(PlatformUtils.GetRecordingDefaults()) playback = { "devicename": "default", "device": "default", "audiosink": "autoaudiosink" } # Overwrite with platform specific settings playback.update(PlatformUtils.GetPlaybackDefaults()) extensions = {"extensions_blacklist": ""} recentprojects = { #FIXME: replace with some kind of proper database since # we now plan to store all the projects created ever # (not just the last 8 used) "paths": "", "names": "", "create_times": "", "last_used_times": "", } sections = { "General": general, "Recording": recording, "Playback": playback, "Extensions": extensions, "RecentProjects": recentprojects, } #_____________________________________________________________________ def __init__(self): self.filename = os.path.join(JOKOSHER_CONFIG_HOME, "config") # Use RawConfigParser so that parameters in pipelines don't get processed self.config = ConfigParser.RawConfigParser() self.read() #_____________________________________________________________________ def read(self): """ Reads configuration settings from the config file and loads then into the Settings dictionaries. """ self.config.read(self.filename) for section in self.sections: if not self.config.has_section(section): self.config.add_section(section) for section, section_dict in self.sections.iteritems(): for key, value in self.config.items(section): if value == "None": value = None section_dict[key] = value #_____________________________________________________________________ def write(self): """ Writes configuration settings to the Settings config file. """ for section, section_dict in self.sections.iteritems(): for key, value in section_dict.iteritems(): self.config.set(section, key, value) file = open(self.filename, 'w') self.config.write(file) file.close()
def __init__(self, parent): """ Creates a new instance of NewProjectDialog. The dialog is used to create a new Project based on the user's input. Parameters: parent -- reference to the MainApp Jokosher window. """ self.parent = parent self.res = gtk.glade.XML(Globals.GLADE_PATH, "NewProjectDialog") self.signals = { "on_OK_clicked" : self.OnOK, "on_Cancel_clicked" : self.OnCancel, "on_editbutton_clicked" : self.OnEdit, "on_Template_toggled" : self.TemplateCheckboxToggled } self.res.signal_autoconnect(self.signals) self.dlg = self.res.get_widget("NewProjectDialog") self.sideimage = self.res.get_widget("sideimage") self.sideimage.set_from_file(os.path.join(Globals.IMAGE_PATH, "newproject.png")) self.name = self.res.get_widget("name") self.name.set_activates_default(True) self.author = self.res.get_widget("author") self.author.set_activates_default(True) self.template = ProjectTemplate.ProjectTemplate() self.template_checkbox = self.res.get_widget("template_checkbox") self.templatehbox = self.res.get_widget("template_hbox") self.templatehbox.set_sensitive(False) self.templatecombo = self.res.get_widget("template_combo") self.templatecombo.clear() self.templatemodel = gtk.ListStore(str) for files in self.template.LoadDictionaryOfInstrumentsFromTemplateFile().iterkeys(): self.templatemodel.append((files,)) self.templatecombo.set_model(self.templatemodel) text = gtk.CellRendererText() self.templatecombo.pack_start(text) self.templatecombo.add_attribute(text, "text", 0) self.templatecombo.set_active(0) # Default author to name of currently logged in user self.author.set_text(PlatformUtils.getFullName()) self.okbutton = self.res.get_widget("okButton") self.okbutton.set_flags(gtk.CAN_DEFAULT) self.okbutton.grab_default() self.folder = gtk.FileChooserButton(_("Select A Folder")) self.folder.set_local_only(True) self.folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) self.res.get_widget("table5").attach(self.folder, 1, 2, 1, 2) self.folder.show() # Set the default folder of 'folder' (a FileChooserButton) if os.path.exists(Globals.settings.general["projectfolder"]): self.folder.set_current_folder(Globals.settings.general["projectfolder"]) else: self.folder.set_current_folder(os.path.expanduser("~")) self.dlg.resize(350, 300) self.dlg.set_icon(self.parent.icon) self.dlg.set_transient_for(self.parent.window)
except OSError, e: Globals.debug("Cannot remove project. Have the permissions been changed, or other directories created inside the project folder?:\n\t%s" % main_dir) #_____________________________________________________________________ def ImportProject(project_uri): try: old_project = LoadProjectFile(project_uri) except OpenProjectError, e: raise all_files = old_project.GetAudioAndLevelsFilenames(include_deleted=True) abs_audio_files, rel_audio_files, levels_files = all_files try: new_project = InitProjectLocation(PlatformUtils.pathname2url(Globals.PROJECTS_PATH)) except CreateProjectError, e: return None delete_on_fail_list = [] try: for audio_filename in rel_audio_files: src = gio.File(path=old_project.audio_path).get_child(audio_filename) dst = gio.File(path=new_project.audio_path).get_child(audio_filename) src.copy(dst) delete_on_fail_list.append(dst.get_uri()) Globals.debug("Copy:\n\t" + src.get_uri() + "\n\t" + dst.get_uri())