Exemplo n.º 1
0
 def send_sync_status(self, state: DocPair, path: Path, /) -> None:
     shell.SHChangeNotify(
         shellcon.SHCNE_UPDATEITEM,
         shellcon.SHCNF_PATH | shellcon.SHCNF_FLUSH,
         force_encode(str(path)),
         None,
     )
Exemplo n.º 2
0
def shell_change_notify():
    """Notify the Windows shell of update.

    Used in windows_explorer.xml."""
    shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST,
                         None, None)
    return 0
Exemplo n.º 3
0
def refresh_shell_cache():
    # Refresh the icon cache:
    shell.SHChangeNotify(
        shellcon.SHCNE_ASSOCCHANGED,
        shellcon.SHCNF_IDLIST | shellcon.SHCNF_FLUSH,
        None,
        None,
    )
Exemplo n.º 4
0
def do_refresh_on_shell_view(pidl):
    """
    Does not work now.
    TODO: fix to avoid manual refreshing folders in Windows Explorer

    Got from:
    https://stackoverflow.com/questions/29004302/refreshing-a-folder-that-doesnt-exist-in-the-file-system
    """
    if REFRESH_ENABLED:
        console("refresh...")
        shell.SHChangeNotify(shellcon.SHCNE_MKDIR,
                             shellcon.SHCNF_IDLIST | shellcon.SHCNF_FLUSH,
                             pidl, None)
        shell.SHChangeNotify(shellcon.SHCNE_CREATE,
                             shellcon.SHCNF_IDLIST | shellcon.SHCNF_FLUSH,
                             pidl, None)
        shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED,
                             shellcon.SHCNF_IDLIST | shellcon.SHCNF_FLUSH,
                             pidl, None)
        console("done.")
Exemplo n.º 5
0
    def SetupLaunchIntegration(self, extensions):
        traits = G_LaunchTraits
        self._SetupProgId(traits)
        self._SetupStartMenu(traits)

        for extension in extensions:
            self._SetupFileOpenWith("." + extension, traits)

        if self._Changed:
            shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED,
                                 shellcon.SHCNF_IDLIST, None, None)
Exemplo n.º 6
0
    def SetupAppIntegration(self):
        # see https://docs.microsoft.com/en-us/windows/desktop/shell/intro

        traits = G_AppTraits
        self._SetupProgId(traits)
        self._SetupFileOpen(traits)
        self._SetupStartMenu(traits)

        if self._Changed:
            shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED,
                                 shellcon.SHCNF_IDLIST, None, None)
Exemplo n.º 7
0
def RegisterPythonwin(register=True):
    """ Add (or remove) Pythonwin to context menu for python scripts.
        ??? Should probably also add Edit command for pys files also.
        Also need to remove these keys on uninstall, but there's no function
            like file_created to add registry entries to uninstall log ???
    """
    import os
    import distutils.sysconfig

    lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1)
    classes_root = get_root_hkey()
    # Installer executable doesn't seem to pass anything to postinstall script
    # indicating if it's a debug build,
    pythonwin_exe = os.path.join(lib_dir, "Pythonwin", "Pythonwin.exe")
    pythonwin_edit_command = pythonwin_exe + ' /edit "%1"'

    keys_vals = [
        ('Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Pythonwin.exe',
         '', pythonwin_exe),
        ('Software\\Classes\\Python.File\\shell\\Edit with Pythonwin',
         'command', pythonwin_edit_command),
        ('Software\\Classes\\Python.NoConFile\\shell\\Edit with Pythonwin',
         'command', pythonwin_edit_command),
    ]

    try:
        if register:
            for key, sub_key, val in keys_vals:
                # Since winreg only uses the character Api functions, this can fail if Python
                # is installed to a path containing non-ascii characters
                hkey = winreg.CreateKey(classes_root, key)
                if sub_key:
                    hkey = winreg.CreateKey(hkey, sub_key)
                winreg.SetValueEx(hkey, None, 0, winreg.REG_SZ, val)
                hkey.Close()
        else:
            for key, sub_key, val in keys_vals:
                try:
                    winreg.DeleteKey(classes_root, key)
                except OSError as why:
                    winerror = getattr(why, 'winerror', why.errno)
                    if winerror != 2:  # file not found
                        raise
    finally:
        # tell windows about the change
        from win32com.shell import shell, shellcon
        shell.SHChangeNotify(
            shellcon.SHCNE_ASSOCCHANGED,
            shellcon.SHCNF_IDLIST,
            None,
            None)
