Example #1
0
    def gui_save_file(self, start_dir=None, default_name=None, types=[]):
        import win32gui
        import win32api

        (pform, _, _, _, _) = win32api.GetVersionEx()

        typestrs = ""
        custom = "%s\0*.%s\0" % (types[0][0], types[0][1])
        for desc, ext in types[1:]:
            typestrs += "%s\0%s\0" % (desc, "*.%s" % ext)

        if pform > 5:
            typestrs = "%s\0%s\0" % (types[0][0], "*.%s" % types[0][1]) + \
                typestrs

        if not typestrs:
            typestrs = custom
            custom = None

        def_ext = "*.%s" % types[0][1]
        try:
            fname, _, _ = win32gui.GetSaveFileNameW(File=default_name,
                                                    CustomFilter=custom,
                                                    DefExt=def_ext,
                                                    Filter=typestrs)
        except Exception, e:
            print "Failed to get filename: %s" % e
            return None
Example #2
0
    def cmd(self, root, label, filter, dir, var):
        if self.saveas:
            if sys.platform[0:3].lower() == 'win':
                ##Win32 GUI hack to avoid "<somefile>/ exists. Do you want to replace it?"
                ##when using tkFileDialog.asksaveasfilename
                import win32gui
                #Convert filter from [('Python Scripts',('*.py','*.pyw')),('Text files','*.txt')] format
                #to 'Python Scripts\0*.py;*.pyw\0Text files\0*.txt\0' format
                winfilter = ''
                for desc, ext in filter:
                    if type(ext) in [list, tuple]: ext = ';'.join(ext)
                    winfilter += '%s (%s)\0%s\0' % (desc, ext, ext)
                try:
                    fd, filter, flags = win32gui.GetSaveFileNameW(
                        InitialDir=dir.get(),
                        Title='Please select a file',
                        Filter=winfilter)
                except:
                    fd = None
            else:
                fd = tkFileDialog.asksaveasfilename(parent=root,
                                                    filetypes=filter,
                                                    initialdir=dir.get(),
                                                    title=label)
        else:
            fd = tkFileDialog.askopenfilename(parent=root,
                                              filetypes=filter,
                                              initialdir=dir.get(),
                                              title=label)

        if fd:
            fd = os.path.normpath(fd)
            dir.set(os.path.split(fd)[0])
            var.set(fd)
Example #3
0
    def save(self):
        """
        saves scan results
        """
        filter = 'Log files (*.log)\0*.log\0All files (*.*)\0*.*\0'
        customfilter = 'Other file types\0*.*\0'
        fname = None

        try:
            fname, customfilter, flags = win32gui.GetSaveFileNameW(
                InitialDir='C:\\',
                Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER,
                File='', DefExt='log',
                Title='Save File',
                Filter=filter,
                CustomFilter=customfilter,
                FilterIndex=1)

        except:
            pass

        if fname:
            with open(fname, 'w') as f:
                f.write(self.log)

            self.logged = self.log
Example #4
0
def win32_save_dialog(title, current_filename):
    import win32gui
    import win32con
    import pywintypes
    supported_files = _get_used_filetypes(current_filename)

    type_filter = '\0'.join(('%s\0%s') % (name, ';'.join(extensions))
                            for name, extensions in supported_files) + '\0'
    custom_filter = _("All Files") + '\0*.*\0'
    directory, filename = os.path.split(current_filename)
    name, extension = os.path.splitext(filename)
    title = title or _('Save')
    try:
        filename, customfilter, flags = win32gui.GetSaveFileNameW(
            InitialDir=directory,
            Flags=win32con.OFN_EXPLORER | win32con.OFN_OVERWRITEPROMPT,
            File=name,
            DefExt=extension,
            Title=title,
            Filter=type_filter,
            CustomFilter=custom_filter,
            FilterIndex=1,  # Select the relevant filter
        )
    except pywintypes.error, e:
        if isinstance(e.args, tuple) and len(e.args) == 3:
            if e.args[0] == 0:
                # cancel
                return u''
        raise Exception("Something went wrong with win32gui", e)
