def __rename_item_list(self, event): """After pre-renaming checks are completed, rename the list of items.""" # calculate refresh settings count = len(main.toRename) count = count / 25 + 1 if count > int(app.prefs.get('renRefreshMin')): count = int(app.prefs.get('renRefreshMin')) # define here for faster processing def exists(item): return os.path.exists(item) def join(a, b, c): return unicode(os.path.join(a, b, c)) warn = False if event != u'undo': path = main.picker.params.root # renaming operation: i = 0 for original, renamed in main.toRename: if warn != 'duplicate_name' and self.__compare(renamed, original) and\ exists(renamed[0]): # set item as bad main.toRename[i][1][1] = None self._set_display(i) main.set_status_msg(_(u"Duplicate name"), u'warn') msg = _(u"This name already exists:\n%s") % renamed[0]\ + _(u"\n\nI can make a sub-folder called 't_e_m_p' and do the renaming operation there.\nYou can then move everything back.\n\nGo ahead and do this?") title = _(u"Duplicate name") if utils.make_yesno_dlg(msg, title): warn = 'duplicate_name' else: error = True break # set correct path if in dupe error mode if warn == 'duplicate_name': if not path.endswith(os.sep): path = path + os.sep renamed[0] = renamed[0].replace(path, u'') renamed[0] = join(path, u't_e_m_p', renamed[0]) # the actual renaimg op error = self._rename_item(i, original, renamed, count) if error: break i += 1 app.debug_print("%s\n%s\n" % (original[0], renamed[0])) main.set_status_msg(_(u"Writing undo files, please wait ..."), u'wait') # write out undo files backup = main.toRename[:i] if app.recursiveFolderOn: backup.reverse() for original, renamed in backup: self.originalFile.write(original[0] + u'\n') self.renamedFile.write(renamed[0] + u'\n') return error, i
def __read_file(self, path): """ Process file and return preferences dictionary. """ prefFile = self.__open_pref_file(path, 'r') prefFile.seek(0) version = prefFile.readline().strip()[8:] # TODO preferences from a prior version if version != app.prefsVersion: app.debug_print("Old version found") prefFile.seek(0) prefs = {} for line in prefFile: if line.find('=') > 0: line = line.replace(u'\n', '') split = line.split('=') try: prefs[split[0]] = int(split[1]) except KeyError: pass except ValueError: prefs[split[0]] = unicode(split[1]) pass prefFile.close() return prefs
def __init__(self, parent, MainWindow): app.debug_print("loading picker core") self.CommonSearches = ( ("", ""), (_(u"- audio"), u"\.(mp3|wav|ogg|flac|wma|aiff|aac|m3u|mid|ra|ram|m4a)$"), (_(u"- image"), u"\.(bmp|jpg|jpeg|png|svg|ico|tif|tiff|gif|psd|ai|thm|nef)$"), (_(u"- video"), u"\.(avi|mpg|mpeg|mpe|mp4|m4e|wmv|divx|flc|mov|ogm)$"), (_(u"- office related"), u"\.(txt|csv|rtf|doc|otf|xls|pps|ppt)$"), (_(u"- web related"), u"\.(htm|html|php|css|js|asp|cgi|swf)$"), (_(u"- programming"), u"\.(py|pyc|php|pl|h|c|cpp|cxx|jar|java|js|tcl)$"), (_(u"- compressed"), u"\.(zip|tar|7z|ace|gz|tgz|rar|r\d{1,3}|cab|bz2)$"), (_(u"- an extension"), u"^.+\..+$"), (_(u"- only an extension"), u"(^|\\\|/)\."), ) self.CustomSearches = {} global main main = MainWindow self.view = wxPickerView.Panel(self, parent, MainWindow) self.params = Parameters(self.view) self.joinedItems = []
def __init__(self, parent, MainWindow): app.debug_print("loading renamer core") global main main = MainWindow self.operations = [] # operations stack self.view = wxRenamerView.Panel(self, parent, main) self.__preview = preview.Core(main) self.__engine = engine.Core(main)
def __init__(self, parent, MainWindow): app.debug_print("loading renamer core"); global main main = MainWindow self.operations = [] # operations stack self.view = wxRenamerView.Panel(self, parent, main) self.__preview = preview.Core(main) self.__engine = engine.Core(main)
def __init__(self, parent, main_window): app.debug_print("loading sorting core"); global main main = main_window if sys.platform == u'win32': self.ctime = _(u"creation time") else: self.ctime = _(u"metadata change time") self.view = wxSortingView.Panel(self, parent, main_window) self.params = Parameters(self.view)
def __init__(self, parent, main_window): app.debug_print("loading sorting core") global main main = main_window if sys.platform == u'win32': self.ctime = _(u"creation time") else: self.ctime = _(u"metadata change time") self.view = wxSortingView.Panel(self, parent, main_window) self.params = Parameters(self.view)
def __init__(self, parent, methods, initial): app.debug_print("Open preferences dialog") global main main = parent self.prefs = methods self.__init_ctrls(parent) self.CentreOnScreen() # to see if these change when applying self.oldDirTree = self.prefs.get(u'useDirTree') self.oldSHowHiddenDirs = self.prefs.get(u'showHiddenDirs')
def set_prefs(self, prefDialog): """ Get values from panels and set to file. """ self.prefFilePath = self.__find_pref_file() prefFile = self.__open_pref_file(self.prefFilePath, 'w') options = self.header app.debug_print("Preferences to save:") # get all pages in notebook for i in range(prefDialog.notebook.GetPageCount()): # section header is page name options += u'\n[%s]\n' % prefDialog.notebook.GetPageText(i) # get all controls in page for child in prefDialog.notebook.GetPage(i).GetChildren(): value = None # order of instance checks is important if isinstance(child, wx.CheckBox): value = int(child.GetValue()) type = 'CheckBox' elif isinstance(child, wx.RadioButton): value = int(child.GetValue()) type = 'RadioButton' elif isinstance(child, wx.TextCtrl): value = child.GetValue() type = 'TextCtrl' elif isinstance(child, wx.SpinCtrl): value = child.GetValue() type = 'SpinCtrl' elif isinstance(child, wx.ComboBox): value = child.GetValue() type = 'ComboBox' elif isinstance(child, wx.Choice): value = int(child.GetSelection()) type = 'Choice' elif isinstance(child, wx.DirPickerCtrl): value = child.GetPath() type = 'DirPickerCtrl' elif isinstance(child, wx.FilePickerCtrl): value = child.GetPath() type = 'FilePickerCtrl' elif isinstance(child, wx.ColourPickerCtrl): value = child.GetColour().GetAsString(wx.C2S_HTML_SYNTAX) type = 'ColourPickerCtrl' if value is not None: name = child.GetName() options += u'%s=%s\n' % (name, value) app.debug_print(" %s (%s) = %s" % (name, type, value)) prefFile.write(options) prefFile.close() self.__load_preferences()
def __get_audio_metadata(self, filename, options=None): """Guess the type of the file and try to open it. The file type is decided by several things, such as the first 128 bytes (which usually contains a file type identifier), the filename extension, and the presence of existing tags. If no appropriate type could be found, None is returned. """ if options is None: options = [ MP3, TrueAudio, OggTheora, OggSpeex, OggVorbis, OggFLAC, FLAC, APEv2File, EasyMP4, ID3FileType, WavPack, Musepack, MonkeysAudio, OptimFROG, ASF ] if not options: return None try: fileobj = file(filename, "rb") except IOError: self.__add_to_errors(filename, _(u"Could not open file!")) return None try: header = fileobj.read(128) # Sort by name after score. Otherwise import order affects # Kind sort order, which affects treatment of things with # equals scores. results = [(Kind.score(filename, fileobj, header), Kind.__name__) for Kind in options] finally: fileobj.close() results = zip(results, options) results.sort() (score, name), Kind = results[-1] if score > 0: if Kind.__name__ == 'MP3': Kind = EasyID3 try: audioMetadata = Kind(filename) except: self.__add_to_errors(filename, _(u"Could not read audio metadata")) return None app.debug_print(audioMetadata) return audioMetadata else: self.__add_to_warnings(filename, _(u"Could not determine audio file type")) return None
def __on_apply_button(self, event): app.debug_print("Save preferences from dialog") self.prefs.set_prefs(self) prefs = app.prefs = self.prefs if prefs.get(u'useDirTree') != self.oldDirTree: main.picker.set_tree() if prefs.get(u'showHiddenDirs') != self.oldSHowHiddenDirs: main.picker.dirPicker.ShowHidden(prefs.get(u'showHiddenDirs')) self.oldDirTree = prefs.get(u'useDirTree') self.oldSHowHiddenDirs = prefs.get(u'showHiddenDirs') main.bottomWindow.display.set_preferences() main.show_preview(True)
def __use_defaults(self): """ Use the default preferences file. """ app.debug_print("Using default preferences") # show preferences prefDiag = Dialog(None, self, initial=True) prefDiag.ShowModal() try: prefDiag.Destroy() except wx._core.PyDeadObjectError: app.debug_print("=======================") pass
def __load_config_xml(self, config): pages = utils.get_notebook_page_names(main) configVersion = config.attributes['version'].value app.debug_print("config version : %s" % configVersion) for page in config.getElementsByTagName('page'): page_name = page.attributes['name'].value page_id = int(page.attributes['id'].value) # normal pages if page_name != 'mainPanel': app.debug_print("loading config page : %s" % page_name) for node in page.getElementsByTagName('value'): id = node.attributes['id'].value # make sure element exists before setting it if hasattr(pages[page_id], id): id = getattr(pages[page_id], id) else: continue type = node.attributes['type'].value try: value = node.childNodes[0].nodeValue except IndexError: value = None self.__set_widget_value(id, type, value) # adjustments if needed if hasattr(pages[page_id], 'on_config_load'): pages[page_id].on_config_load() # main page else: app.debug_print("loading renamer config") # cleanup before loading main.renamer.view.destroy_all_operations() # load values for op in page.getElementsByTagName('operation'): type = op.attributes['type'].value type = operations.get_translated_name(type) app.debug_print("loading operation type : %s" % type) # make sure it's a valid type if type == False: continue id = op.attributes['id'].value # initialise object, passing parameters params = self.__get_operation_params(op) main.renamer.view.stack_operation(type, id, params) # apply node values to widgets operation = main.renamer.operations[int(id)] for node in op.childNodes: if node.nodeType == 1 and node.nodeName != "parameters": self.__apply_values(operation, node) # apply each operation's post load routine if hasattr(operation, 'on_config_load'): operation.on_config_load()
def __get_audio_metadata(self, filename, options=None): """Guess the type of the file and try to open it. The file type is decided by several things, such as the first 128 bytes (which usually contains a file type identifier), the filename extension, and the presence of existing tags. If no appropriate type could be found, None is returned. """ if options is None: options = [MP3, TrueAudio, OggTheora, OggSpeex, OggVorbis, OggFLAC, FLAC, APEv2File, EasyMP4, ID3FileType, WavPack, Musepack, MonkeysAudio, OptimFROG, ASF] if not options: return None try: fileobj = file(filename, "rb") except IOError: self.__add_to_errors(filename, _(u"Could not open file!")) return None try: header = fileobj.read(128) # Sort by name after score. Otherwise import order affects # Kind sort order, which affects treatment of things with # equals scores. results = [(Kind.score(filename, fileobj, header), Kind.__name__) for Kind in options] finally: fileobj.close() results = zip(results, options) results.sort() (score, name), Kind = results[-1] if score > 0: if Kind.__name__ == 'MP3': Kind = EasyID3 try: audioMetadata = Kind(filename) except: self.__add_to_errors(filename, _(u"Could not read audio metadata")) return None app.debug_print(audioMetadata) return audioMetadata else: self.__add_to_warnings(filename, _(u"Could not determine audio file type")) return None
def __get_operation_params(self, op): """Get operation parameters from XML, return dict.""" params = {} try: paramNode = op.getElementsByTagName('parameters')[0] except IndexError: app.debug_print(u"warning : could not load all parameters for '%s' operation." % op.attributes['type'].value) else: for node in paramNode.childNodes: if node.nodeType == 1: value = node.childNodes[0].nodeValue if value == 'True': value = True if value == 'False': value = False params[node.nodeName] = value return params
def set_root_path(self, root): """Load all needed panel values to instance.""" app.debug_print("Examining : %s" % root) self.root = False # don't do anything for blank path if not root: main.set_status_msg('', u'eyes') # don't do anything unless path is readable elif not os.access(root, os.R_OK): main.set_status_msg(_(u"Cannot read path!"), u'warn') #main.bottomWindow.display.DeleteAllItems() # all good else: self.root = root
def __get_operation_params(self, op): """Get operation parameters from XML, return dict.""" params = {} try: paramNode = op.getElementsByTagName('parameters')[0] except IndexError: app.debug_print( u"warning : could not load all parameters for '%s' operation." % op.attributes['type'].value) else: for node in paramNode.childNodes: if node.nodeType == 1: value = node.childNodes[0].nodeValue if value == 'True': value = True if value == 'False': value = False params[node.nodeName] = value return params
def _rename_item(self, i, original, renamed, refresh_int): """ Renaming operation, with recursive error handling. Returns False on success. """ try: shutil1.move(original[0], renamed[0], True) except IOError as (errNumb, err): app.debug_print("IOError : %s, %s" % (errNumb, err)) # may need to create dirs first if errNumb == 2 and not os.path.exists(os.path.dirname(renamed[0])): try: os.makedirs(os.path.dirname(renamed[0])) except OSError as (n, err): self._show_rename_error(i, err, original, renamed) return 'makedirs' else: return self._rename_item(i, original, renamed, refresh_int)
def load_prefs(self, panel): """load preferences from file and apply them to a panel.""" app.debug_print('Loading %s preferences ...' % panel.GetName()) for child in panel.GetChildren(): try: v = self.prefs.get(child.GetName(), False) except KeyError: pass else: app.debug_print(" %s = %s" % (child.GetName(), v)) if isinstance(child, wx.CheckBox) or isinstance(child, wx.RadioButton)\ or isinstance(child, wx.SpinCtrl): child.SetValue(v) elif isinstance(child, wx.ComboBox) or isinstance(child, wx.TextCtrl): child.SetValue(unicode(v)) elif isinstance(child, wx.Choice): child.SetSelection(v) elif isinstance(child, wx.DirPickerCtrl) or isinstance(child, wx.FilePickerCtrl): child.SetPath(unicode(v)) elif isinstance(child, wx.ColourPickerCtrl): child.SetColour(v)
def load_prefs(self, panel): """ load preferences from file and apply them to a panel. """ app.debug_print('Load preferences from file into %s' % panel.GetName()) object_types = (wx.CheckBox, wx.RadioButton, wx.SpinCtrl, wx.ComboBox, wx.TextCtrl, wx.Choice, wx.DirPickerCtrl, wx.FilePickerCtrl, wx.ColourPickerCtrl) for child in panel.GetChildren(): if not isinstance(child, object_types): continue child_name = child.GetName() try: v = self.prefs.get(child_name) except KeyError: app.debug_print("Could not find value for: '%s'" % (child_name)) # forces the user to apply prefs, hopefully fixing the file self.close.Enable(False) else: app.debug_print(" %s = %s" % (child_name, v)) if isinstance(child, wx.CheckBox) or isinstance(child, wx.RadioButton)\ or isinstance(child, wx.SpinCtrl): child.SetValue(v) elif isinstance(child, wx.ComboBox) or isinstance( child, wx.TextCtrl): child.SetValue(unicode(v)) elif isinstance(child, wx.Choice): child.SetSelection(v) elif isinstance(child, wx.DirPickerCtrl) or isinstance( child, wx.FilePickerCtrl): child.SetPath(unicode(v)) elif isinstance(child, wx.ColourPickerCtrl): child.SetColour(v)
def __load_preferences(self): """ Get values from file (one way or another) """ prefFile = self.__find_pref_file() app.debug_print("Try to load preferences from file") # make sure the file exist and is filled: if not os.path.exists(prefFile) or os.path.getsize(prefFile) < 5: app.debug_print("File does not exist or is empty: Using default preferences") prefFile = app.get_real_path(os.path.join('preferences', 'default.ini')) self.prefFilePath = prefFile prefs = self.__read_file(prefFile) # windows-compatible? if platform.system() != 'Windows': win_compatible = False if prefs.get(u'useWinChars', win_compatible): prefs[u'bad_chars'] = (u'\\', u'/', u':', u'*', u'?', u'"', u'>', u'<', u'|') if prefs.get(u'useWinNames', win_compatible): prefs[u'bad_win_words'] = (u'con', u'prn', u'aux', u'clock$', u'nul', u'com1', u'com2', u'com3', u'com4', u'com5', u'com6', u'com7', u'com8', u'com9', u'lpt1', u'lpt2', u'lpt3', u'lpt4', u'lpt5', u'lpt6', u'lpt7', u'lpt8', u'lpt9') prefs[u'backgroundColor'] = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) prefs[u'highlightColor'] = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT) prefs[u'highlightTextColor'] = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT) prefs[u'textColor'] = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) app.debug_print("Loaded %s preferences" % len(prefs)) self.prefs = prefs
def __init__(self, parent, MainWindow): app.debug_print("loading picker core") self.CommonSearches = ( ("" , ""), ( _(u"- audio") , u"\.(mp3|wav|ogg|flac|wma|aiff|aac|m3u|mid|ra|ram|m4a)$"), ( _(u"- image") , u"\.(bmp|jpg|jpeg|png|svg|ico|tif|tiff|gif|psd|ai|thm|nef)$"), ( _(u"- video") , u"\.(avi|mpg|mpeg|mpe|mp4|m4e|wmv|divx|flc|mov|ogm)$"), ( _(u"- office related") , u"\.(txt|csv|rtf|doc|otf|xls|pps|ppt)$"), ( _(u"- web related") , u"\.(htm|html|php|css|js|asp|cgi|swf)$"), ( _(u"- programming") , u"\.(py|pyc|php|pl|h|c|cpp|cxx|jar|java|js|tcl)$"), ( _(u"- compressed") , u"\.(zip|tar|7z|ace|gz|tgz|rar|r\d{1,3}|cab|bz2)$"), ( _(u"- an extension") , u"^.+\..+$"), ( _(u"- only an extension") , u"(^|\\\|/)\."), ) self.CustomSearches = {} global main main = MainWindow self.view = wxPickerView.Panel(self, parent, MainWindow) self.params = Parameters(self.view) self.joinedItems = []
def __load_file(self, configFilePath): """Read file and apply settings.""" app.debug_print("loading config file : %s" % configFilePath) # attempt to open config file try: xmldoc = codecs.open(configFilePath, 'r', 'utf-8') xmldoc = minidom.parseString(xmldoc.read().encode("utf-8")) except: utils.make_err_msg( _(u"Invalid XML in config file : %s") % configFilePath, _(u"Invalid Configuration") ) else: config = xmldoc.firstChild # set autopreview to false while loading config # avoids loading paths more than once v = main.bottomWindow.autoPreview.GetValue() main.bottomWindow.autoPreview.SetValue(False) # get original path oldPath = main.picker.view.path.GetValue() self.__load_config_xml(config) if self.loadError: utils.make_warn_msg(_(u"Not all settings could be loaded.")) # Do not replace a set path if one is not set in the config newPath = main.picker.view.path.GetValue() if oldPath and not newPath: main.picker.view.path.SetValue(oldPath) # preview main.bottomWindow.autoPreview.SetValue(v) if app.autoModeLevel != 0 or\ (app.prefs.get('previewOnConfig') and app.autoModeLevel is False): main.picker.view.reset_dirpicker_on_config_load()
def load_prefs(self, panel): """load preferences from file and apply them to a panel.""" app.debug_print('Loading %s preferences ...' % panel.GetName()) for child in panel.GetChildren(): try: v = self.prefs.get(child.GetName(), False) except KeyError: pass else: app.debug_print(" %s = %s" % (child.GetName(), v)) if isinstance(child, wx.CheckBox) or isinstance(child, wx.RadioButton)\ or isinstance(child, wx.SpinCtrl): child.SetValue(v) elif isinstance(child, wx.ComboBox) or isinstance( child, wx.TextCtrl): child.SetValue(unicode(v)) elif isinstance(child, wx.Choice): child.SetSelection(v) elif isinstance(child, wx.DirPickerCtrl) or isinstance( child, wx.FilePickerCtrl): child.SetPath(unicode(v)) elif isinstance(child, wx.ColourPickerCtrl): child.SetColour(v)
def __load_file(self, configFilePath): """Read file and apply settings.""" app.debug_print("loading config file : %s" % configFilePath) # attempt to open config file try: xmldoc = codecs.open(configFilePath, 'r', 'utf-8') xmldoc = minidom.parseString(xmldoc.read().encode("utf-8")) except: utils.make_err_msg( _(u"Invalid XML in config file : %s") % configFilePath, _(u"Invalid Configuration")) else: config = xmldoc.firstChild # set autopreview to false while loading config # avoids loading paths more than once v = main.bottomWindow.autoPreview.GetValue() main.bottomWindow.autoPreview.SetValue(False) # get original path oldPath = main.picker.view.path.GetValue() self.__load_config_xml(config) if self.loadError: utils.make_warn_msg(_(u"Not all settings could be loaded.")) # Do not replace a set path if one is not set in the config newPath = main.picker.view.path.GetValue() if oldPath and not newPath: main.picker.view.path.SetValue(oldPath) # preview main.bottomWindow.autoPreview.SetValue(v) if app.autoModeLevel != 0 or\ (app.prefs.get('previewOnConfig') and app.autoModeLevel is False): main.picker.view.reset_dirpicker_on_config_load()
def load_prefs(self, panel): """ load preferences from file and apply them to a panel. """ app.debug_print('Load preferences from file into %s' % panel.GetName()) object_types = ( wx.CheckBox, wx.RadioButton, wx.SpinCtrl, wx.ComboBox, wx.TextCtrl, wx.Choice, wx.DirPickerCtrl, wx.FilePickerCtrl, wx.ColourPickerCtrl ) for child in panel.GetChildren(): if not isinstance(child, object_types): continue child_name = child.GetName() try: v = self.prefs.get(child_name) except KeyError: app.debug_print("Could not find value for: '%s'" % (child_name)) # forces the user to apply prefs, hopefully fixing the file self.close.Enable(False) else: app.debug_print(" %s = %s" % (child_name, v)) if isinstance(child, wx.CheckBox) or isinstance(child, wx.RadioButton)\ or isinstance(child, wx.SpinCtrl): child.SetValue(v) elif isinstance(child, wx.ComboBox) or isinstance(child, wx.TextCtrl): child.SetValue(unicode(v)) elif isinstance(child, wx.Choice): child.SetSelection(v) elif isinstance(child, wx.DirPickerCtrl) or isinstance(child, wx.FilePickerCtrl): child.SetPath(unicode(v)) elif isinstance(child, wx.ColourPickerCtrl): child.SetColour(v)
except IOError as (errNumb, err): app.debug_print("IOError : %s, %s" % (errNumb, err)) # may need to create dirs first if errNumb == 2 and not os.path.exists(os.path.dirname(renamed[0])): try: os.makedirs(os.path.dirname(renamed[0])) except OSError as (n, err): self._show_rename_error(i, err, original, renamed) return 'makedirs' else: return self._rename_item(i, original, renamed, refresh_int) else: self._show_rename_error(i, err, original, renamed) return True except OSError as (errNumb, err): app.debug_print("OSError : %s, %s" % (errNumb, err)) # don't stop for a read-only error if the renamed item exists if not (errNumb == 30 and os.path.exists(renamed[0])): self._show_rename_error(i, err, original, renamed) return True # set item as renamed main.toRename[i][1][1] = True # refresh based on user settings if i % refresh_int == 0: self._set_display(i) # renaming is successful return False
def __open_pref_file(self, type): prefFile = self.__find_pref_file() app.debug_print("Opening as '%s' : %s" % (type, prefFile)) prefFile = codecs.open(prefFile, type, 'utf-8') return prefFile
def __init__(self, main_window): app.debug_print("loading operations parser"); global main main = main_window self.reset()
def __init__(self, parent, MainWindow): app.debug_print("loading errors core") global main main = MainWindow self.view = wxErrorsView.Panel(self, parent, main)
def __init__(self, parent, MainWindow): app.debug_print("loading errors core"); global main main = MainWindow self.view = wxErrorsView.Panel(self, parent, main)
class MainWindow(wx.Frame): """Main application class""" def __init_menubar(self, parent): parent.Append(menu=self.menuFile, title=_(u"File")) parent.Append(menu=self.menuPicker, title=_(u"Picker")) parent.Append(menu=self.menuRenamer, title=_(u"Renamer")) parent.Append(menu=self.menuEdit, title=_(u"Settings")) parent.Append(menu=self.menuHelp, title=_(u"Help")) self.menuPicker.getAllMenu.Enable(False) self.menuPicker.getNoneMenu.Enable(False) self.menuFile.GoMenu.Enable(False) def __init_menu_file(self, parent): parent.LoadIniMenu = wx.MenuItem(parent, wxID_MENUFILE_LOADINI, _(u"&Load Config\tctrl+L"), self.make_space(_(u"Load configuration from file"))) parent.LoadIniMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'loadIni.png'), wx.BITMAP_TYPE_PNG)) parent.SaveIniMenu = wx.MenuItem(parent, wxID_MENUFILE_SAVEINI, _(u"&Save Config\tctrl+S"), self.make_space(_(u"Save configuration to file"))) parent.SaveIniMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'saveIni.png'), wx.BITMAP_TYPE_PNG)) parent.SaveLog = wx.MenuItem(parent, wxID_MENUFILE_SAVELOG, _(u"&Export to log file"), self.make_space(_(u"Save current snapshot to a log file"))) parent.SaveLog.SetBitmap(wx.Bitmap(utils.icon_path(u'CSVto.png'), wx.BITMAP_TYPE_PNG)) parent.Import = wx.MenuItem(parent, wxID_MENUFILE_IMPORT, _(u"&Import from log file"), self.make_space(_(u"Load a snapshot"))) parent.Import.SetBitmap(wx.Bitmap(utils.icon_path(u'CSVfrom.png'), wx.BITMAP_TYPE_PNG)) parent.resetApp = wx.MenuItem(parent, wxID_MENUFILE_RESET, _(u"&Reset"), self.make_space(_(u"Reset all settings"))) parent.resetApp.SetBitmap(wx.Bitmap(utils.icon_path(u'preview.png'), wx.BITMAP_TYPE_PNG)) parent.PreviewMenu = wx.MenuItem(parent, wxID_MENUFILE_PREVIEW, _(u"&Preview\tF7"), self.make_space(_(u"Preview selection"))) parent.PreviewMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'preview.png'), wx.BITMAP_TYPE_PNG)) parent.GoMenu = wx.MenuItem(parent, wxID_MENUFILE_GO, _(u"&Go !\tF8"), self.make_space(_(u"Rename selection"))) parent.GoMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'go.png'), wx.BITMAP_TYPE_PNG)) parent.exitMenu = wx.MenuItem(parent, wxID_MENUFILE_EXIT, _(u"&Quit\tctrl+Q"), self.make_space(_(u"Quit Metamorphose"))) parent.exitMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'exit.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.LoadIniMenu) parent.AppendItem(parent.SaveIniMenu) parent.AppendSeparator() parent.AppendItem(parent.SaveLog) parent.SaveLog.Enable(False) parent.AppendItem(parent.Import) parent.AppendSeparator() parent.AppendItem(parent.PreviewMenu) parent.AppendItem(parent.GoMenu) parent.AppendSeparator() parent.AppendItem(parent.resetApp) parent.AppendItem(parent.exitMenu) self.Bind(wx.EVT_MENU, self.save_items_as_text, id=wxID_MENUFILE_SAVELOG) self.Bind(wx.EVT_MENU, self.import_items_from_text, id=wxID_MENUFILE_IMPORT) self.Bind(wx.EVT_MENU, self.save_config, id=wxID_MENUFILE_SAVEINI) self.Bind(wx.EVT_MENU, self.load_config, id=wxID_MENUFILE_LOADINI) self.Bind(wx.EVT_MENU, self.on_preview_button, id=wxID_MENUFILE_PREVIEW) self.Bind(wx.EVT_MENU, self.rename_items, id=wxID_MENUFILE_GO) self.Bind(wx.EVT_MENU, self.on_menu_reset, id=wxID_MENUFILE_RESET) self.Bind(wx.EVT_MENU, self.on_menu_exit, id=wxID_MENUFILE_EXIT) def __init_menu_renamer(self, parent): parent.destroyMenu = wx.MenuItem(parent, wxID_MENURENAMER_DESTROY, _(u"Delete operation"), self.make_space(_(u"Delete current operation"))) parent.destroyMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'errors.ico'), wx.BITMAP_TYPE_ICO)) parent.destroyAllMenu = wx.MenuItem(parent, wxID_MENURENAMER_DESTROYALL, _(u"Delete all operations\tctrl+D"), self.make_space(_(u"Delete all operations"))) parent.destroyAllMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'nuke.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.destroyMenu) parent.AppendItem(parent.destroyAllMenu) self.Bind(wx.EVT_MENU, self.renamer.view.delete_operation, id=wxID_MENURENAMER_DESTROY) self.Bind(wx.EVT_MENU, self.renamer.view.destroy_all_operations, id=wxID_MENURENAMER_DESTROYALL) def __init_menu_picker(self, parent): parent.browseMenu = wx.MenuItem(parent, wxID_MENUPICKER_BROWSE, _(u"&Browse...\tF4"), self.make_space(_(u"Browse for path"))) parent.browseMenu.SetBitmap(wx.Bitmap( utils.icon_path(u'browse.png'), wx.BITMAP_TYPE_PNG)) parent.okMenu = wx.MenuItem(parent, wxID_MENUPICKER_OK, _(u"&Refresh\tF5"), self.make_space(_(u"Load or reload current path"))) parent.okMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'reload.png'), wx.BITMAP_TYPE_PNG)) parent.getAllMenu = wx.MenuItem(parent, wxID_MENUPICKER_ALL, _(u"Select &All\tctrl+A"), self.make_space(_(u"Select all items in picker"))) parent.getAllMenu.SetBitmap(wx.Bitmap( utils.icon_path(u'selectAll.png'), wx.BITMAP_TYPE_PNG)) parent.getNoneMenu = wx.MenuItem(parent, wxID_MENUPICKER_NONE, _(u"Select &None\tctrl+N"), self.make_space(_(u"Deselect all items in picker"))) parent.getNoneMenu.SetBitmap(wx.Bitmap( utils.icon_path(u'selectNone.png'), wx.BITMAP_TYPE_PNG)) parent.walkMenu = wx.MenuItem(parent, wxID_MENUPICKER_WALK, _(u"Recursive &selection\tctrl+R"), self.make_space(_(u"Get all files in directory and sub-directories, but no folders"))) parent.walkMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'walk.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.browseMenu) parent.AppendItem(parent.okMenu) parent.AppendSeparator() parent.AppendItem(parent.getAllMenu) parent.AppendItem(parent.getNoneMenu) parent.AppendItem(parent.walkMenu) self.Bind(wx.EVT_MENU, self.picker.browse_for_path, id=wxID_MENUPICKER_BROWSE) self.Bind(wx.EVT_MENU, self.picker.set_path, id=wxID_MENUPICKER_OK) self.Bind(wx.EVT_MENU, self.picker.select_none, id=wxID_MENUPICKER_NONE) self.Bind(wx.EVT_MENU, self.picker.select_all, id=wxID_MENUPICKER_ALL) self.Bind(wx.EVT_MENU, self.picker.walk_from_menu, id=wxID_MENUPICKER_WALK) def __init_menu_edit(self, parent): parent.PrefsMenu = wx.MenuItem(parent, wxID_MENUSETTINGS_PREFERENCES, _(u"Preferences"), self.make_space(_(u"Change your preferences"))) parent.langMenu = wx.MenuItem(parent, wxID_MENUSETTINGS_LANG, _(u"Language"), self.make_space(_(u"Change the language"))) parent.PrefsMenu.SetBitmap(wx.Bitmap( utils.icon_path(u'preferences.ico'), wx.BITMAP_TYPE_ICO)) parent.AppendItem(parent.PrefsMenu) parent.langMenu.SetBitmap(wx.Bitmap( utils.icon_path(u'language.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.langMenu) self.Bind(wx.EVT_MENU, self.show_preferences, id=wxID_MENUSETTINGS_PREFERENCES) self.Bind(wx.EVT_MENU, self.language_select, id=wxID_MENUSETTINGS_LANG) def __init_menu_help(self, parent): parent.aboutMenu = wx.MenuItem(parent, wxID_MENUHELP_ABOUT, _(u"About"), self.make_space(_(u"Display general information about Metamorphose"))) parent.aboutMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'about.ico'), wx.BITMAP_TYPE_ICO)) parent.helpMenu = wx.MenuItem(parent, wxID_MENUHELP_HELP, _(u"&Help\tF1"), self.make_space(_(u"How to use Metamorphose"))) parent.helpMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'help.ico'), wx.BITMAP_TYPE_ICO)) parent.examplesMenu = wx.MenuItem(parent, wxID_MENUHELP_EXAMPLES, _(u"&Examples\tF2"), self.make_space(_(u"Some useful examples"))) parent.examplesMenu.SetBitmap(wx.Bitmap( utils.icon_path(u'examples.ico'), wx.BITMAP_TYPE_ICO)) parent.FormatHelpMenu = wx.MenuItem(parent, wxID_MENUHELP_FORMATHELP, _(u"&Date && Time Formats"), self.make_space(_(u"Display a reference for Date & Time formats"))) parent.FormatHelpMenu.SetBitmap(wx.Bitmap( utils.icon_path(u'date_time.ico'), wx.BITMAP_TYPE_ICO)) parent.REhelpMenu = wx.MenuItem(parent, wxID_MENUHELP_REHELP, _(u"&Regular Expressions"), self.make_space(_(u"Display a regular expression reference"))) parent.REhelpMenu.SetBitmap(wx.Bitmap(utils.icon_path(u're.ico'), wx.BITMAP_TYPE_ICO)) parent.AppendItem(parent.aboutMenu) parent.AppendItem(parent.helpMenu) parent.AppendItem(parent.examplesMenu) parent.AppendItem(parent.FormatHelpMenu) parent.AppendItem(parent.REhelpMenu) self.Bind(wx.EVT_MENU, self.show_about, id=wxID_MENUHELP_ABOUT) self.Bind(wx.EVT_MENU, self.show_help, id=wxID_MENUHELP_HELP) self.Bind(wx.EVT_MENU, self.show_small_help, id=wxID_MENUHELP_EXAMPLES) self.Bind(wx.EVT_MENU, self.show_small_help, id=wxID_MENUHELP_FORMATHELP) self.Bind(wx.EVT_MENU, self.show_small_help, id=wxID_MENUHELP_REHELP) def __init_notebook(self): parent = self.notebook # init Core classes self.picker = picker.Core(parent, self) self.sorting = sorting.Core(parent, self) self.errors = errors.Core(parent, self) self.renamer = renamer.Core(parent, self) # list containing notebook images il = wx.ImageList(16, 16) img0 = il.Add(wx.Bitmap(utils.icon_path(u'picker.ico'), wx.BITMAP_TYPE_ICO)) img1 = il.Add(wx.Bitmap(utils.icon_path(u'main.ico'), wx.BITMAP_TYPE_ICO)) img2 = il.Add(wx.Bitmap(utils.icon_path(u'sorting.ico'), wx.BITMAP_TYPE_ICO)) img3 = il.Add(wx.Bitmap(utils.icon_path(u'errors.ico'), wx.BITMAP_TYPE_ICO)) parent.AssignImageList(il) # add notebook pages to notebook parent.AddPage(self.picker.view, _(u"Picker"), True, img0) parent.AddPage(self.renamer.view, _(u"- Renamer -"), False, img1) parent.AddPage(self.sorting.view, _(u"Sorting"), False, img2) parent.AddPage(self.errors.view, _(u"Errors/Warnings: %s") % 0, False, img3) def __init_sizer(self): mainSizer = self.mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(self.splitter, 1, wx.EXPAND | wx.ALL, 5) self.SetSizerAndFit(mainSizer) def __init_utils(self): self.menuFile = wx.Menu() self.menuPicker = wx.Menu() self.menuEdit = wx.Menu() self.menuHelp = wx.Menu() self.menuBar = wx.MenuBar() self.menuRenamer = wx.Menu() self.__init_menu_file(self.menuFile) self.__init_menu_picker(self.menuPicker) self.__init_menu_renamer(self.menuRenamer) self.__init_menu_edit(self.menuEdit) self.__init_menu_help(self.menuHelp) self.__init_menubar(self.menuBar) self.SetMenuBar(self.menuBar) def __init_fonts(self): """Get fonts from system or specify own.""" if wx.Platform == '__WXGTK__': sysFont = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) app.fontParams = { 'size': sysFont.GetPixelSize()[0], 'style': sysFont.GetStyle(), 'family': sysFont.GetFamily(), 'weight': sysFont.GetWeight(), } else: app.fontParams = { 'size': 9, 'style': wx.NORMAL, 'family': wx.DEFAULT, 'weight': wx.NORMAL, } #print(app.fontParams) self.SetFont(wx.Font( app.fontParams['size'], app.fontParams['family'], app.fontParams['style'], app.fontParams['weight']) ) def __init_ctrls(self, prnt): wx.SystemOptions.SetOption('msw.notebook.themed-background', '0') if app.debug: self.SetTitle(u"Métamorphose 2 v. %s -- DEBUG MODE" % app.version) else: self.SetTitle(u"Métamorphose 2 (beta)") self.SetBackgroundColour(wx.NullColour) self.SetAutoLayout(False) self.SetStatusBarPane(0) self.SetIcon(wx.Icon(utils.icon_path(u'metamorphose.ico'), wx.BITMAP_TYPE_ICO)) self.SetThemeEnabled(True) self.__init_fonts() self.statusBar1 = ESB.EnhancedStatusBar(id=wxID_MAIN_WINDOWSTATUSBAR1, name=u'statusBar1', parent=self) self.SetStatusBar(self.statusBar1) self.statusImage = wx.StaticBitmap(bitmap=self.statusImages[u'eyes'], id=wxID_MAIN_WINDOWSTATUSIMAGE, name=u'statusImage', parent=self.statusBar1, size=wx.Size(-1, 16), style=0) self.statusBar1.AddWidget(self.statusImage, ESB.ESB_ALIGN_LEFT) self.splitter = MySplitter(self) # notebook self.notebook = wx.Notebook(id=wxID_MAIN_WINDOWNOTEBOOK, name=u'notebook', parent=self.splitter, style=wx.NB_TOP | wx.NO_BORDER) self.notebook.SetThemeEnabled(True) self.bottomWindow = bottomWindow.MainPanel(self.splitter, self) self.SetMinSize(wx.Size(-1, 600)) self.splitter.SetMinimumPaneSize(40) if wx.Platform == '__WXGTK__': split = -210 elif wx.Platform == '__WXMSW__': split = -200 else: split = -205 self.splitter.SplitHorizontally(self.notebook, self.bottomWindow, split) def set_language(self): """ Determine language to be loaded depending on : setting file, CLI option, or neither. Apply language to interface. """ app.debug_print("== Interface Localization ==") # reference: locales = { #u'ar' : (wx.LANGUAGE_ARABIC, u'ar_SA.UTF-8'), #u'de' : (wx.LANGUAGE_GERMAN, u'de_DE.UTF-8'), #u'el' : (wx.LANGUAGE_GREEK, u'el_GR.UTF-8'), #u'en_GB' : (wx.LANGUAGE_ENGLISH_UK, u'en_GB.UTF-8'), u'en_US': (wx.LANGUAGE_ENGLISH_US, u'en_US.UTF-8'), u'es': (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'), u'fr': (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'), #u'he' : (wx.LANGUAGE_HEBREW, u'he_IL.UTF-8'), #u'hu' : (wx.LANGUAGE_HUNGARIAN, u'hu_HU.UTF-8'), #u'it' : (wx.LANGUAGE_ITALIAN, u'it_IT.UTF-8'), #u'ja' : (wx.LANGUAGE_JAPANESE, u'ja_JP.UTF-8'), #u'pl' : (wx.LANGUAGE_POLISH, u'pl_PL.UTF-8'), #u'pt_BR' : (wx.LANGUAGE_PORTUGUESE_BRAZILIAN, u'pt_BR.UTF-8'), #u'ru' : (wx.LANGUAGE_RUSSIAN, u'ru_RU.UTF-8'), #u'sv' : (wx.LANGUAGE_SWEDISH, u'sv_SE.UTF-8'), #u'tr' : (wx.LANGUAGE_TURKISH, u'tr_TR.UTF-8'), #u'zh_CN' : (wx.LANGUAGE_CHINESE_SIMPLIFIED, u'zh_CN.UTF-8'), } # right-to-left languages: rightToLeftLanguages = ('ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi') ''' syslang = locale.getdefaultlocale()[0] if syslang in locales: language = syslang ''' # get language from file if not specified from command line if not app.language: try: # see if language file exist langIni = codecs.open(utils.get_user_path(u'language.ini'), 'r', 'utf-8') except IOError: # have user choose language language = self.language_select(0) else: # get language from file language = langIni.read().strip() else: language = app.language try: locales[language] except KeyError: msg = u"Could not initialize language: '%s'.\nContinuing in " % language msg += u"American English (en_US)\n" print(msg) language = 'en_US' # needed for calendar and other things, send all logs to stderr wx.Log.SetActiveTarget(wx.LogStderr()) # set locale and language wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT) try: Lang = gettext.translation(u'metamorphose2', app.locale_path(language), languages=[locales[language][1]]) except IOError: print("Could not find the translation file for '%s'." % language) print("Try running messages/update_langs.sh\n") sys.exit(1) Lang.install(unicode=True) # set some globals if language not in rightToLeftLanguages: self.langLTR = True self.alignment = wx.ALIGN_LEFT else: self.langLTR = False self.alignment = wx.ALIGN_RIGHT app.language = language app.debug_print("Set language: " + app.language) locale.setlocale(locale.LC_ALL,'') self.encoding = unicode(locale.getlocale()[1]) app.debug_print("Set encoding: " + self.encoding) # to get some language settings to display properly: if platform.system() in ('Linux', 'FreeBSD'): try: os.environ['LANG'] = locales[language][1] except (ValueError, KeyError): pass app.debug_print("============================") app.debug_print("") def __init__(self, prnt, options): # Important variables needed throughout the application classes self.warn = [] # warnings self.bad = [] # errors self.errorLog = [] # all errors go here self.items = [] # items to rename self.spacer = u" " * 6 # spacer for status messages (to clear image) # icons used for status bar messages self.statusImages = { u'failed': wx.Bitmap(utils.icon_path(u'failed_sb.ico'), wx.BITMAP_TYPE_ICO), u'wait': wx.Bitmap(utils.icon_path(u'wait.png'), wx.BITMAP_TYPE_PNG), u'warn': wx.Bitmap(utils.icon_path(u'warn_sb.ico'), wx.BITMAP_TYPE_ICO), u'complete': wx.Bitmap(utils.icon_path(u'complete.ico'), wx.BITMAP_TYPE_ICO), u'eyes': wx.Bitmap(utils.icon_path(u'eyes.png'), wx.BITMAP_TYPE_PNG), } app.debug_print("Init MainWindow") wx.Frame.__init__(self, id=wxID_MAIN_WINDOW, name=u'MainWindow', parent=prnt, style=wx.DEFAULT_FRAME_STYLE) app.debug_print("") app.debug_print("======== System Info =======") app.debug_print("Operating System: %s - %s - %s" % (platform.system(), platform.release(), platform.version())) app.debug_print("Python version: %s" % platform.python_version()) app.debug_print("wxPython version: %s" % wx.version()) app.debug_print("============================") app.debug_print("") # first run? utils.init_environment() self.set_language() # import these modules here since they need language settings activated global renamer import renamer global configs import configs global picker import picker global bottomWindow import bottomWindow # initialize preferences app.debug_print("======== Preferences =======") app.prefs = preferences.Methods() app.debug_print("============================") app.debug_print("") # build main GUI self.__init_ctrls(prnt) # clear undo if set in preferences: if app.prefs.get(u'clearUndo'): try: originalFile = codecs.open(utils.get_user_path(u'undo/original.bak'), 'w', "utf-8") originalFile.write('') renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'), 'w', "utf-8") renamedFile.write('') except IOError, error: utils.make_err_msg(_(u"%s\n\nCould not clear undo") % error, _(u"Error")) pass # construct rest of GUI: self.__init_notebook() self.__init_utils() self.__init_sizer() # call this after sizer to place properly: self.Center(wx.HORIZONTAL | wx.VERTICAL) # Load config from command line if options['configFilePath']: app.debug_print("Load config from CLI") configs.LoadConfig(self, options['configFilePath']) # Set root directory from command line arguments: if options['path']: path = options['path'].rstrip() self.picker.view.path.SetValue(path) self.picker.set_path(True)
def set_language(self): """ Determine language to be loaded depending on : setting file, CLI option, or neither. Apply language to interface. """ app.debug_print("== Interface Localization ==") # reference: locales = { #u'ar' : (wx.LANGUAGE_ARABIC, u'ar_SA.UTF-8'), #u'de' : (wx.LANGUAGE_GERMAN, u'de_DE.UTF-8'), #u'el' : (wx.LANGUAGE_GREEK, u'el_GR.UTF-8'), #u'en_GB' : (wx.LANGUAGE_ENGLISH_UK, u'en_GB.UTF-8'), u'en_US': (wx.LANGUAGE_ENGLISH_US, u'en_US.UTF-8'), u'es': (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'), u'fr': (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'), #u'he' : (wx.LANGUAGE_HEBREW, u'he_IL.UTF-8'), #u'hu' : (wx.LANGUAGE_HUNGARIAN, u'hu_HU.UTF-8'), #u'it' : (wx.LANGUAGE_ITALIAN, u'it_IT.UTF-8'), #u'ja' : (wx.LANGUAGE_JAPANESE, u'ja_JP.UTF-8'), #u'pl' : (wx.LANGUAGE_POLISH, u'pl_PL.UTF-8'), #u'pt_BR' : (wx.LANGUAGE_PORTUGUESE_BRAZILIAN, u'pt_BR.UTF-8'), #u'ru' : (wx.LANGUAGE_RUSSIAN, u'ru_RU.UTF-8'), #u'sv' : (wx.LANGUAGE_SWEDISH, u'sv_SE.UTF-8'), #u'tr' : (wx.LANGUAGE_TURKISH, u'tr_TR.UTF-8'), #u'zh_CN' : (wx.LANGUAGE_CHINESE_SIMPLIFIED, u'zh_CN.UTF-8'), } # right-to-left languages: rightToLeftLanguages = ('ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi') ''' syslang = locale.getdefaultlocale()[0] if syslang in locales: language = syslang ''' # get language from file if not specified from command line if not app.language: try: # see if language file exist langIni = codecs.open(utils.get_user_path(u'language.ini'), 'r', 'utf-8') except IOError: # have user choose language language = self.language_select(0) else: # get language from file language = langIni.read().strip() else: language = app.language try: locales[language] except KeyError: msg = u"Could not initialize language: '%s'.\nContinuing in " % language msg += u"American English (en_US)\n" print(msg) language = 'en_US' # needed for calendar and other things, send all logs to stderr wx.Log.SetActiveTarget(wx.LogStderr()) # set locale and language wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT) try: Lang = gettext.translation(u'metamorphose2', app.locale_path(language), languages=[locales[language][1]]) except IOError: print("Could not find the translation file for '%s'." % language) print("Try running messages/update_langs.sh\n") sys.exit(1) Lang.install(unicode=True) # set some globals if language not in rightToLeftLanguages: self.langLTR = True self.alignment = wx.ALIGN_LEFT else: self.langLTR = False self.alignment = wx.ALIGN_RIGHT app.language = language app.debug_print("Set language: " + app.language) self.encoding = unicode(locale.getlocale()[1]) app.debug_print("Set encoding: " + self.encoding) # to get some language settings to display properly: if platform.system() in ('Linux', 'FreeBSD'): try: os.environ['LANG'] = locales[language][1] except (ValueError, KeyError): pass app.debug_print("============================") app.debug_print("")
def __init__(self, main_window): app.debug_print("loading operations parser") global main main = main_window self.reset()
def __init__(self, prnt, options): # Important variables needed throughout the application classes self.warn = [] # warnings self.bad = [] # errors self.errorLog = [] # all errors go here self.items = [] # items to rename self.spacer = u" " * 6 # spacer for status messages (to clear image) # icons used for status bar messages self.statusImages = { u'failed': wx.Bitmap(utils.icon_path(u'failed_sb.ico'), wx.BITMAP_TYPE_ICO), u'wait': wx.Bitmap(utils.icon_path(u'wait.png'), wx.BITMAP_TYPE_PNG), u'warn': wx.Bitmap(utils.icon_path(u'warn_sb.ico'), wx.BITMAP_TYPE_ICO), u'complete': wx.Bitmap(utils.icon_path(u'complete.ico'), wx.BITMAP_TYPE_ICO), u'eyes': wx.Bitmap(utils.icon_path(u'eyes.png'), wx.BITMAP_TYPE_PNG), } app.debug_print("Init MainWindow") wx.Frame.__init__(self, id=wxID_MAIN_WINDOW, name=u'MainWindow', parent=prnt, style=wx.DEFAULT_FRAME_STYLE) app.debug_print("") app.debug_print("======== System Info =======") app.debug_print("Operating System: %s - %s - %s" % (platform.system(), platform.release(), platform.version())) app.debug_print("Python version: %s" % platform.python_version()) app.debug_print("wxPython version: %s" % wx.version()) app.debug_print("============================") app.debug_print("") # first run? utils.init_environment() self.set_language() # import these modules here since they need language settings activated global renamer import renamer global configs import configs global picker import picker global bottomWindow import bottomWindow # initialize preferences app.debug_print("======== Preferences =======") app.prefs = preferences.Methods() app.debug_print("============================") app.debug_print("") # build main GUI self.__init_ctrls(prnt) # clear undo if set in preferences: if app.prefs.get(u'clearUndo'): try: originalFile = codecs.open(utils.get_user_path(u'undo/original.bak'), 'w', "utf-8") originalFile.write('') renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'), 'w', "utf-8") renamedFile.write('') except IOError, error: utils.make_err_msg(_(u"%s\n\nCould not clear undo") % error, _(u"Error")) pass
def __init__(self, MainWindow): app.debug_print("loading renamer preview") global main main = MainWindow self.setup()
def run(self, operations): """ Parse user settings, go through each item to be renamed and apply renaming operations. Results are stored in the dictionary 'self.toRename' which is used by the rename function to rename. """ main.Update() main.set_status_msg( _(u"Generating %s new names, please wait ...") % len(main.items), u'wait') if app.showTimes: t = time.time() main.counter = 0 main.bad = [] main.warn = [] main.ec = 0 main.errorLog = [] self.items_ren = [] app.REmsg = False # regular expression warn message # define here for faster processing def split(item): return os.path.split(item) def splitext(item): return os.path.splitext(item) def join(newPath, renamedItem): return unicode(os.path.join(newPath, renamedItem)) # test for numbering panel hasNumbering = False for op in operations: if hasattr(op, 'numberingPanel'): hasNumbering = True break # set some numbering globals if hasNumbering: main.lastDir = False main.lastName = '\n\t\r' # no item should ever have this name! main.curName = False progressDialog = classes.ProgressDialog( main, self.prefs, main.items, _(u"Generating %%% new names, please wait ...")) # define here for faster access onlyShowChangedItems = app.prefs.get('onlyShowChangedItems') for itemToRename, isFile in main.items: # clear stuff out splitPath = split(itemToRename) newPath = splitPath[0] # split name & extension renamedItem = splitPath[1] if isFile: splitName = splitext(renamedItem) newName = splitName[0] newExt = splitName[1][1:] else: newName = renamedItem newExt = False app.debug_print(itemToRename) if hasNumbering: main.curDir = newPath # go through each operation for i in range(len(operations)): op = operations[i] newPath, newName, newExt = op.rename_item( newPath, newName, newExt, itemToRename) if newExt is not False: renamedItem = newName + '.' + newExt else: renamedItem = newName # get name as it is before the last operation # use to reset numbering based on duplicate names if hasNumbering and len(operations) - 2 == i: main.curName = renamedItem renamedItem, newPath = self.errorCheck(renamedItem, itemToRename, newPath) # add to list of renamed items newItem = join(newPath, renamedItem) if not onlyShowChangedItems: self.items_ren.append(newItem) elif newItem != itemToRename or main.ec in main.bad or\ main.ec in main.warn: self.items_ren.append(newItem) app.debug_print("%s\n" % newItem) # increment item position counters main.ec += 1 # for error/warn assignment if progressDialog.update(main.ec) == False: break # for reseting numbering if hasNumbering: main.lastDir = main.curDir # by directory main.lastName = main.curName # by name progressDialog.destroy() items_ren = map(self.addStatus, self.items_ren) # make new dict with original and renamed files: main.toRename = zip(main.items, items_ren) del items_ren main.menuFile.SaveLog.Enable(True) # output time taken if set if app.showTimes: print("%s items preview : %s" % (len(main.toRename), (time.time() - t))) self.setStatusMessage()
def set_status_msg(self, msg, img): """Set status bar text and image.""" self.statusImage.SetBitmap(self.statusImages[img]) self.SetStatusText(self.make_space(msg)) app.debug_print(u"status message: '%s'" % msg)
def __init__(self, MainWindow): app.debug_print("loading renamer engine"); global main main = MainWindow
class MainWindow(wx.Frame): """Main application class""" def __init_menubar(self, parent): parent.Append(menu=self.menuFile, title=_(u"File")) parent.Append(menu=self.menuPicker, title=_(u"Picker")) parent.Append(menu=self.menuRenamer, title=_(u"Renamer")) parent.Append(menu=self.menuEdit, title=_(u"Settings")) parent.Append(menu=self.menuHelp, title=_(u"Help")) self.menuPicker.getAllMenu.Enable(False) self.menuPicker.getNoneMenu.Enable(False) self.menuFile.GoMenu.Enable(False) def __init_menu_file(self, parent): parent.LoadIniMenu = wx.MenuItem(parent, wxID_MENUFILE_LOADINI, _(u"&Load Config\tctrl+L"), self.make_space(_(u"Load configuration from file"))) parent.LoadIniMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'loadIni.png'), wx.BITMAP_TYPE_PNG)) parent.SaveIniMenu = wx.MenuItem(parent, wxID_MENUFILE_SAVEINI, _(u"&Save Config\tctrl+S"), self.make_space(_(u"Save configuration to file"))) parent.SaveIniMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'saveIni.png'), wx.BITMAP_TYPE_PNG)) parent.SaveLog = wx.MenuItem(parent, wxID_MENUFILE_SAVELOG, _(u"&Export to log file"), self.make_space(_(u"Save current snapshot to a log file"))) parent.SaveLog.SetBitmap(wx.Bitmap(utils.icon_path(u'CSVto.png'), wx.BITMAP_TYPE_PNG)) parent.Import = wx.MenuItem(parent, wxID_MENUFILE_IMPORT, _(u"&Import from log file"), self.make_space(_(u"Load a snapshot"))) parent.Import.SetBitmap(wx.Bitmap(utils.icon_path(u'CSVfrom.png'), wx.BITMAP_TYPE_PNG)) parent.resetApp = wx.MenuItem(parent, wxID_MENUFILE_RESET, _(u"&Reset"), self.make_space(_(u"Reset all settings"))) parent.resetApp.SetBitmap(wx.Bitmap(utils.icon_path(u'preview.png'), wx.BITMAP_TYPE_PNG)) parent.PreviewMenu = wx.MenuItem(parent, wxID_MENUFILE_PREVIEW, _(u"&Preview\tF7"), self.make_space(_(u"Preview selection"))) parent.PreviewMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'preview.png'), wx.BITMAP_TYPE_PNG)) parent.GoMenu = wx.MenuItem(parent, wxID_MENUFILE_GO, _(u"&Go !\tF8"), self.make_space(_(u"Rename selection"))) parent.GoMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'go.png'), wx.BITMAP_TYPE_PNG)) parent.exitMenu = wx.MenuItem(parent, wxID_MENUFILE_EXIT, _(u"&Quit\tctrl+Q"), self.make_space(_(u"Quit Metamorphose"))) parent.exitMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'exit.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.LoadIniMenu) parent.AppendItem(parent.SaveIniMenu) parent.AppendSeparator() parent.AppendItem(parent.SaveLog) parent.SaveLog.Enable(False) parent.AppendItem(parent.Import) parent.AppendSeparator() parent.AppendItem(parent.PreviewMenu) parent.AppendItem(parent.GoMenu) parent.AppendSeparator() parent.AppendItem(parent.resetApp) parent.AppendItem(parent.exitMenu) self.Bind(wx.EVT_MENU, self.save_items_as_text, id=wxID_MENUFILE_SAVELOG) self.Bind(wx.EVT_MENU, self.import_items_from_text, id=wxID_MENUFILE_IMPORT) self.Bind(wx.EVT_MENU, self.save_config, id=wxID_MENUFILE_SAVEINI) self.Bind(wx.EVT_MENU, self.load_config, id=wxID_MENUFILE_LOADINI) self.Bind(wx.EVT_MENU, self.on_preview_button, id=wxID_MENUFILE_PREVIEW) self.Bind(wx.EVT_MENU, self.rename_items, id=wxID_MENUFILE_GO) self.Bind(wx.EVT_MENU, self.on_menu_reset, id=wxID_MENUFILE_RESET) self.Bind(wx.EVT_MENU, self.on_menu_exit, id=wxID_MENUFILE_EXIT) def __init_menu_renamer(self, parent): parent.destroyMenu = wx.MenuItem(parent, wxID_MENURENAMER_DESTROY, _(u"Delete operation"), self.make_space(_(u"Delete current operation"))) parent.destroyMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'errors.ico'), wx.BITMAP_TYPE_ICO)) parent.destroyAllMenu = wx.MenuItem(parent, wxID_MENURENAMER_DESTROYALL, _(u"Delete all operations\tctrl+D"), self.make_space(_(u"Delete all operations"))) parent.destroyAllMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'nuke.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.destroyMenu) parent.AppendItem(parent.destroyAllMenu) self.Bind(wx.EVT_MENU, self.renamer.view.delete_operation, id=wxID_MENURENAMER_DESTROY) self.Bind(wx.EVT_MENU, self.renamer.view.destroy_all_operations, id=wxID_MENURENAMER_DESTROYALL) def __init_menu_picker(self, parent): parent.browseMenu = wx.MenuItem(parent, wxID_MENUPICKER_BROWSE, _(u"&Browse...\tF4"), self.make_space(_(u"Browse for path"))) parent.browseMenu.SetBitmap(wx.Bitmap(\ utils.icon_path(u'browse.png'), wx.BITMAP_TYPE_PNG)) parent.okMenu = wx.MenuItem(parent, wxID_MENUPICKER_OK, _(u"&Refresh\tF5"), self.make_space(_(u"Load or reload current path"))) parent.okMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'reload.png'), wx.BITMAP_TYPE_PNG)) parent.getAllMenu = wx.MenuItem(parent, wxID_MENUPICKER_ALL, _(u"Select &All\tctrl+A"), self.make_space(_(u"Select all items in picker"))) parent.getAllMenu.SetBitmap(wx.Bitmap(\ utils.icon_path(u'selectAll.png'), wx.BITMAP_TYPE_PNG)) parent.getNoneMenu = wx.MenuItem(parent, wxID_MENUPICKER_NONE, _(u"Select &None\tctrl+N"), self.make_space(_(u"Deselect all items in picker"))) parent.getNoneMenu.SetBitmap(wx.Bitmap(\ utils.icon_path(u'selectNone.png'), wx.BITMAP_TYPE_PNG)) parent.walkMenu = wx.MenuItem(parent, wxID_MENUPICKER_WALK, _(u"Recursive &selection\tctrl+R"), self.make_space(_(u"Get all files in directory and sub-directories, but no folders"))) parent.walkMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'walk.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.browseMenu) parent.AppendItem(parent.okMenu) parent.AppendSeparator() parent.AppendItem(parent.getAllMenu) parent.AppendItem(parent.getNoneMenu) parent.AppendItem(parent.walkMenu) self.Bind(wx.EVT_MENU, self.picker.browse_for_path, id=wxID_MENUPICKER_BROWSE) self.Bind(wx.EVT_MENU, self.picker.set_path, id=wxID_MENUPICKER_OK) self.Bind(wx.EVT_MENU, self.picker.select_none, id=wxID_MENUPICKER_NONE) self.Bind(wx.EVT_MENU, self.picker.select_all, id=wxID_MENUPICKER_ALL) self.Bind(wx.EVT_MENU, self.picker.walk_from_menu, id=wxID_MENUPICKER_WALK) def __init_menu_edit(self, parent): parent.PrefsMenu = wx.MenuItem(parent, wxID_MENUSETTINGS_PREFERENCES, _(u"Preferences"), self.make_space(_(u"Change your preferences"))) parent.langMenu = wx.MenuItem(parent, wxID_MENUSETTINGS_LANG, _(u"Language"), self.make_space(_(u"Change the language"))) parent.PrefsMenu.SetBitmap(wx.Bitmap(\ utils.icon_path(u'preferences.ico'), wx.BITMAP_TYPE_ICO)) parent.AppendItem(parent.PrefsMenu) parent.langMenu.SetBitmap(wx.Bitmap(\ utils.icon_path(u'language.png'), wx.BITMAP_TYPE_PNG)) parent.AppendItem(parent.langMenu) self.Bind(wx.EVT_MENU, self.show_preferences, id=wxID_MENUSETTINGS_PREFERENCES) self.Bind(wx.EVT_MENU, self.language_select, id=wxID_MENUSETTINGS_LANG) def __init_menu_help(self, parent): parent.aboutMenu = wx.MenuItem(parent, wxID_MENUHELP_ABOUT, _(u"About"), self.make_space(_(u"Display general information about Metamorphose"))) parent.aboutMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'about.ico'), wx.BITMAP_TYPE_ICO)) parent.helpMenu = wx.MenuItem(parent, wxID_MENUHELP_HELP, _(u"&Help\tF1"), self.make_space(_(u"How to use Metamorphose"))) parent.helpMenu.SetBitmap(wx.Bitmap(utils.icon_path(u'help.ico'), wx.BITMAP_TYPE_ICO)) parent.examplesMenu = wx.MenuItem(parent, wxID_MENUHELP_EXAMPLES, _(u"&Examples\tF2"), self.make_space(_(u"Some useful examples"))) parent.examplesMenu.SetBitmap(wx.Bitmap(\ utils.icon_path(u'examples.ico'), wx.BITMAP_TYPE_ICO)) parent.FormatHelpMenu = wx.MenuItem(parent, wxID_MENUHELP_FORMATHELP, _(u"&Date && Time Formats"), self.make_space(_(u"Display a reference for Date & Time formats"))) parent.FormatHelpMenu.SetBitmap(wx.Bitmap(\ utils.icon_path(u'date_time.ico'), wx.BITMAP_TYPE_ICO)) parent.REhelpMenu = wx.MenuItem(parent, wxID_MENUHELP_REHELP, _(u"&Regular Expressions"), self.make_space(_(u"Display a regular expression reference"))) parent.REhelpMenu.SetBitmap(wx.Bitmap(utils.icon_path(u're.ico'), wx.BITMAP_TYPE_ICO)) parent.AppendItem(parent.aboutMenu) parent.AppendItem(parent.helpMenu) parent.AppendItem(parent.examplesMenu) parent.AppendItem(parent.FormatHelpMenu) parent.AppendItem(parent.REhelpMenu) self.Bind(wx.EVT_MENU, self.show_about, id=wxID_MENUHELP_ABOUT) self.Bind(wx.EVT_MENU, self.show_help, id=wxID_MENUHELP_HELP) self.Bind(wx.EVT_MENU, self.show_small_help, id=wxID_MENUHELP_EXAMPLES) self.Bind(wx.EVT_MENU, self.show_small_help, id=wxID_MENUHELP_FORMATHELP) self.Bind(wx.EVT_MENU, self.show_small_help, id=wxID_MENUHELP_REHELP) def __init_notebook(self): parent = self.notebook # init Core classes self.picker = picker.Core(parent, self) self.sorting = sorting.Core(parent, self) self.errors = errors.Core(parent, self) self.renamer = renamer.Core(parent, self) # list containing notebook images il = wx.ImageList(16, 16) img0 = il.Add(wx.Bitmap(utils.icon_path(u'picker.ico'), wx.BITMAP_TYPE_ICO)) img1 = il.Add(wx.Bitmap(utils.icon_path(u'main.ico'), wx.BITMAP_TYPE_ICO)) img2 = il.Add(wx.Bitmap(utils.icon_path(u'sorting.ico'), wx.BITMAP_TYPE_ICO)) img3 = il.Add(wx.Bitmap(utils.icon_path(u'errors.ico'), wx.BITMAP_TYPE_ICO)) parent.AssignImageList(il) # add notebook pages to notebook parent.AddPage(self.picker.view, _(u"Picker"), True, img0) parent.AddPage(self.renamer.view, _(u"- Renamer -"), False, img1) parent.AddPage(self.sorting.view, _(u"Sorting"), False, img2) parent.AddPage(self.errors.view, _(u"Errors/Warnings: %s") % 0, False, img3) def __init_sizer(self): mainSizer = self.mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(self.splitter, 1, wx.EXPAND | wx.ALL, 5) self.SetSizerAndFit(mainSizer) def __init_utils(self): self.menuFile = wx.Menu() self.menuPicker = wx.Menu() self.menuEdit = wx.Menu() self.menuHelp = wx.Menu() self.menuBar = wx.MenuBar() self.menuRenamer = wx.Menu() self.__init_menu_file(self.menuFile) self.__init_menu_picker(self.menuPicker) self.__init_menu_renamer(self.menuRenamer) self.__init_menu_edit(self.menuEdit) self.__init_menu_help(self.menuHelp) self.__init_menubar(self.menuBar) self.SetMenuBar(self.menuBar) def __init_fonts(self): """Get fonts from system or specify own.""" if wx.Platform == '__WXGTK__': sysFont = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) app.fontParams = { 'size': sysFont.GetPixelSize()[0], 'style': sysFont.GetStyle(), 'family': sysFont.GetFamily(), 'weight': sysFont.GetWeight(), } else: app.fontParams = { 'size': 9, 'style': wx.NORMAL, 'family': wx.DEFAULT, 'weight': wx.NORMAL, } #print app.fontParams self.SetFont(wx.Font( app.fontParams['size'], app.fontParams['family'], app.fontParams['style'], app.fontParams['weight']) ) def __init_ctrls(self, prnt): wx.SystemOptions.SetOption('msw.notebook.themed-background', '0') if app.debug: self.SetTitle(u"Métamorphose 2 v. %s -- DEBUG MODE" % app.version) else: self.SetTitle(u"Métamorphose 2 (beta)") self.SetBackgroundColour(wx.NullColour) self.SetAutoLayout(False) self.SetStatusBarPane(0) self.SetIcon(wx.Icon(utils.icon_path(u'metamorphose.ico'), wx.BITMAP_TYPE_ICO)) self.SetThemeEnabled(True) self.__init_fonts() self.statusBar1 = ESB.EnhancedStatusBar(id=wxID_MAIN_WINDOWSTATUSBAR1, name=u'statusBar1', parent=self) self.SetStatusBar(self.statusBar1) self.statusImage = wx.StaticBitmap(bitmap=self.statusImages[u'eyes'], id=wxID_MAIN_WINDOWSTATUSIMAGE, name=u'statusImage', parent=self.statusBar1, size=wx.Size(-1, 16), style=0) self.statusBar1.AddWidget(self.statusImage, ESB.ESB_ALIGN_LEFT) self.splitter = MySplitter(self) # notebook self.notebook = wx.Notebook(id=wxID_MAIN_WINDOWNOTEBOOK, name=u'notebook', parent=self.splitter, style=wx.NB_TOP | wx.NO_BORDER) self.notebook.SetThemeEnabled(True) self.bottomWindow = bottomWindow.MainPanel(self.splitter, self) self.SetMinSize(wx.Size(-1, 600)) self.splitter.SetMinimumPaneSize(40) if wx.Platform == '__WXGTK__': split = -210 elif wx.Platform == '__WXMSW__': split = -200 else: split = -205 self.splitter.SplitHorizontally(self.notebook, self.bottomWindow, split) def usage(self): """Print CLI usage and options to screen.""" print() print("Metamorphose 2.%s\nRunning on Python %s, wxPython %s" % (app.version, platform.python_version(), utils.get_wxversion())) print("Copyright (C) 2006-2014 ianare sevi") print("<http://file-folder-ren.sourceforge.net/>\n") print("Metamorphose is a graphical mass renaming program for files and folders.") print("There is support for automating GUI tasks via command line.\n") print("metamorphose2 [/path/to/open/spaces ok]") print("metamorphose2 [-t] [-d] [-p /path/to/open] [[-c /path/to/file.cfg] [-a level (0-3)]] [-l language]") print() print("-h, --help Show help screen and exit.") print("-t, --timer Show time taken to complete operations.") print("-d, --debug Show debugging information.") print("-p=, --path Specify a directory to load.") print("-c=, --config Specify a configuration file to load.") print("-a=, --auto Specify automatic mode level to use with configuration file:") print(" 0 = do not preview items") print(" 1 = auto preview items") print(" 2 = auto rename items") print(" 3 = auto rename items and exit on success") print("-l=, --language Overide prefered language :") print(" en_US") print(" fr") print() print("If no other options are given, you may specify a path to open:") print("$ metamorphose2 /srv/samba/Windows Likes Spaces") print() sys.exit() def exit(self, message): """Display message and exit""" print("Command line error :") print(message) print() sys.exit(1) def strip_leading(self, a): """remove a leading '=' from CLI options""" if '=' in a: a = a.lstrip('=') return a def __get_cli_options(self): """Get options passed in at the command line""" shortOptions = "htdp:vc:va:vl:v" longOptions = ["help", "timer", "debug", "path=", "config=", "auto=", "language="] try: opts, args = getopt.getopt(sys.argv[1:], shortOptions, longOptions) except getopt.GetoptError as err: # print help information and exit: print(str(err)) sys.exit(2) # set options path = False configFilePath = False if sys.argv[1:] != [] and opts == []: path = '' for chunk in sys.argv[1:]: path += chunk + ' ' for o, a in opts: # show processing times if o in ("-t", "--timer"): app.showTimes = True print("Showing processing times") # show debug messages elif o in ("-d", "--debug"): app.debug = True print("Running in debug mode") print("Version : " + app.version) print("Python %s, wxPython %s" % (platform.python_version(), utils.get_wxversion())) # set path elif o in ("-p", "--path"): path = self.strip_leading(a) # show help and exit elif o in ("-h", "--help"): self.usage() # use a config path elif o in ("-c", "--config"): configFilePath = self.strip_leading(a) # set auto level elif o in ("-a", "--auto"): level = self.strip_leading(a) if level not in ('0', '1', '2', '3'): exit("Invalid auto mode level : '%s'" % level) elif not configFilePath: exit("Auto mode level must be used with configuration file ( '-c' or '--config' option )") else: print("Auto mode level set : %s" % level) app.autoModeLevel = int(level) # specify the language elif o in ("-l", "--language"): app.language = self.strip_leading(a) return path, configFilePath def set_language(self): """ Determine language to be loaded depending on : setting file, CLI option, or neither. Apply language to interface. """ # reference: locales = { #u'ar' : (wx.LANGUAGE_ARABIC, u'ar_SA.UTF-8'), #u'de' : (wx.LANGUAGE_GERMAN, u'de_DE.UTF-8'), #u'el' : (wx.LANGUAGE_GREEK, u'el_GR.UTF-8'), #u'en_GB' : (wx.LANGUAGE_ENGLISH_UK, u'en_GB.UTF-8'), u'en_US': (wx.LANGUAGE_ENGLISH_US, u'en_US.UTF-8'), u'es': (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'), u'fr': (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'), #u'he' : (wx.LANGUAGE_HEBREW, u'he_IL.UTF-8'), #u'hu' : (wx.LANGUAGE_HUNGARIAN, u'hu_HU.UTF-8'), #u'it' : (wx.LANGUAGE_ITALIAN, u'it_IT.UTF-8'), #u'ja' : (wx.LANGUAGE_JAPANESE, u'ja_JP.UTF-8'), #u'pl' : (wx.LANGUAGE_POLISH, u'pl_PL.UTF-8'), #u'pt_BR' : (wx.LANGUAGE_PORTUGUESE_BRAZILIAN, u'pt_BR.UTF-8'), #u'ru' : (wx.LANGUAGE_RUSSIAN, u'ru_RU.UTF-8'), #u'sv' : (wx.LANGUAGE_SWEDISH, u'sv_SE.UTF-8'), #u'tr' : (wx.LANGUAGE_TURKISH, u'tr_TR.UTF-8'), #u'zh_CN' : (wx.LANGUAGE_CHINESE_SIMPLIFIED, u'zh_CN.UTF-8'), } # right-to-left languages: rightToLeftLanguages = ('ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi') ''' syslang = locale.getdefaultlocale()[0] if syslang in locales: language = syslang ''' # get language from file if not specified from command line if app.language == '': try:# see if language file exist langIni = codecs.open(utils.get_user_path(u'language.ini'), 'r', 'utf-8') except IOError:# have user choose language language = self.language_select(0) else:# get language from file language = langIni.read().strip() else: language = app.language try: locales[language] except KeyError: msg = u"Could not initialize language: '%s'.\nContinuing in " % language msg += u"American English (en_US)\n" print(msg) language = 'en_US' # needed for calendar and other things, send all logs to stderr wx.Log.SetActiveTarget(wx.LogStderr()) # set locale and language wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT) try: Lang = gettext.translation(u'metamorphose2', app.locale_path(language), languages=[locales[language][1]]) except IOError: print("Could not find the translation file for '%s'." % language) print("Try running messages/update_langs.sh\n") sys.exit(1) Lang.install(unicode=True) # set some globals if language not in rightToLeftLanguages: self.langLTR = True self.alignment = wx.ALIGN_LEFT else: self.langLTR = False self.alignment = wx.ALIGN_RIGHT app.language = language self.encoding = unicode(locale.getlocale()[1]) # to get some language settings to display properly: if platform.system() in ('Linux', 'FreeBSD'): try: os.environ['LANG'] = locales[language][1] except (ValueError, KeyError): pass def __init__(self, prnt): # Important variables needed throughout the application classes self.warn = [] # warnings self.bad = [] # errors self.errorLog = [] # all errors go here self.items = [] # items to rename self.spacer = u" " * 6 # spacer for status messages (to clear image) path, configFilePath = self.__get_cli_options() wx.Frame.__init__(self, id=wxID_MAIN_WINDOW, name=u'MainWindow', parent=prnt, style=wx.DEFAULT_FRAME_STYLE) # first run? utils.init_environment() self.set_language() app.debug_print("Operating System : " + platform.system()) app.debug_print("System encoding : " + self.encoding) app.debug_print("Interface language : " + app.language) # import these modules here since they need language settings activated global renamer import renamer global configs import configs global picker import picker global bottomWindow import bottomWindow # initialise preferences app.prefs = preferences.Methods() # icons used for status bar messages self.statusImages = { u'failed': wx.Bitmap(utils.icon_path(u'failed_sb.ico'), wx.BITMAP_TYPE_ICO), u'wait': wx.Bitmap(utils.icon_path(u'wait.png'), wx.BITMAP_TYPE_PNG), u'warn': wx.Bitmap(utils.icon_path(u'warn_sb.ico'), wx.BITMAP_TYPE_ICO), u'complete': wx.Bitmap(utils.icon_path(u'complete.ico'), wx.BITMAP_TYPE_ICO), u'eyes': wx.Bitmap(utils.icon_path(u'eyes.png'), wx.BITMAP_TYPE_PNG), } # build main GUI self.__init_ctrls(prnt) # clear undo (if set in preferences): if app.prefs.get(u'clearUndo'): try: originalFile = codecs.open(utils.get_user_path(u'undo/original.bak'), 'w', "utf-8") originalFile.write('') renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'), 'w', "utf-8") renamedFile.write('') except IOError, error: utils.make_err_msg(_(u"%s\n\nCould not clear undo") % error, _(u"Error")) pass # construct rest of GUI: self.__init_notebook() self.__init_utils() self.__init_sizer() # call this after sizer to place properly: self.Center(wx.HORIZONTAL | wx.VERTICAL) # Load config from command line if configFilePath: app.debug_print("Load config from CLI") configs.LoadConfig(self, configFilePath) # Set root directory from command line arguments: if path: path = path.rstrip() self.picker.view.path.SetValue(path) self.picker.set_path(True)
def set_language(self): """ Determine language to be loaded depending on : setting file, CLI option, or neither. Apply language to interface. """ app.debug_print("== Interface Localization ==") # reference: locales = { #u'ar' : (wx.LANGUAGE_ARABIC, u'ar_SA.UTF-8'), #u'de' : (wx.LANGUAGE_GERMAN, u'de_DE.UTF-8'), #u'el' : (wx.LANGUAGE_GREEK, u'el_GR.UTF-8'), #u'en_GB' : (wx.LANGUAGE_ENGLISH_UK, u'en_GB.UTF-8'), u'en_US': (wx.LANGUAGE_ENGLISH_US, u'en_US.UTF-8'), u'es': (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'), u'fr': (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'), #u'he' : (wx.LANGUAGE_HEBREW, u'he_IL.UTF-8'), #u'hu' : (wx.LANGUAGE_HUNGARIAN, u'hu_HU.UTF-8'), #u'it' : (wx.LANGUAGE_ITALIAN, u'it_IT.UTF-8'), #u'ja' : (wx.LANGUAGE_JAPANESE, u'ja_JP.UTF-8'), #u'pl' : (wx.LANGUAGE_POLISH, u'pl_PL.UTF-8'), #u'pt_BR' : (wx.LANGUAGE_PORTUGUESE_BRAZILIAN, u'pt_BR.UTF-8'), #u'ru' : (wx.LANGUAGE_RUSSIAN, u'ru_RU.UTF-8'), #u'sv' : (wx.LANGUAGE_SWEDISH, u'sv_SE.UTF-8'), #u'tr' : (wx.LANGUAGE_TURKISH, u'tr_TR.UTF-8'), #u'zh_CN' : (wx.LANGUAGE_CHINESE_SIMPLIFIED, u'zh_CN.UTF-8'), } # right-to-left languages: rightToLeftLanguages = ('ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi') ''' syslang = locale.getdefaultlocale()[0] if syslang in locales: language = syslang ''' # get language from file if not specified from command line if not app.language: try: # see if language file exist langIni = codecs.open(utils.get_user_path(u'language.ini'), 'r', 'utf-8') except IOError: # have user choose language language = self.language_select(0) else: # get language from file language = langIni.read().strip() else: language = app.language try: locales[language] except KeyError: msg = u"Could not initialize language: '%s'.\nContinuing in " % language msg += u"American English (en_US)\n" print(msg) language = 'en_US' # needed for calendar and other things, send all logs to stderr wx.Log.SetActiveTarget(wx.LogStderr()) # set locale and language wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT) try: Lang = gettext.translation(u'metamorphose2', app.locale_path(language), languages=[locales[language][1]]) except IOError: print("Could not find the translation file for '%s'." % language) print("Try running messages/update_langs.sh\n") sys.exit(1) Lang.install(unicode=True) # set some globals if language not in rightToLeftLanguages: self.langLTR = True self.alignment = wx.ALIGN_LEFT else: self.langLTR = False self.alignment = wx.ALIGN_RIGHT app.language = language app.debug_print("Set language: " + app.language) locale.setlocale(locale.LC_ALL,'') self.encoding = unicode(locale.getlocale()[1]) app.debug_print("Set encoding: " + self.encoding) # to get some language settings to display properly: if platform.system() in ('Linux', 'FreeBSD'): try: os.environ['LANG'] = locales[language][1] except (ValueError, KeyError): pass app.debug_print("============================") app.debug_print("")
def run(self, operations): """ Parse user settings, go through each item to be renamed and apply renaming operations. Results are stored in the dictionary 'self.toRename' which is used by the rename function to rename. """ main.Update() main.set_status_msg(_(u"Generating %s new names, please wait ...") % len(main.items), u'wait') if app.showTimes: t = time.time() main.counter = 0 main.bad = [] main.warn = [] main.ec = 0 main.errorLog = [] self.items_ren = [] app.REmsg = False # regular expression warn message # define here for faster processing def split(item): return os.path.split(item) def splitext(item): return os.path.splitext(item) def join(newPath, renamedItem): return unicode(os.path.join(newPath, renamedItem)) # test for numbering panel hasNumbering = False for op in operations: if hasattr(op, 'numberingPanel'): hasNumbering = True break # set some numbering globals if hasNumbering: main.lastDir = False main.lastName = '\n\t\r'# no item should ever have this name! main.curName = False progressDialog = classes.ProgressDialog(main, self.prefs, main.items, _(u"Generating %%% new names, please wait ...")) # define here for faster access onlyShowChangedItems = app.prefs.get('onlyShowChangedItems') for itemToRename, isFile in main.items: # clear stuff out splitPath = split(itemToRename) newPath = splitPath[0] # split name & extension renamedItem = splitPath[1] if isFile: splitName = splitext(renamedItem) newName = splitName[0] newExt = splitName[1][1:] else: newName = renamedItem newExt = False app.debug_print(itemToRename) if hasNumbering: main.curDir = newPath # go through each operation for i in range(len(operations)): op = operations[i] newPath, newName, newExt = op.rename_item(newPath, newName, newExt, itemToRename) if newExt is not False: renamedItem = newName + '.' + newExt else: renamedItem = newName # get name as it is before the last operation # use to reset numbering based on duplicate names if hasNumbering and len(operations)-2 == i: main.curName = renamedItem renamedItem, newPath = self.errorCheck(renamedItem, itemToRename, newPath) # add to list of renamed items newItem = join(newPath, renamedItem) if not onlyShowChangedItems: self.items_ren.append(newItem) elif newItem != itemToRename or main.ec in main.bad or\ main.ec in main.warn: self.items_ren.append(newItem) app.debug_print("%s\n" % newItem) # increment item position counters main.ec += 1 # for error/warn assignment if progressDialog.update(main.ec) == False: break # for reseting numbering if hasNumbering: main.lastDir = main.curDir # by directory main.lastName = main.curName # by name progressDialog.destroy() items_ren = map(self.addStatus, self.items_ren) # make new dict with original and renamed files: main.toRename = zip(main.items, items_ren) del items_ren main.menuFile.SaveLog.Enable(True) # output time taken if set if app.showTimes: print("%s items preview : %s" % (len(main.toRename), (time.time() - t))) self.setStatusMessage()
def __open_pref_file(self, path, mode): app.debug_print("Opening as '%s': %s" % (mode, path)) prefFile = codecs.open(path, mode, 'utf-8') return prefFile
def __init__(self, MainWindow): app.debug_print("loading renamer preview"); global main main = MainWindow self.setup()