Exemplo n.º 8
0
def shell_notify(paths):
    '''
    Refresh Windows shell when file states change.  This allows
    the explorer to refresh their icons based on their new state
    '''
    if not os.name == 'nt':
        return
    try:
        from win32com.shell import shell, shellcon
        for path in paths:
            abspath = os.path.abspath(path)
            pidl, ignore = shell.SHILCreateFromPath(abspath, 0)
            shell.SHChangeNotify(shellcon.SHCNE_UPDATEITEM, 
                                 shellcon.SHCNF_IDLIST | shellcon.SHCNF_FLUSHNOWAIT,
                                 pidl, None)
    except ImportError:
        pass
Exemplo n.º 9
0
def register():
    base = os.path.dirname(sys.executable)

    for program, data in default_programs().iteritems():
        data = data.copy()
        exe = os.path.join(base, program)
        capabilities_path = cap_path(data)
        ext_map = {
            ext.lower(): guess_type('file.' + ext.lower())[0]
            for ext in extensions(program)
        }
        ext_map = {ext: mt for ext, mt in ext_map.iteritems() if mt}
        prog_id_map = {
            ext: progid_name(data['assoc_name'], ext)
            for ext in ext_map
        }

        with Key(capabilities_path) as key:
            for k, v in {
                    'ApplicationDescription': 'description',
                    'ApplicationName': 'name'
            }.iteritems():
                key.set(k, data[v])
            key.set('ApplicationIcon', '%s,0' % exe)
            key.set_default_value(r'shell\open\command', '"%s" "%%1"' % exe)

            with Key('FileAssociations',
                     root=key) as fak, Key('MimeAssociations',
                                           root=key) as mak:
                # previous_associations = set(fak.itervalues())
                for ext, prog_id in prog_id_map.iteritems():
                    mt = ext_map[ext]
                    fak.set('.' + ext, prog_id)
                    mak.set(mt, prog_id)
        for ext, prog_id in prog_id_map.iteritems():
            create_prog_id(ext, prog_id, ext_map, exe)

        with Key(r'Software\RegisteredApplications') as key:
            key.set(data['name'], capabilities_path)

    from win32com.shell import shell, shellcon
    shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED,
                         shellcon.SHCNF_DWORD | shellcon.SHCNF_FLUSH, 0, 0)
Exemplo n.º 10
0
#‘path’가 네트워크 드라이브에 있는지 확인하는 함수 
def path_on_network(path):
    """Check whether 'path' is on a network drive"""
    if len(os.path.splitunc(path)[0]) > 0:
        return True
    drive = os.path.splitdrive(path)[0] + '\\'
    return win32file.GetDriveType(drive) == win32file.DRIVE_REMOTE

#Windows 업데이트를 shell에 알리는 함수
def shell_change_notify():
    """Notify the Windows shell of update.
    
    Window_Thomer.xml에 사용된다.. 
    Used in windows_explorer.xml."""
    shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST,
                         None, None)
    return 0
                        
#CleanerML 및 Winapp2.ini에서 사용할 환경 변수를 정의하는 함수
def set_environ(varname, path):
    """Define an environment variable for use in CleanerML and Winapp2.ini"""
    if not path:
        return
    if varname in os.environ:
        #logger.debug('set_environ(%s, %s): skipping because environment variable is already defined', varname, path)
        if 'nt' == os.name:
            os.environ[varname] = bleachbit.expandvars(u'%%%s%%' % varname).encode('utf-8')
        # Do not redefine the environment variable when it already exists
        # But re-encode them with utf-8 instead of mbcs
        return
    try:
Exemplo n.º 11
0
 def updateDir(path):
     pidl, _ = shell.SHILCreateFromPath(path, 0)
     shell.SHChangeNotify(shellcon.SHCNE_UPDATEDIR,
                          shellcon.SHCNF_IDLIST | shellcon.SHCNF_FLUSH,
                          pidl,
                          None)
Exemplo n.º 12
0
 def notifyPathnameStatusChange(self, pathname, new_status, extras=None):
     shell.SHChangeNotify(shellcon.SHCNE_UPDATEITEM, shellcon.SHCNF_PATHW,
                          self._get_absolute_pathname(pathname), None)
Exemplo n.º 13
0
Klemperer (Cohen)
""",
    '7 Hamilton': """\
water filter
""",
}

from string import split

for table in tables:
    print >> todayFile, '<table width="100%" cellspacing="5">'
    print >> todayFile, '<tr><th colspan="3" align="center">%s</th></tr>' % table
    items = [item for item in split(tables[table], '\n') if item] + 3 * ['-']
    for start in range(0, len(items), 3):
        if items[start] != '-':
            print >> todayFile, '<tr>',
            for item in items[start:start + 3]:
                print >> todayFile, '<td>%s</td>' % item
        print >> todayFile, '</tr>'
    print >> todayFile, '</table>'

todayFile.close()

from win32com.shell.shellcon import *
from win32com.shell import shell

# SHChangeNotify should, I understand, be content with None in each of the final two arguments
# However, since it's not ...
lpil = shell.SHGetSpecialFolderLocation(0, CSIDL_DESKTOP)
shell.SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, lpil, lpil)
Exemplo n.º 14
0
def main_imp():
    #/
    parser = parser_make()

    #/
    args_obj = parser.parse_args()

    #/
    ensure_spec(parser, ARG_SPEC)

    #/
    ver_on = getattr(args_obj, ARG_VER_ON_K)

    #/
    if ver_on:
        #/
        print(__version__)

        #/
        return MAIN_RET_V_VER_SHOW_OK

    #/ 4hnADY0
    args_obj = parser.parse_args()
    #/ 4e0PxM6
    ## Exit here if arguments are incorrect

    #/ 5i6GFQ8
    config_file_path = getattr(args_obj, ARG_CONFIG_PATH_K)

    try:
        #/ 6tY207f
        with open(config_file_path, mode='rb') as config_file_obj:
            #/ 8g0anQk
            try:
                dict_obj = yaml.load(config_file_obj)
            except Exception:

                #/ 4u4Bhxf
                sys.stderr.write('#/ Error\n')
                sys.stderr.write('Parsing config file failed.\n')

                #/ 2axbv0h
                return MAIN_RET_V_PARSING_CONFIG_FILE_FAILED

    except Exception:
        #/ 3s9B4lm
        sys.stderr.write('#/ Error')
        sys.stderr.write('Reading config file failed.')

        #/ 9cqrvjt
        return MAIN_RET_V_OPENING_CONFIG_FILE_FAILED

    #/
    var_d = dict_obj[CFG_K_VAR_D]

    ext_info_s = dict_obj[CFG_K_EXT_INFO_D]

    #/ 2iPQrhI
    owp_del = getattr(args_obj, ARG_OWP_DEL_K)

    res_txt = config_parse(
        ext_info_s,
        var_d,
        owp_del=owp_del,
    )

    res_txt_utf8 = res_txt.encode(
        'utf8') if sys.version_info[0] > 2 else res_txt

    #/ 4p6J0rK
    import_on = getattr(args_obj, ARG_IMPORT_ON_K)

    if not import_on:
        #/ 7xyc66b
        stdout_write_bytes(b'REGEDIT4\n')

        stdout_write_bytes(res_txt_utf8)

        #/ 7mHikdk
        return MAIN_RET_V_PRODUCING_REGISTRY_DATA_OK

    #/ 2jkggbB
    assert import_on

    sys.stderr.write('#/ Import to Windows Registry\n')

    reg_file_path = None

    ret_code = None

    try:
        #/ 3jYbKK0
        file_obj = tempfile.NamedTemporaryFile(delete=False)
        ## 6nOuOHjB
        ## Note on Windows, the temp file is not created until |close| is called.
        ## But by default when |close| is called, the file is deleted.
        ## In order to get access to the temp file, have to use |delete=False|
        ##  and manually delete the file after job done.

        reg_file_path = file_obj.name

        file_obj.write(b'REGEDIT4\n')
        file_obj.write(res_txt_utf8)
        file_obj.close()

        #/ 2thKJr6
        proc_obj = subprocess.Popen(['regedit', '/s', reg_file_path],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

        ret_output = proc_obj.communicate()

        ret_code = proc_obj.returncode
    finally:
        if reg_file_path:
            try:
                os.unlink(reg_file_path)
            except:
                pass

    #/ 9a7gWwP
    if ret_code == 0:
        #/ 8tBWx3Y
        sys.stderr.write('Ok\n')
    else:
        #/ 3oGPSzN
        sys.stderr.write('Failed\n')

        stderr_bytes = ret_output[1]

        sys.stderr.write(stderr_bytes)
        sys.stderr.write('\n')

        #/ 4tlxev2
        return MAIN_RET_V_IMPORTING_TO_REGISTRY_FAILED

    #/ 6hVotpt
    sys.stderr.write(
        '#/ Send shell change notification, to make changes take effect.\n')

    #/ 3djlJqJ
    try:
        import win32com.shell.shell as shell  #@UnresolvedImport
        import win32com.shell.shellcon as shellcon  #@UnresolvedImport
    except ImportError:
        #/ 9jmnJR7
        sys.stderr.write(r"""Failed. Changes may not take effects immediately.
