def do_windows(self): import win32gui, win32con _fa = [] for _f in self.filters: _fa.append(repr(_f)) filter='\0'.join(_fa)+'\0' customfilter='Other files (*.*)\0*.*\0' print "FILTER:",repr(filter) fname = "ERROR" try: fname,customfilter,flags = win32gui.GetOpenFileNameW( InitialDir=os.getcwd(), Flags=win32con.OFN_EXPLORER, File='', DefExt='py', Title='Open File...', Filter=filter, CustomFilter=customfilter, FilterIndex=1 ) except Exception, e: if hasattr(e,'what'): print e.what() raise RuntimeError("File select error!")
def prompt_for_input_file(self): if "Linux" in system(): import wx _app = wx.App(None) style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST dialog = wx.FileDialog(None, 'Open', style=style) if dialog.ShowModal() == wx.ID_OK: self.filepath = dialog.GetPath() else: self.filepath = "" dialog.Destroy() elif "Windows" in system(): import win32gui, win32con, os try: self.filepath, customfilter, flags = win32gui.GetOpenFileNameW( InitialDir=os.environ['temp'], Flags=win32con.OFN_EXPLORER, ) except Exception: print("File could not be selected") return else: print("OS could not be determined") return
def win32_open_dialog(title, directory): # http://msdn.microsoft.com/en-us/library/aa155724%28v=office.10%29.aspx import win32gui import win32con import pywintypes supported_files = [(_(name), ';'.join(extensions)) for name, extensions in _get_file_types()] type_filter = '\0'.join(('%s\0%s') % (name, extensions) for name, extensions in supported_files) + '\0' custom_filter = _("All Files") + '\0*.*\0' title = title or _('Choose a Translation File') try: filename, customfilter, flags = win32gui.GetOpenFileNameW( InitialDir=directory, Flags=win32con.OFN_EXPLORER | win32con.OFN_FILEMUSTEXIST | win32con.OFN_HIDEREADONLY, File='', DefExt='', Title=title, Filter=type_filter, CustomFilter=custom_filter, FilterIndex=1, # Select the "All Supported Files" ) except pywintypes.error, e: if isinstance(e.args, tuple) and len(e.args) == 3: if e.args[0] == 0: # cancel return () raise Exception("Something went wrong with win32gui", e)
def browse_files(_, title): """Ask the user to select files. Return full paths""" try: # The File parameter is a hack to increase the buffer length. ret = win32gui.GetOpenFileNameW(None, File='\x00' * 10240, Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER | win32con.OFN_FILEMUSTEXIST | win32con.OFN_HIDEREADONLY, Title=title) except pywintypes.error as e: if 0 == e.winerror: logger.debug('browse_files(): user cancelled') else: logger.exception('exception in browse_files()') return None _split = ret[0].split('\x00') if 1 == len(_split): # only one filename return _split pathnames = [] dirname = _split[0] for fname in _split[1:]: pathnames.append(os.path.join(dirname, fname)) return pathnames
def run(self): try: if mode != "dir": args = {} if self.path: atgs["InitialDir"] = os.path.dirname(self.path) args["File"] = os.path.splitext(os.path.dirname( self.path))[0] args["DefExt"] = os.path.splitext( os.path.dirname(self.path))[1] args["Title"] = self.title if self.title else "Pick a file..." args["CustomFilter"] = 'Other file types\x00*.*\x00' args["FilterIndex"] = 1 filters = "" for f in self.filters: if type(f) == str: filters += (f + "\x00") * 2 else: filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00" args["Filter"] = filters flags = win32con.OFN_EXTENSIONDIFFERENT | win32con.OFN_OVERWRITEPROMPT if self.multiple: flags |= win32con.OFN_ALLOWmultiple | win32con.OFN_EXPLORER if self.show_hidden: flags |= win32con.OFN_FORCESHOWHIDDEN args["Flags"] = flags if self.mode == "open": self.fname, self.customfilter, self.flags = win32gui.GetOpenFileNameW( **args) elif self.mode == "save": self.fname, self.customfilter, self.flags = win32gui.GetSaveFileNameW( **args) if self.fname: if self.multiple: seq = str(self.fname).split("\x00") dir_n, base_n = seq[0], seq[1:] self.selection = [ os.path.join(dir_n, i) for i in base_n ] else: self.selection = str(self.fname).split("\x00") else: # From http://timgolden.me.uk/python/win32_how_do_i/browse-for-a-folder.html pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), None, self.title if self.title else "Pick a folder...", 0, None, None) self.selection = [str(shell.SHGetPathFromIDList(pidl))] return self.selection except (RuntimeError, pywintypes.error): return None
def gui_open_file(self, start_dir=None): # pylint: disable-msg=W0703,W0613 import win32gui try: fname, _, _ = win32gui.GetOpenFileNameW() except Exception, e: print("dPlatform : Failed to get filename: %s" % e) return None
def pick_file(): fname, filt, flags = win32gui.GetOpenFileNameW( InitialDir=environ['temp'], Flags=win32con.OFN_EXPLORER, File='somefilename', DefExt='log', Title='GetOpenFileNameW', Filter='Selected extensions\0*.*\0', FilterIndex=0) return fname
def run(self): try: if self.mode != "dir": args = {} if self.path: args["InitialDir"] = os.path.dirname(self.path) path = os.path.splitext(os.path.dirname(self.path)) args["File"] = path[0] args["DefExt"] = path[1] args["Title"] = self.title if self.title else "Pick a file..." args["CustomFilter"] = 'Other file types\x00*.*\x00' args["FilterIndex"] = 1 filters = "" for f in self.filters: if type(f) == str: filters += (f + "\x00") * 2 else: filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00" args["Filter"] = filters flags = (win32con.OFN_EXTENSIONDIFFERENT | win32con.OFN_OVERWRITEPROMPT) if self.multiple: flags |= win32con.OFN_ALLOWmultiple | win32con.OFN_EXPLORER if self.show_hidden: flags |= win32con.OFN_FORCESHOWHIDDEN args["Flags"] = flags if self.mode == "open": self.fname, _, _ = win32gui.GetOpenFileNameW(**args) elif self.mode == "save": self.fname, _, _ = win32gui.GetSaveFileNameW(**args) if self.fname: if self.multiple: seq = str(self.fname).split("\x00") dir_n, base_n = seq[0], seq[1:] self.selection = [os.path.join(dir_n, i) for i in base_n] else: self.selection = str(self.fname).split("\x00") else: # From http://goo.gl/UDqCqo pidl, name, images = browse( # pylint: disable=unused-variable win32gui.GetDesktopWindow(), None, self.title if self.title else "Pick a folder...", 0, None, None ) self.selection = [str(get_path(pidl))] return self.selection except (RuntimeError, pywintypes.error): return None
def gui_open_file(self, start_dir=None): # pylint: disable-msg=W0703,W0613 import win32gui try: fname, _, _ = win32gui.GetOpenFileNameW() except Exception as e: print(f"Failed to get filename: {e}") return None return str(fname)
def configure(self): config = ConfigParser.RawConfigParser() local_path = "%s/q3anotifier.ini" % os.path.dirname(sys.argv[0]) tmp_quake_path = None try: config_file = file(local_path, "r") config.read(local_path) tmp_quake_path = config.get("q3anotifier", "quake3.exe") config_file.close() if config.has_option("q3anotifier", "timeout"): self.timeout = config.getint("q3anotifier", "timeout") if config.has_option("q3anotifier", "defaultmap"): self.defaultmap = config.get("q3anotifier", "defaultmap") if config.has_option("q3anotifier", "cmd_extra_args"): self.cmd_extra_args = config.get("q3anotifier", "cmd_extra_args") except (IOError, NoSectionError): pass if (not tmp_quake_path or not os.path.isfile(tmp_quake_path)): try: fname, customfilter, flags = win32gui.GetOpenFileNameW( File="quake3.exe", Filter="Quake 3 binary (quake3.exe)\0quake3.exe", Title="Where is your quake3.exe?", FilterIndex=0) if not os.path.isfile(fname): raise IOError tmp_quake_path = fname if not config.has_section("q3anotifier"): config.add_section("q3anotifier") config.set("q3anotifier", "quake3.exe", fname) except: sys.exit(1) try: config.set("q3anotifier", "timeout", self.timeout) config.set("q3anotifier", "defaultmap", self.defaultmap) config.set("q3anotifier", "createdwith", self.version) config.set("q3anotifier", "cmd_extra_args", self.cmd_extra_args) config_file = file(local_path, "w") config.write(config_file) config_file.close() except: pass self.QUAKEPATH = tmp_quake_path
def create_file_dialog(self, dialog_type, directory, allow_multiple, save_filename): if not directory: directory = os.environ['temp'] try: if dialog_type == FOLDER_DIALOG: desktop_pidl = shell.SHGetFolderLocation( 0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list =\ shell.SHBrowseForFolder(self.hwnd, desktop_pidl, None, 0, None, None) file_path = (shell.SHGetPathFromIDList(pidl).decode("utf-8"), ) elif dialog_type == OPEN_DIALOG: file_filter = localization[ "windows.fileFilter.allFiles"] + u"\0*.*\0" custom_filter = localization[ "windows.fileFilter.otherFiles"] + u"\0*.*\0" flags = win32con.OFN_EXPLORER if allow_multiple: flags = flags | win32con.OFN_ALLOWMULTISELECT file_path, customfilter, flags = \ win32gui.GetOpenFileNameW(self.hwnd, InitialDir=directory, Flags=flags, File=None, DefExt="", Title="", Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) parts = file_path.split('\x00') if len(parts) > 1: file_path = tuple([ os.path.join(parts[0], file_name) for file_name in parts[1:] ]) else: file_path = (file_path, ) elif dialog_type == SAVE_DIALOG: file_filter = localization[ "windows.fileFilter.allFiles"] + u"\0*.*\0" custom_filter = localization[ "windows.fileFilter.otherFiles"] + u"\0*.*\0" file_path, customfilter, flags = \ win32gui.GetSaveFileNameW(self.hwnd, InitialDir=directory, File=save_filename, DefExt="", Title="", Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) except Exception as e: logger.debug("File dialog crash", exc_info=True) file_path = None return file_path
def browse_file(_, title): """Ask the user to select a single file. Return full path""" try: ret = win32gui.GetOpenFileNameW(None, Flags=win32con.OFN_EXPLORER | win32con.OFN_FILEMUSTEXIST | win32con.OFN_HIDEREADONLY, Title=title) except pywintypes.error, e: if 0 == e.winerror: print 'debug: browse_file(): user cancelled' else: traceback.print_exc() return None
def gui_open_file(self, start_dir=None, types=[]): import win32gui typestrs = "" for desc, spec in types: typestrs += "%s\0%s\0" % (desc, spec) if not typestrs: typestrs = None try: fname, _, _ = win32gui.GetOpenFileNameW(Filter=typestrs) except Exception, e: print "Failed to get filename: %s" % e return None
def browse_file(_, title): """Ask the user to select a single file. Return full path""" try: ret = win32gui.GetOpenFileNameW(None, Flags=win32con.OFN_EXPLORER | win32con.OFN_FILEMUSTEXIST | win32con.OFN_HIDEREADONLY, Title=title) except pywintypes.error, e: logger = logging.getLogger(__name__) if 0 == e.winerror: logger.debug('browse_file(): user cancelled') else: logger.exception('exception in browse_file()') return None
def importdialog2(self, object): global filefilter, filename2 try: filename2, customfilter, flags = win32gui.GetOpenFileNameW( InitialDir=".", Flags=win32con.OFN_EXPLORER, File='', DefExt='txt', Title='Import Second Frame', Filter=filefilter, FilterIndex=0) except win32gui.error: pass os.chdir(workingdir) self.fileselected2(self)
def create_file_dialog(self, dialog_type, directory, allow_multiple, save_filename): if not directory: directory = os.environ['temp'] try: if dialog_type == FOLDER_DIALOG: desktop_pidl = shell.SHGetFolderLocation( 0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list =\ shell.SHBrowseForFolder(self.hwnd, desktop_pidl, None, 0, None, None) file_path = (shell.SHGetPathFromIDList(pidl), ) elif dialog_type == OPEN_DIALOG: file_filter = 'All Files\0*.*\0' custom_filter = 'Other file types\0*.*\0' flags = win32con.OFN_EXPLORER if allow_multiple: flags = flags | win32con.OFN_ALLOWMULTISELECT file_path, customfilter, flags = \ win32gui.GetOpenFileNameW(InitialDir=directory, Flags=flags, File=None, DefExt='', Title='', Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) parts = file_path.split('\x00') if len(parts) > 1: file_path = tuple([ os.path.join(parts[0], file_name) for file_name in parts[1:] ]) else: file_path = (file_path, ) elif dialog_type == SAVE_DIALOG: file_filter = 'All Files\0*.*\0' custom_filter = 'Other file types\0*.*\0' file_path, customfilter, flags = \ win32gui.GetSaveFileNameW(InitialDir=directory, File=save_filename, DefExt='', Title='', Filter=file_filter, CustomFilter=custom_filter, FilterIndex=0) parts = file_path.split('\x00') return file_path except: return None
def file_select(title, flt): try: ret = win32gui.GetOpenFileNameW( hwndOwner=win32console.GetConsoleWindow(), Title=title, MaxFile=1048576, Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_PATHMUSTEXIST | win32con.OFN_FILEMUSTEXIST | win32con.OFN_HIDEREADONLY | win32con.OFN_EXPLORER | win32con.OFN_DONTADDTORECENT | win32con.OFN_NOCHANGEDIR, Filter=flt) files = ret[0].split('\0') if len(files) > 1: files = [os.path.join(files[0], file) for file in files[1:]] return files except win32gui.error: return []
def btnExcute_click(self, sendor, sType, wParam, lParam): def PyThreadPythonExecute(): try: self._StartAnimation() self._ExecutePython() except Exception as e: PyLog().LogText(str(traceback.format_exc())) self._StopAnimation() PyLog().LogText('PyThreadExecute exit') # 多线程测试 t = threading.Thread(target=PyThreadPythonExecute) t.start() # ctypes测试 windll.user32.MessageBoxW(0, "中文", "Your title", win32con.MB_YESNO) windll.user32.MessageBoxA(0, "中文".encode('gbk'), "Your title".encode('gbk'), win32con.MB_YESNO) # win32gui测试 import win32gui win32gui.MessageBox(self.GetHWnd(), '中文', 'Your title', win32con.MB_YESNO | win32con.MB_ICONINFORMATION | win32con.MB_SYSTEMMODAL) (a, b, c) = win32gui.GetOpenFileNameW() print(a, b, c) win32gui.MessageBox(self.GetHWnd(), a, str(b), win32con.MB_YESNO | win32con.MB_ICONINFORMATION | win32con.MB_SYSTEMMODAL) # 进程间消息测试 hwnd = windll.user32.FindWindowW(None, '计算器') if windll.user32.IsWindow(hwnd): msgstr = '计算器' + '\0' print(len(msgstr)) msgbytes = msgstr.encode('utf-8') copydata = COPYDATASTRUCT(None, len(msgbytes), msgbytes) for i in range(1, 2): # time.sleep(1) PyLog().LogText('%d'%i) windll.user32.SendMessageA(hwnd, 0x4a, None, byref(copydata))
def OpendFileDlg(DefExt='*'): import win32gui, win32con try: flt = 'Other file types\0*.*\0' customfilter = '%s\0*.%s\0' % (DefExt.upper(), DefExt) #fname, customfilter, flags return win32gui.GetOpenFileNameW( InitialDir=CurDir, Flags=win32con.OFN_EXPLORER, # win32con.OFN_ALLOWMULTISELECT| File='', DefExt=DefExt, Title='GetOpenFileNameW', Filter=flt, CustomFilter=customfilter, FilterIndex=0) except: return None
def importdialog(self, object): global filefilter, filenames, workingdir try: filename, customfilter, flags = win32gui.GetOpenFileNameW( InitialDir=".", Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER, File='', DefExt='txt', Title='Import Image(s)', Filter=filefilter, FilterIndex=0) filenames = filename.split("\0") if len(filenames) > 1: folder = filenames[0] filenames.remove(folder) for i in range(0, len(filenames)): filenames[i] = folder + "\\" + filenames[i] except win32gui.error: pass os.chdir(workingdir) self.fileselected(self)
def run(self): self.selection = [] try: if self.mode != "dir": args = {} if self.path: if isdir(self.path): args["InitialDir"] = self.path else: args["InitialDir"] = dirname(self.path) _, ext = splitext(self.path) args["File"] = self.path args["DefExt"] = ext and ext[1:] # no period args["Title"] = self.title if self.title else "Pick a file..." args["CustomFilter"] = 'Other file types\x00*.*\x00' args["FilterIndex"] = 1 # e.g. open_file(filters=['*.txt', '*.py']) filters = "" for f in self.filters: if type(f) == str: filters += (f + "\x00") * 2 else: filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00" args["Filter"] = filters flags = win32con.OFN_OVERWRITEPROMPT flags |= win32con.OFN_HIDEREADONLY if self.multiple: flags |= win32con.OFN_ALLOWMULTISELECT flags |= win32con.OFN_EXPLORER if self.show_hidden: flags |= win32con.OFN_FORCESHOWHIDDEN args["Flags"] = flags try: if self.mode == "open": self.fname, _, _ = win32gui.GetOpenFileNameW(**args) elif self.mode == "save": self.fname, _, _ = win32gui.GetSaveFileNameW(**args) except pywintypes.error as e: # if canceled, it's not really an error if not e.winerror: self._handle_selection(self.selection) return self.selection raise if self.fname: if self.multiple: seq = str(self.fname).split("\x00") if len(seq) > 1: dir_n, base_n = seq[0], seq[1:] self.selection = [join(dir_n, i) for i in base_n] else: self.selection = seq else: self.selection = str(self.fname).split("\x00") else: # dir mode BIF_EDITBOX = shellcon.BIF_EDITBOX BIF_NEWDIALOGSTYLE = 0x00000040 # From http://goo.gl/UDqCqo pidl, name, images = browse( # pylint: disable=unused-variable win32gui.GetDesktopWindow(), None, self.title if self.title else "Pick a folder...", BIF_NEWDIALOGSTYLE | BIF_EDITBOX, None, None) # pidl is None when nothing is selected # and e.g. the dialog is closed afterwards with Cancel if pidl: self.selection = [str(get_path(pidl).decode('utf-8'))] except (RuntimeError, pywintypes.error, Exception): # ALWAYS! let user know what happened import traceback traceback.print_exc() self._handle_selection(self.selection) return self.selection
File='somefilename', DefExt='py', Title='GetSaveFileNameW', Filter=filter, CustomFilter=customfilter, FilterIndex=1) print('save file names:', repr(fname)) print('filter used:', repr(customfilter)) print('Flags:', flags) for k, v in list(win32con.__dict__.items()): if k.startswith('OFN_') and flags & v: print('\t' + k) fname, customfilter, flags = win32gui.GetOpenFileNameW( InitialDir=os.environ['temp'], Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER, File='somefilename', DefExt='py', Title='GetOpenFileNameW', Filter=filter, CustomFilter=customfilter, FilterIndex=0) print('open file names:', repr(fname)) print('filter used:', repr(customfilter)) print('Flags:', flags) for k, v in list(win32con.__dict__.items()): if k.startswith('OFN_') and flags & v: print('\t' + k)
def confirmMessage(): support = 1 display() custom_message = options['message'] message_backup = options['message_backup'] if custom_message == '': try: options['message'] = configureMessage.format(**variables) if options['message'] == options['message_backup']: options['message_type'] = 'Default' else: options['message_type'] = 'Config' except: options['message'] = options['message_backup'] options['message_type'] = 'Backup' print( '''Error: Unable to parse variables used in "configureMessage". To fix this, remove any invalid {variables} from "configureMessage" at the top of this script. ''') message = options['message'] # Custom file GUI mode if message == '$gui': try: import win32gui, win32con except: print( '\nError: unable to import "pypiwin32", this is needed for GUI mode' ) print('Attempting to install "pypiwin32"...') try: os.system('pip install pypiwin32 --user') os.system('cls') os.system('"' + str(os.path.basename(__file__)) + '"') exit() except: print( 'Failed to install "pypiwin32"\nPress enter to go back...') input() setupMessage() exit() try: print('Please select a file from the File picker GUI') selectedFile, Filter, flags = win32gui.GetOpenFileNameW( InitialDir=os.environ['temp'], Flags=win32con.OFN_EXPLORER, Title= f'{data["meta"]["proj"]} v{data["meta"]["ver"]}: Select a file to use for flooding', Filter='All files\0*.*\0', FilterIndex=0) display() options['file_path'] = selectedFile options['message_type'] = '$File' options['filename'] = os.path.basename(options['file_path']) try: with open(options['file_path'], 'r') as file_contents: options['message'] = file_contents.read() except: options[ 'message'] = 'Preview unavailable: Unsupported filetype' options['message_type'] = '$Copy' # Attempt to load variables try: options['message'] = options['message'].format(**variables) except: pass except: # No file selected setupMessage() # Custom file console mode elif message[0] == '$': try: if os.path.exists( os.path.join(os.path.dirname(__file__), message[1:])): options['file_path'] = os.path.join(os.path.dirname(__file__), message[1:]) options['message_type'] = '$File' options['filename'] = os.path.basename(options['file_path']) try: with open(options['file_path'], 'r') as file_contents: options['message'] = file_contents.read() except: options[ 'message'] = 'Preview unavailable: Unsupported filetype' options['message_type'] = '$Copy' #Attempt to load variables try: options['message'] = options['message'].format(**variables) except: pass except: setupMessage() message = options['message'] message_type = options['message_type'] filename = options['filename'] print(f'Message Type: {message_type}') if message_type == '$File' or message_type == '$Copy': print(f'Filename: {filename}') print(f'\n______ Message ______\n\n{message}\n\n______ Message ______\n') confirm = confirm_choice() if confirm: setup_drive() else: setupMessage()
def run(self): self.selection = [] try: if self.mode != "dir": args = {} if self.path: args["InitialDir"] = dirname(self.path) _, ext = splitext(self.path) args["File"] = self.path args["DefExt"] = ext args["Title"] = self.title if self.title else "Pick a file..." args["CustomFilter"] = 'Other file types\x00*.*\x00' args["FilterIndex"] = 1 # e.g. open_file(filters=['*.txt', '*.py']) filters = "" for f in self.filters: if type(f) == str: filters += (f + "\x00") * 2 else: filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00" args["Filter"] = filters flags = win32con.OFN_EXTENSIONDIFFERENT flags |= win32con.OFN_OVERWRITEPROMPT if self.multiple: flags |= win32con.OFN_ALLOWMULTISELECT flags |= win32con.OFN_EXPLORER if self.show_hidden: flags |= win32con.OFN_FORCESHOWHIDDEN args["Flags"] = flags # GetOpenFileNameW, GetSaveFileNameW will raise # pywintypes.error: (0, '...', 'No error message is available') # which is most likely due to incorrect type handling from the # win32gui side; return empty list in that case after exception if self.mode == "open": self.fname, _, _ = win32gui.GetOpenFileNameW(**args) elif self.mode == "save": self.fname, _, _ = win32gui.GetSaveFileNameW(**args) if self.fname: if self.multiple: seq = str(self.fname).split("\x00") dir_n, base_n = seq[0], seq[1:] self.selection = [ join(dir_n, i) for i in base_n ] else: self.selection = str(self.fname).split("\x00") else: # dir mode # From http://goo.gl/UDqCqo pidl, name, images = browse( # pylint: disable=unused-variable win32gui.GetDesktopWindow(), None, self.title if self.title else "Pick a folder...", 0, None, None ) # pidl is None when nothing is selected # and e.g. the dialog is closed afterwards with Cancel if pidl: self.selection = [str(get_path(pidl).decode('utf-8'))] except (RuntimeError, pywintypes.error): # ALWAYS! let user know what happened import traceback traceback.print_exc() self._handle_selection(self.selection) return self.selection
Title="GetSaveFileNameW", Filter=filter, CustomFilter=customfilter, FilterIndex=1, ) print("save file names:", repr(fname)) print("filter used:", repr(customfilter)) print("Flags:", flags) for k, v in list(win32con.__dict__.items()): if k.startswith("OFN_") and flags & v: print("\t" + k) fname, customfilter, flags = win32gui.GetOpenFileNameW( InitialDir=os.environ["temp"], Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER, File="somefilename", DefExt="py", Title="GetOpenFileNameW", Filter=filter, CustomFilter=customfilter, FilterIndex=0, ) print("open file names:", repr(fname)) print("filter used:", repr(customfilter)) print("Flags:", flags) for k, v in list(win32con.__dict__.items()): if k.startswith("OFN_") and flags & v: print("\t" + k)
try: _cp = int(_cp[2:]) ctypes.windll.kernel32.SetConsoleCP(_cp) ctypes.windll.kernel32.SetConsoleOutputCP(_cp) except (ValueError, TypeError): # Code page number in locale is not valid pass except ImportError: pass # Workaround for IPython thread issues with win32 comdlg32 if os.environ.get('IPYTHON', False): try: import win32gui, win32api try: win32gui.GetOpenFileNameW( File=win32api.GetSystemDirectory()[:2]) except win32gui.error: # This error is triggered intentionally pass except ImportError: # Unfortunately, pywin32 is not installed... pass # Set standard outputs encoding: # (otherwise, for example, print u"é" will fail) encoding = None try: import locale except ImportError: pass else:
def main(): # Find NSIS. try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'Software\NSIS') nsisPath = _winreg.QueryValueEx(key, '')[0] _winreg.CloseKey(key) except WindowsError: win32api.MessageBox( 0, '''To create theme installers, you must have NSIS installed on your system. NSIS is needed to create theme installers, but not to use them. NSIS is free software that can be downloaded from http://nsis.sourceforge.net/.''', 'Theme Installer Generator', win32con.MB_OK | win32con.MB_ICONSTOP) sys.exit(1) makensis = os.path.join(nsisPath, 'makensis.exe') # Find possible themes. themes = [] os.chdir(os.path.join('..', 'data', 'themes')) for name in os.listdir('.'): if os.path.isfile(os.path.join(name, 'theme.ini')): themes.append(name) # Get the theme and its version number. themesel = ThemeSelectWindow(Tk(), themes) theme = themesel.run() versel = VersionSelectWindow(Tk()) version = versel.run() # Allow a license agreement to be added. if win32api.MessageBox( 0, 'Would you like to display a license agreement in the installer?', 'Theme Installer Generator', win32con.MB_YESNO | win32con.MB_ICONQUESTION) == win32con.IDYES: try: licensefile = win32gui.GetOpenFileNameW( Filter= 'License Agreements (COPYING,LICENSE,*.txt,*.rtf)\0COPYING;LICENSE;*.txt;*.rtf\0All Files (*.*)\0*.*\0', Title='Theme Installer Generator: Select license agreement', Flags=win32con.OFN_DONTADDTORECENT | win32con.OFN_FILEMUSTEXIST | win32con.OFN_HIDEREADONLY | win32con.OFN_NOCHANGEDIR)[0] except pywintypes.error: sys.exit(0) else: licensefile = None # Where are we putting this? try: destfile = win32gui.GetSaveFileNameW( Filter='Executable files (*.exe)\0*.exe\0All Files (*.*)\0*.*\0', Title='Theme Installer Generator: Save installer', Flags=win32con.OFN_DONTADDTORECENT | win32con.OFN_OVERWRITEPROMPT | win32con.OFN_HIDEREADONLY | win32con.OFN_NOCHANGEDIR)[0] except pywintypes.error: sys.exit(0) # Let's do this. script = r""" !define THEME_NAME "%s" !define THEME_VERSION "%s" !include "MUI2.nsh" # Installer title and filename. Name 'FoFiX Theme "${THEME_NAME}" v${THEME_VERSION}' OutFile '%s' # Installer parameters. SetCompressor /SOLID lzma RequestExecutionLevel user # no UAC on Vista ShowInstDetails show # Where we're going (by default at least) InstallDir '$DOCUMENTS\FoFiX' # Where we stashed the install location. InstallDirRegKey HKCU 'SOFTWARE\myfingershurt\FoFiX' InstallRoot # Function to run FoFiX from the finish page. Function runFoFiX SetOutPath $INSTDIR Exec $INSTDIR\FoFiX.exe FunctionEnd # More installer parameters. !define MUI_ABORTWARNING !define MUI_FINISHPAGE_NOAUTOCLOSE !define MUI_FINISHPAGE_NOREBOOTSUPPORT !define MUI_FINISHPAGE_RUN !define MUI_FINISHPAGE_RUN_TEXT "Run FoFiX" !define MUI_FINISHPAGE_RUN_FUNCTION runFoFiX !define MUI_LICENSEPAGE_RADIOBUTTONS !define MUI_HEADERIMAGE !define MUI_FINISHPAGE_TEXT "FoFiX Theme $\"${THEME_NAME}$\" v${THEME_VERSION} has been installed on your computer.$\r$\n$\r$\nClick Finish to close this wizard.$\r$\n$\r$\nInstaller framework by John Stumpo." !define MUI_FINISHPAGE_TEXT_LARGE # gfx pending #!define MUI_HEADERIMAGE_BITMAP "pkg\installer_gfx\header.bmp" # Function to verify the install path. Function verifyFoFiXInstDir IfFileExists $INSTDIR haveDir Abort haveDir: IfFileExists $INSTDIR\FoFiX.exe allow MessageBox MB_YESNO|MB_ICONEXCLAMATION "This does not look like a valid FoFiX installation folder.$\r$\n$\r$\nIf you would like to merely unpack the theme files into this folder, you may continue anyway.$\r$\n$\r$\nContinue?" IDYES allow Abort allow: FunctionEnd # The pages of the installer... !insertmacro MUI_PAGE_WELCOME %s !define MUI_PAGE_CUSTOMFUNCTION_LEAVE verifyFoFiXInstDir !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH # Throw in a cool background image. # gfx pending #!define MUI_CUSTOMFUNCTION_GUIINIT startBackground #Function startBackground # InitPluginsDir # File /oname=$PLUGINSDIR\background.bmp pkg\installer_gfx\background.bmp # BgImage::SetBG /NOUNLOAD /FILLSCREEN $PLUGINSDIR\background.bmp # BgImage::Redraw /NOUNLOAD #FunctionEnd #Function .onGUIEnd # BgImage::Destroy #FunctionEnd !insertmacro MUI_LANGUAGE "English" Section """ % tuple( map(str, (theme, version, destfile, licensefile and ('!insertmacro MUI_PAGE_LICENSE "%s"' % licensefile) or ''))) for root, dirs, files in os.walk(theme): if root.find('.svn') != -1: #stump: skip .svn folders continue script += 'SetOutPath "$INSTDIR\\data\\themes\\%s\\%s"\r\n' % ( theme, root[len(theme):]) for f in files: script += 'File "%s"\r\n' % os.path.join(root, f) script += 'SetOutPath $INSTDIR\r\nSectionEnd\r\n' open('Setup.nsi', 'w').write(script) if os.spawnl(os.P_WAIT, makensis, 'makensis.exe', 'Setup.nsi') != 0: raise RuntimeError, 'Installer generation failed.' os.unlink('Setup.nsi') win32api.MessageBox(0, 'Installer generation complete.', 'Theme Installer Generator', win32con.MB_OK | win32con.MB_ICONINFORMATION)