Example #5
0
    def gui_save_file(self, start_dir=None, default_name=None):
        # pylint: disable-msg=W0703,W0613
        import win32gui

        try:
            fname, _, _ = win32gui.GetSaveFileNameW(File=default_name)
        except Exception, e:
            print("dPlatform :Failed to get filename: %s" % e)
            return None
Example #6
0
    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
Example #7
0
    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
Example #8
0
    def gui_save_file(self, start_dir=None, default_name=None):
        # pylint: disable-msg=W0703,W0613
        import win32gui

        try:
            fname, _, _ = win32gui.GetSaveFileNameW(File=default_name)
        except Exception as e:
            print(f"Failed to get filename: {e}")
            return None

        return str(fname)
Example #9
0
    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
Example #10
0
    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
Example #11
0
    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
Example #12
0
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)
import win32gui
import win32con
import os

filter = 'Python Scripts\0*.py;*.pyw;*.pys\0Text files\0*.txt\0'
customfilter = 'Other file types\0*.*\0'

fname, customfilter, flags = win32gui.GetSaveFileNameW(
    InitialDir=os.environ['temp'],
    Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER,
    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,
Example #14
0
    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
Example #15
0
import win32gui, win32con, os

filter = "Python Scripts\0*.py;*.pyw;*.pys\0Text files\0*.txt\0"
customfilter = "Other file types\0*.*\0"

fname, customfilter, flags = win32gui.GetSaveFileNameW(
    InitialDir=os.environ["temp"],
    Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER,
    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,
Example #16
0
    def convert(self, object):
        global steamfolder, vtfwidth, vtfheight, fileheight, filewidth, fileheight2, filewidth2, vtfframes, fileframes, transparency, filenames, builder, workingdir, filename2, tgabasename, tgabasename2
        animate = builder.get_object("animated").get_active()
        fade = builder.get_object("fading").get_active()
        gamefolderlist = []
        username = ""
        if filenames[0] == "":
            return
        dirlist = os.listdir(
            r"vtex\materials\vgui\logos")  # clean out old .vtfs
        filelist = [fname for fname in dirlist if fname.endswith(".vtf")]
        for fname in filelist:
            os.unlink(r"vtex\materials\vgui\logos\\" + fname)

        ## check if steam is running
        #out = string.join(os.popen('tasklist').readlines())
        #if out.lower().find("steam.exe")>-1:
        #    pass # steam is running
        #else:
        #    md = gtk.MessageDialog(builder.get_object("window1"),
        #        gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING,
        #        gtk.BUTTONS_CLOSE, "Steam is not running, please start Steam before creating a spray")
        #    md.run()
        #    md.destroy()
        #    return

        # create exception here if the size is to big to create any frames.
        if vtfframes == 0:  # if it has no frames, exit
            return
        spliceleft = 0
        splicetop = 0
        framecount = 0
        framecounter = 0
        background = ""
        splicestring = ""
        splicestring2 = ""

        vtextext = open(r"vtex\materialsrc\vgui\logos\output.txt", "w+")
        vtextext.write('"Startframe" "0"\n')
        vtextext.write('"endframe" "' + str(vtfframes - 1) + '"\n')
        vtextext.close()
        everynthframe = 1  # by default, take every frame
        if vtfframes < fileframes:  # cut some frames out
            everynthframe = float(fileframes) / float(vtfframes)
        if transparency == 2:
            background = "-background transparent -bordercolor transparent "  # pass this string to convert.exe if transparency is enabled
        else:
            background = "-alpha deactivate "  # no transparency, no alpha channel. room for more frames.
        tempw = filewidth / float(vtfwidth)
        temph = fileheight / float(vtfheight)
        if temph > tempw:
            newheight = vtfheight
            newwidth = int(
                round(float(filewidth) * float(vtfheight) / float(fileheight)))
        else:
            newheight = int(
                round(float(fileheight) * float(vtfwidth) / float(filewidth)))
            newwidth = vtfwidth
        topbottomborder = int(round(vtfheight - newheight))
        leftrightborder = int(round(vtfwidth - newwidth))
        if leftrightborder % 2:  # if the border padding isn't an even number, splice an extra pixel of border in.
            spliceleft = 1
        if topbottomborder % 2:
            splicetop = 1
        if spliceleft or splicetop:
            splicestring = "-splice " + str(spliceleft) + "x" + str(
                splicetop) + " "
        if filename2:
            tempw = filewidth2 / float(vtfwidth)
            temph = fileheight2 / float(vtfheight)
            if temph > tempw:
                newheight = vtfheight
                newwidth = int(
                    round(
                        float(filewidth2) * float(vtfheight) /
                        float(fileheight2)))
            else:
                newheight = int(
                    round(
                        float(fileheight2) * float(vtfwidth) /
                        float(filewidth2)))
                newwidth = vtfwidth
            topbottomborder2 = int(round(vtfheight - newheight))
            leftrightborder2 = int(round(vtfwidth - newwidth))
            if leftrightborder2 % 2:  # if the border padding isn't an even number, splice an extra pixel of border in.
                spliceleft = 1
            if topbottomborder2 % 2:
                splicetop = 1
            if spliceleft or splicetop:
                splicestring2 = "-splice " + str(spliceleft) + "x" + str(
                    splicetop) + " "
        else:
            leftrightborder2 = leftrightborder
            topbottomborder2 = topbottomborder
            splicestring2 = splicestring
        tgadir = "tga\\"
        dirlist = os.listdir(tgadir)
        tgalist = [tganame for tganame in dirlist if tganame.endswith(".tga")]
        natsort(tgalist
                )  # natural sort the TGA list to get them in the right order
        vtfname = os.path.basename(
            filenames[0])  # name of vtf without the path
        vmtname = vtfname.rsplit(".")[0] + ".vmt"
        vtfname = vtfname.rsplit(".")[0] + ".vtf"
        if fade:
            if vtfframes == 1:  # no space for 2 frames? exit.
                return
            frame = str(int(builder.get_object("adjustment1").get_value()) - 1)
            frame2 = str(
                int(builder.get_object("adjustment2").get_value()) - 1)
            tganame1 = tgabasename + frame + ".tga"
            if filename2:
                tganame2 = tgabasename2 + frame2 + ".tga"
            else:
                tganame2 = tgabasename + frame2 + ".tga"
            # generate mipmaps
            os.popen("imagemagick\convert -resize " + str(vtfwidth) + "x" +
                     str(vtfheight) + " " + tganame1 +
                     " vtfcmd\\output_00.tga")
            os.popen("imagemagick\convert " + splicestring + background +
                     "-border " + str(int(leftrightborder / 2)) + "x" +
                     str(int(topbottomborder / 2)) +
                     " vtfcmd\\output_00.tga vtfcmd\\output_00.tga")
            os.popen("imagemagick\convert -resize " + str(vtfwidth) + "x" +
                     str(vtfheight) + " " + tganame2 +
                     " vtfcmd\\output_01.tga")
            os.popen("imagemagick\convert " + splicestring2 + background +
                     "-border " + str(int(leftrightborder2 / 2)) + "x" +
                     str(int(topbottomborder2 / 2)) +
                     " vtfcmd\\output_01.tga vtfcmd\\output_01.tga")
            os.popen("imagemagick\convert -resize " + str(vtfwidth / 2) + "x" +
                     str(vtfheight / 2) +
                     " vtfcmd\\output_01.tga vtfcmd\\output_01.tga")
            for i in range(2, 7):
                os.popen("imagemagick\convert -resize " + str(vtfwidth /
                                                              (2**i)) + "x" +
                         str(vtfheight / (2**i)) + " vtfcmd\\output_01.tga" +
                         " vtfcmd\\output_0" + str(i) + ".tga")
            os.popen("vtfcmd\\nvdxt -file vtfcmd\\*.tga -dxt5 -outdir vtfcmd"
                     )  # compile to dxt5 format .dds files
            os.popen("vtfcmd\\stitch vtfcmd\output"
                     )  # stitch .dds files as mipmaps into one .dds texture
            os.popen(
                'vtfcmd\\vpktoolwrap "' + workingdir + '\\vtfcmd\\output.dds"'
            )  # auto-it wrapper for quick and dirty tools, converts .dds to .vtf
            vtfpath = "vtfcmd\\output.vtf"
        elif animate:
            for tganame in tgalist:
                if tganame.find(
                        "-" + str(int(round(framecount)))
                ) > -1:  # process only the frames you need, speeding things up
                    os.popen("imagemagick\convert -resize " + str(vtfwidth) +
                             "x" + str(vtfheight) + " " + tgadir + tganame +
                             " " + "vtex\\materialsrc\\vgui\\logos\\" +
                             tganame)
                    os.popen("imagemagick\convert " + splicestring +
                             background + "-border " +
                             str(int(leftrightborder / 2)) + "x" +
                             str(int(topbottomborder / 2)) +
                             " vtex\\materialsrc\\vgui\\logos\\" + tganame +
                             " vtex\\materialsrc\\vgui\\logos\\" + tganame)
                    shutil.copy(
                        "vtex\\materialsrc\\vgui\\logos\\" + tganame,
                        "vtex\\materialsrc\\vgui\\logos\\output" + '%0*d' %
                        (3, framecounter) + ".tga")
                    framecount = framecount + everynthframe  #advance to next frame
                    framecounter = framecounter + 1
            if filenames[0].find(".gif") > -1 or len(filenames) > 1:
                output = string.join(
                    os.popen(
                        r'vtex\vtex.exe -nopause vtex\materialsrc\vgui\logos\output.txt'
                    ).readlines())  # compile using vtex.exe
            else:
                output = string.join(
                    os.popen(
                        r'vtex\vtex.exe -nopause vtex\materialsrc\vgui\logos\output000.tga'
                    ).readlines())  # single frame
                os.rename("vtex\\materials\\vgui\\logos\output000.vtf",
                          "vtex\\materials\\vgui\\logos\output.vtf")
            vtfpath = "vtex\\materials\\vgui\\logos\\output.vtf"

        if os.path.exists(
                vtfpath
        ) != True:  # if the vtf file doesn't exist, skip the rest.
            return

        username = builder.get_object("combobox1").get_active_text()
        tf2check = builder.get_object("tf2check").get_active()
        csscheck = builder.get_object("csscheck").get_active()
        l4dcheck = builder.get_object("L4Dcheck").get_active()
        l4d2check = builder.get_object("L4D2check").get_active()
        savecheck = builder.get_object("savecheck").get_active()
        line1 = re.compile(r'cl_logofile "(.*)"')
        if tf2check:
            try:
                f = open(
                    steamfolder + "\\steamapps\\" + username +
                    "\\team fortress 2\\tf\\cfg\\game.cfg", 'r')
                filecontents = f.read()
                f.close()
                match = line1.search(filecontents)
                if match:
                    newfilecontents = filecontents.replace(
                        match.group(1),
                        "materials\\vgui\\logos\\" + vtfname + '"')
                    f = open(
                        steamfolder + "\\steamapps\\" + username +
                        "\\team fortress 2\\tf\\cfg\\game.cfg", 'w')
                    f.write(newfilecontents)
                    f.close()
                else:
                    newfilecontents = 'cl_logofile "' + "materials\\vgui\\logos\\" + vtfname + '"'
                    f = open(
                        steamfolder + "\\steamapps\\" + username +
                        "\\team fortress 2\\tf\\cfg\\game.cfg", 'w')
                    f.write(newfilecontents)
                    f.close()
            except:
                pass
            gamefolderlist.append(
                steamfolder + "\\steamapps\\" + username +
                "\\team fortress 2\\tf\\materials\\vgui\\logos\\")
        if csscheck:
            try:
                f = open(
                    steamfolder + "\\steamapps\\" + username +
                    "\\counter-strike source\\cstrike\\cfg\\game.cfg", 'r')
                filecontents = f.read()
                f.close()
                match = line1.search(filecontents)
                if match:
                    newfilecontents = filecontents.replace(
                        match.group(1),
                        "materials\\vgui\\logos\\" + vtfname + '"')
                    f = open(
                        steamfolder + "\\steamapps\\" + username +
                        "\\counter-strike source\\cstrike\\cfg\\game.cfg", 'w')
                    f.write(newfilecontents)
                    f.close()
                else:
                    newfilecontents = 'cl_logofile "' + "materials\\vgui\\logos\\" + vtfname + '"'
                    f = open(
                        steamfolder + "\\steamapps\\" + username +
                        "\\counter-strike source\\cstrike\\cfg\\game.cfg", 'w')
                    f.write(newfilecontents)
                    f.close()
            except:
                pass
            gamefolderlist.append(
                steamfolder + "\\steamapps\\" + username +
                "\\counter-strike source\\cstrike\\materials\\vgui\\logos\\")
        if l4dcheck:
            try:
                f = open(
                    steamfolder +
                    "\\steamapps\\common\\left 4 dead\\left4dead\\cfg\\autoexec.cfg",
                    'r')
                filecontents = f.read()
                f.close()
                match = line1.search(filecontents)
                if match:
                    newfilecontents = filecontents.replace(
                        match.group(1),
                        "materials/vgui/logos/custom/" + vtfname + '"')
                    f = open(
                        steamfolder +
                        "\\steamapps\\common\\left 4 dead\\left4dead\\cfg\\autoexec.cfg",
                        'w')
                    f.write(newfilecontents)
                    f.close()
                else:
                    newfilecontents = filecontents + "\n" + 'cl_logofile "' + "materials/vgui/logos/custom/" + vtfname + '"'
                    f = open(
                        steamfolder +
                        "\\steamapps\\common\\left 4 dead\\left4dead\\cfg\\autoexec.cfg",
                        'w')
                    f.write(newfilecontents)
                    f.close()
            except:
                newfilecontents = 'cl_logofile "' + "materials/vgui/logos/custom/" + vtfname + '"'
                f = open(
                    steamfolder +
                    "\\steamapps\\common\\left 4 dead\\left4dead\\cfg\\autoexec.cfg",
                    'w')
                f.write(newfilecontents)
                f.close()
            gamefolderlist.append(
                steamfolder +
                "\\steamapps\\common\\left 4 dead\\left4dead\\materials\\vgui\\logos\\custom\\"
            )
        if l4d2check:
            try:
                f = open(
                    steamfolder +
                    "\\steamapps\\common\\left 4 dead 2\\left4dead2\\cfg\\autoexec.cfg",
                    'r')
                filecontents = f.read()
                f.close()
                match = line1.search(filecontents)
                if match:
                    newfilecontents = filecontents.replace(
                        match.group(1),
                        "materials/vgui/logos/custom/" + vtfname + '"')
                    f = open(
                        steamfolder +
                        "\\steamapps\\common\\left 4 dead 2\\left4dead2\\cfg\\autoexec.cfg",
                        'w')
                    f.write(newfilecontents)
                    f.close()
                else:
                    newfilecontents = filecontents + "\n" + 'cl_logofile "' + "materials/vgui/logos/custom/" + vtfname + '"'
                    f = open(
                        steamfolder +
                        "\\steamapps\\common\\left 4 dead 2\\left4dead2\\cfg\\autoexec.cfg",
                        'w')
                    f.write(newfilecontents)
                    f.close()
            except:
                newfilecontents = 'cl_logofile "' + "materials/vgui/logos/custom/" + vtfname + '"'
                f = open(
                    steamfolder +
                    "\\steamapps\\common\\left 4 dead 2\\left4dead2\\cfg\\autoexec.cfg",
                    'w')
                f.write(newfilecontents)
                f.close()
            gamefolderlist.append(
                steamfolder +
                "\\steamapps\\common\\left 4 dead 2\\left4dead2\\materials\\vgui\\logos\\custom\\"
            )

        for gamefolder in gamefolderlist:
            if os.path.exists(
                    gamefolder + vtfname
            ):  # if the file of the same name exists, in the game folder
                os.unlink(
                    gamefolder + vtfname
                )  # delete the destination file of the same name, in the game folder

            if os.path.exists(gamefolder + r"\ui") != True:
                if gamefolder.find("\\left4dead") > -1:
                    if os.path.exists(gamefolder + r"\..\ui") != True:
                        os.makedirs(gamefolder + r"\..\ui"
                                    )  # create vgui folder if it doesn't exist
                else:
                    os.makedirs(
                        gamefolder +
                        r"\ui")  # create vgui folder if it doesn't exist

            #output=os.popen(r'copy /y vtex\materials\vgui\logos\output.vtf "'+ gamefolder + vtfname + '"')
            shutil.copy(vtfpath, gamefolder + vtfname)

            #time.sleep(1)
            vmt1 = open(gamefolder + vmtname, "w+")
            vmt1.write('LightmappedGeneric\n')
            vmt1.write('{\n')
            vmt1.write('$basetexture "vgui\logos\custom/' +
                       vtfname.rsplit(".vtf")[0] + '"\n')
            vmt1.write('$translucent 1\n')
            vmt1.write('$decal 1\n')
            vmt1.write('$decalscale "0.250"\n')
            vmt1.write('}\n')
            vmt1.close()

            if gamefolder.find("\\left4dead") > -1:
                vmt2 = open(gamefolder + r"\..\ui\\" + vmtname, "w+")
            else:
                vmt2 = open(gamefolder + r"\ui\\" + vmtname, "w+")
            vmt2.write('"UnlitGeneric"\n')
            vmt2.write('{\n')
            vmt2.write('    "$translucent" 1\n')
            if gamefolder.find("\\left4dead") > -1:
                vmt2.write('    "$basetexture"	"vgui\logos\custom/' +
                           vtfname.rsplit(".vtf")[0] + '"\n')
            else:
                vmt2.write('    "$basetexture"	"vgui\logos/' +
                           vtfname.rsplit(".vtf")[0] + '"\n')
            vmt2.write('    "$vertexcolor" 1\n')
            vmt2.write('    "$vertexalpha" 1\n')
            vmt2.write('    "$no_fullbright" 1\n')
            vmt2.write('    "$ignorez" 1\n')
            vmt2.write('}\n')
            vmt2.close()

            # launch explorer after installation to see how messy the game folder is
            os.spawnl(os.P_NOWAIT, "c:\windows\explorer.exe", "explorer",
                      gamefolder)
        if savecheck:
            filefilter2 = """Spray Files\0*.vtf\0"""
            try:
                filename, customfilter, flags = win32gui.GetSaveFileNameW(
                    InitialDir=".",
                    Flags=win32con.OFN_EXPLORER,
                    File='',
                    DefExt='txt',
                    Title='Save Spray',
                    Filter=filefilter2,
                    FilterIndex=0)
                os.chdir(workingdir)
                shutil.copy(vtfpath, filename)
            except win32gui.error:
                pass