Error:
Importing |win32com| failed.
Please install |pywin32|.
Download is available at http://sourceforge.net/projects/pywin32/files/pywin32/
""")

        #/ 3d4HYyD
        return MAIN_RET_V_IMPORTING_WIN32COM_FAILED

    #/ 7bldEFK
    shell.SHChangeNotify(
        shellcon.SHCNE_ASSOCCHANGED,
        shellcon.SHCNF_IDLIST,
        None,
        None,
    )

    #/ 4gNKPDp
    sys.stderr.write('OK\n')

    #/ 3wGMLbJ
    return MAIN_RET_V_IMPORTING_TO_REGISTRY_OK
Exemplo n.º 15
0
#This script will programmatically eject a removable storage drive for windows
#It first dismounts teh filesystem then ejects the media

import win32api, win32gui, win32con, win32file, struct

FSCTL_LOCK_VOLUME = 0x0090018
FSCTL_DISMOUNT_VOLUME = 0x00090020
IOCTL_STORAGE_MEDIA_REMOVAL = 0x002D4804
IOCTL_STORAGE_EJECT_MEDIA = 0x002D4808


lpFileName = r"\\.\F:"
dwDesiredAccess = win32con.GENERIC_READ|win32con.GENERIC_WRITE
dwShareMode = win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE
dwCreationDisposition = win32con.OPEN_EXISTING

hVolume = win32file.CreateFile(lpFileName, dwDesiredAccess, dwShareMode, None, dwCreationDisposition, 0, None)
win32file.DeviceIoControl(hVolume, FSCTL_LOCK_VOLUME, "", 0, None)
win32file.DeviceIoControl(hVolume, FSCTL_DISMOUNT_VOLUME, "", 0, None)
try:
	win32file.DeviceIoControl(hVolume, IOCTL_STORAGE_MEDIA_REMOVAL, struct.pack("B", 0), 0, None)
	win32file.DeviceIoControl(hVolume, IOCTL_STORAGE_EJECT_MEDIA, "", 0, None)
except:
	raise
finally:
	win32file.CloseHandle(hVolume)

from win32com.shell import shell, shellcon 
shell.SHChangeNotify(shellcon.SHCNE_DRIVEREMOVED, shellcon.SHCNF_PATH, 
"F:\\")