コード例 #1
0
ファイル: morlaframe.py プロジェクト: dasld/morla
def gui_loop() -> None:
    to_open = sys.argv[1] if len(sys.argv) == 2 else ""
    morla_frame = MorlaFrame(to_open)
    exit_status = morla_frame.mainloop()
    if False:
        _cleanup()
    sys.exit(exit_status)
コード例 #2
0
 def close_all_event(self, event=None):
     """ Quit all the PyEditor : called when exiting application """
     while self.editor_list.get_size() > 0:
         reply = self.editor_list.close_current_editor()
         if reply == "cancel":
             break
     if self.editor_list.get_size() == 0:
         sys.exit(0)
コード例 #3
0
ファイル: Application.py プロジェクト: walidsadat/MrPython
    def close_all_event(self, event=None):
        """ Quit all the PyEditor : called when exiting application """

        print("MrPython says 'bye bye!' ...")
        while self.editor_list.get_size() > 0:
            reply = self.editor_list.close_current_editor()
            if reply == "cancel":
                break
        if self.editor_list.get_size() == 0:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive():                
                self.running_interpreter_proxy.process.terminate()
                self.running_interpreter_proxy.process.join()
            sys.exit(0)
コード例 #4
0
ファイル: Application.py プロジェクト: fredokun/MrPython
    def close_all_event(self, event=None):
        """ Quit all the PyEditor : called when exiting application """

        print("MrPython says 'bye bye!' ...")
        while self.editor_list.get_size() > 0:
            reply = self.editor_list.close_current_editor()
            if reply == "cancel":
                break
        if self.editor_list.get_size() == 0:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive():                
                self.running_interpreter_proxy.process.terminate()
                self.running_interpreter_proxy.process.join()
            sys.exit(0)
コード例 #5
0
def Autoclick():
    global activate
    if not (activate):
        activate = True
        global score
        global au_price
        global au_multy
        if score >= au_price:
            score -= au_price
            au_price *= 4
            deltext(text3)
            instext("Auto upgrade\nprice: " + str(au_price), text3)
            while True:
                score += 1 * au_multy
                deltext(text1)
                instext("Your score: " + str(score), text1)
                if score >= 10000000:
                    instext("Congratulations!!!\nYOU WIN!", textend)
                    time.sleep(10)
                    sys.exit()
                time.sleep(1)
コード例 #6
0
    return ((e_x > p_x and e_x < (p_x + player_size)) or
            (p_x > e_x and p_x <=
             (e_x + enemy_size))) and ((e_y > p_y and e_y <
                                        (p_y + player_size)) or
                                       (p_y > e_y and p_y <=
                                        (e_y + enemy_size)))


pressed_keys = {"left": False, "right": False, "up": False, "down": False}
while not game_over:
    x = player_pos[0]
    y = player_pos[1]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT:
                pressed_keys["left"] = True
            if event.key == pygame.K_RIGHT:
                pressed_keys["right"] = True
            if event.key == pygame.K_UP:
                pressed_keys["up"] = True
            if event.key == pygame.K_DOWN:
                pressed_keys["down"] = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                pressed_keys["left"] = False
            if event.key == pygame.K_RIGHT:
コード例 #7
0
                value = str(value)
            except ValueError:
                print(f"> couldn't convert {value} to str!")
                raise
            else:
                print(f"> converting {value} to str...")
        self[USER][key] = value

    def save(self, name: str = "preferences", where: str = None):
        if not where:
            where = self.directory
        with Cd(where):
            filename = name + ".ini"
            with open(filename, "w") as prefs_file:
                try:
                    self.write(prefs_file)
                    # json.dump(self.dict, json_file)
                except:
                    print(f"> Writing {filename} failed.")
                    raise
                else:
                    print(f"> Wrote {filename}.")
            print_sep()
            with open(filename, "r") as prefs_file:
                print(prefs_file.read().strip())
            print_sep()


if __name__ == "__main__":
    sys.exit("This module should not be run alone.")
コード例 #8
0
def do_download(manifest):
    if manifest == '':
        print_text("Select a manifest file first!")
        return None
    manifest_path = Path(manifest)
    target_dir_path = manifest_path.parent

    manifest_text = manifest_path.open().read()
    manifest_text = manifest_text.replace('\r', '').replace('\n', '')

    manifest_json = json.loads(manifest_text)

    try:
        if not "minecraftModpack" == manifest_json['manifestType']:
            print_text('Manifest Error. manifestType is not "minecraftModpack"')
            return None
    except KeyError as e:
        print_text('I got a KeyError - reason %s' % str(e))
        print_text("Manifest Error. Make sure you selected a valid pack manifest.json")
        return None

    try:
        override_path = Path(target_dir_path, manifest_json['overrides'])
        minecraft_path = Path(target_dir_path, "minecraft")
        mods_path = minecraft_path / "mods"
    except KeyError as e:
        print_text('I got a KeyError - reason %s' % str(e))
        print_text("Manifest Error. Make sure you selected a valid pack manifest.json")
        return None

    if override_path.exists():
        shutil.move(str(override_path), str(minecraft_path))

    downloader_dirs = appdirs.AppDirs(appname="cursePackDownloader", appauthor="portablejim")
    cache_path = Path(downloader_dirs.user_cache_dir, "curseCache")

    # Attempt to set proper portable data directory if asked for
    if args.portable:
        if getattr(sys, 'frozen', False):
            # if frozen, get embeded file
            cache_path = Path(os.path.join(os.path.dirname(sys.executable), 'curseCache'))
        else:
            if '__file__' in globals():
                cache_path = Path(os.path.dirname(os.path.realpath(__file__)), "curseCache")
            else:
                print_text("Portable data dir not supported for interpreter environment")
                sys.exit(2)

    if not cache_path.exists():
        cache_path.mkdir(parents=True)

    if not minecraft_path.exists():
        minecraft_path.mkdir()

    if not mods_path.exists():
        mods_path.mkdir()

    i = 1
    try:
        i_len = len(manifest_json['files'])
    except KeyError as e:
        print_text('I got a KeyError - reason %s' % str(e))
        print_text("Manifest Error. Make sure you selected a valid pack manifest.json")
        return None

    print_text("Cached files are stored here:\n %s\n" % cache_path)
    print_text("%d files to download" % i_len)
    if args.gui:
        programGui.tl_progress["maximum"] = i_len
    for dependency in manifest_json['files']:
        dep_cache_dir = cache_path / str(dependency['projectID']) / str(dependency['fileID'])
        if dep_cache_dir.is_dir():
            # File is cached
            dep_files = [f for f in dep_cache_dir.iterdir()]
            if len(dep_files) >= 1:
                dep_file = dep_files[0]
                target_file = minecraft_path / "mods" / dep_file.name
                shutil.copyfile(str(dep_file), str(target_file))
                print_text("[%d/%d] %s (cached)" % (i, i_len, target_file.name))

                i += 1
                if args.gui:
                    programGui.tl_progress["value"] = i

                # Cache access is successful,
                # Don't download the file
                continue

        # File is not cached and needs to be downloaded

        temp_mod_file = str(minecraft_path / temp_file_name)
        if Path(temp_mod_file).exists():
            os.remove(temp_mod_file)

        project_response = sess.get("http://minecraft.curseforge.com/projects/%s"
                                    % (dependency['projectID']), stream=True)
        project_response.url = project_response.url.replace('?cookieTest=1', '')
        file_response = sess.get("%s/files/%s/download"
                                 % (project_response.url, dependency['fileID']), stream=True)
        requested_file_sess = sess.get(file_response.url, stream=True)

        remote_url = Path(requested_file_sess.url)
        file_name = unquote(remote_url.name).split('?')[0]  # If query data strip it and return just the file name.
        # print_text(str(requested_file_sess.status_code))
        # print_text(str(requested_file_sess.headers['content-type']))
        if (requested_file_sess.status_code == 404) or (file_name == "download"):
            print_text(str("[%d/%d] " + "Trying to resolve using alternate requesting.") % (i, i_len))

            # If curse website fails to provide correct url try Dries API list.
            # get the json from Dries:
            metabase = "https://cursemeta.dries007.net"
            metaurl = "%s/%s/%s.json" % (metabase, dependency['projectID'], dependency['fileID'])
            r = sess.get(metaurl)
            r.raise_for_status()
            main_json = r.json()
            if "code" in main_json:
                print_text(str("[%d/%d] " + "ERROR FILE MISSING FROM SOURCE") % (i, i_len))
                erred_mod_downloads.append(metaurl.url)
                i += 1
                continue
            fileurl = main_json["DownloadURL"]
            file_name = main_json["FileNameOnDisk"]
            requested_file_sess = sess.get(fileurl, stream=True)

        try:
            full_file_size = int(requested_file_sess.headers.get('content-length'))
            # print_text(str(requested_file_sess.headers['content-length']))
        except TypeError:
            print_text(str("[%d/%d] " + "MISSING FILE SIZE") % (i, i_len))
            full_file_size = 100

        print_text(str("[%d/%d] " + file_name +
                   " (DL: " + get_human_readable(full_file_size) + ")") % (i, i_len))
        time.sleep(0.1)

        with open(temp_mod_file, 'wb') as file_data:
            dl = 0
            widgets = [Percentage(), Bar(), ' ', AdaptiveETA()]
            pbar = ProgressBar(widgets=widgets, maxval=full_file_size)
            if args.gui:
                programGui.dl_progress["maximum"] = full_file_size
            # maybe do something
            if enableTxtProgressBar:
                pbar.start()
            for chunk in requested_file_sess.iter_content(chunk_size=1024):
                if dl < full_file_size:
                    dl += len(chunk)
                elif dl > full_file_size:
                    dl = full_file_size
                if enableTxtProgressBar:
                    pbar.update(dl)
                if args.gui:
                    programGui.dl_progress["value"] = dl
                if chunk:  # filter out keep-alive new chunks
                    file_data.write(chunk)
            if enableTxtProgressBar:
                pbar.finish()
            if args.gui:
                programGui.dl_progress["value"] = 0
            file_data.close()
        shutil.move(temp_mod_file, str(mods_path / file_name))  # Rename from temp to correct file name.

        # Try to add file to cache.
        if not dep_cache_dir.exists():
            dep_cache_dir.mkdir(parents=True)
            shutil.copyfile(str(mods_path / file_name), str(dep_cache_dir / file_name))

        i += 1
        if args.gui:
            programGui.tl_progress["value"] = i

    # This is not available in curse-only packs
    if 'directDownload' in manifest_json:
        i = 1
        i_len = len(manifest_json['directDownload'])
        programGui.set_output("%d additional files to download." % i_len)
        for download_entry in manifest_json['directDownload']:
            if "url" not in download_entry or "filename" not in download_entry:
                programGui.set_output("[%d/%d] <Error>" % (i, i_len))
                i += 1
                continue
            source_url = urlparse(download_entry['url'])
            download_cache_children = Path(source_url.path).parent.relative_to('/')
            download_cache_dir = cache_path / "directdownloads" / download_cache_children
            cache_target = Path(download_cache_dir / download_entry['filename'])
            if cache_target.exists():
                # Cached
                target_file = minecraft_path / "mods" / cache_target.name
                shutil.copyfile(str(cache_target), str(target_file))

                i += 1
                if args.gui:
                    programGui.tl_progress["value"] = i

                # Cache access is successful,
                # Don't download the file
                continue
            # File is not cached and needs to be downloaded
            file_response = sess.get(source_url, stream=True)
            while file_response.is_redirect:
                source = file_response
                file_response = sess.get(source, stream=True)
            programGui.set_output("[%d/%d] %s" % (i, i_len, download_entry['filename']))
            with open(str(minecraft_path / "mods" / download_entry['filename']), "wb") as mod:
                mod.write(file_response.content)

            i += 1
            if args.gui:
                programGui.tl_progress["value"] = i

        if args.gui:
            programGui.tl_progress["value"] = 0

    if len(erred_mod_downloads) is not 0:
        print_text("\n!! WARNING !!\nThe following mod downloads failed.")
        for index in erred_mod_downloads:
            print_text("- " + index)
        # Create log of failed download links to pack manifest directory for user to inspect manually.
        log_file = open(str(target_dir_path / "cursePackDownloaderModErrors.log"), 'w')
        log_file.write("\n".join(str(elem) for elem in erred_mod_downloads))
        log_file.close()
        print_text("See log in manifest directory for list.\n!! WARNING !!\n")
        erred_mod_downloads.clear()

    print_text("Unpacking Complete")
    sess.close()
コード例 #9
0
        erred_mod_downloads.clear()

    print_text("Unpacking Complete")
    sess.close()


if args.gui:
    programGui = DownloadUI()
    if args.manifest is not None:
        programGui.set_manifest(args.manifest)
    programGui.root.mainloop()
else:
    programGui = HeadlessUI()
    if args.manifest is not None:
        do_download(args.manifest)
    else:
        if sys.platform == "win32":
            if compiledExecutable:
                print('C:\someFolder\cursePackDownloader.exe '
                      '--portable '
                      '--nogui '
                      '--manifest ["/path/to/manifest.json"]')
                sys.exit()
            else:
                print(
                    'CMD>"path/to/python" "/path/to/downloader.py" '
                    '--portable '
                    '--nogui '
                    '--manifest ["/path/to/manifest.json"]')
                sys.exit()
コード例 #10
0
def do_download(manifest):
    if manifest == '':
        print_text("Select a manifest file first!")
        return None
    manifest_path = Path(manifest)
    target_dir_path = manifest_path.parent

    manifest_text = manifest_path.open().read()
    manifest_text = manifest_text.replace('\r', '').replace('\n', '')

    manifest_json = json.loads(manifest_text)

    try:
        if not "minecraftModpack" == manifest_json['manifestType']:
            print_text(
                'Manifest Error. manifestType is not "minecraftModpack"')
            return None
    except KeyError as e:
        print_text('I got a KeyError - reason %s' % str(e))
        print_text(
            "Manifest Error. Make sure you selected a valid pack manifest.json"
        )
        return None

    try:
        override_path = Path(target_dir_path, manifest_json['overrides'])
        minecraft_path = Path(target_dir_path, "minecraft")
        mods_path = minecraft_path / "mods"
    except KeyError as e:
        print_text('I got a KeyError - reason %s' % str(e))
        print_text(
            "Manifest Error. Make sure you selected a valid pack manifest.json"
        )
        return None

    if override_path.exists():
        shutil.move(str(override_path), str(minecraft_path))

    downloader_dirs = appdirs.AppDirs(appname="cursePackDownloader",
                                      appauthor="portablejim")
    cache_path = Path(downloader_dirs.user_cache_dir, "curseCache")

    # Attempt to set proper portable data directory if asked for
    if args.portable:
        if getattr(sys, 'frozen', False):
            # if frozen, get embeded file
            cache_path = Path(
                os.path.join(os.path.dirname(sys.executable), 'curseCache'))
        else:
            if '__file__' in globals():
                cache_path = Path(os.path.dirname(os.path.realpath(__file__)),
                                  "curseCache")
            else:
                print_text(
                    "Portable data dir not supported for interpreter environment"
                )
                sys.exit(2)

    if not cache_path.exists():
        cache_path.mkdir(parents=True)

    if not minecraft_path.exists():
        minecraft_path.mkdir()

    if not mods_path.exists():
        mods_path.mkdir()

    sess = requests.session()

    i = 1
    try:
        i_len = len(manifest_json['files'])
    except KeyError as e:
        print_text('I got a KeyError - reason %s' % str(e))
        print_text(
            "Manifest Error. Make sure you selected a valid pack manifest.json"
        )
        return None

    print_text("Cached files are stored here:\n %s\n" % cache_path)
    print_text("%d files to download" % i_len)

    for dependency in manifest_json['files']:
        dep_cache_dir = cache_path / str(dependency['projectID']) / str(
            dependency['fileID'])
        if dep_cache_dir.is_dir():
            # File is cached
            dep_files = [f for f in dep_cache_dir.iterdir()]
            if len(dep_files) >= 1:
                dep_file = dep_files[0]
                target_file = minecraft_path / "mods" / dep_file.name
                shutil.copyfile(str(dep_file), str(target_file))
                print_text("[%d/%d] %s (cached)" %
                           (i, i_len, target_file.name))

                i += 1

                # Cache access is successful,
                # Don't download the file
                continue

        # File is not cached and needs to be downloaded
        project_response = sess.get(
            "http://minecraft.curseforge.com/mc-mods/%s" %
            (dependency['projectID']),
            stream=True)
        project_response.url = project_response.url.replace(
            '?cookieTest=1', '')
        file_response = sess.get("%s/files/%s/download" %
                                 (project_response.url, dependency['fileID']),
                                 stream=True)
        while file_response.is_redirect:
            source = file_response
            file_response = sess.get(source, stream=True)
        file_path = Path(file_response.url)
        file_name = unquote(file_path.name)
        print_text("[%d/%d] %s" % (i, i_len, file_name))
        with open(str(minecraft_path / "mods" / file_name), "wb") as mod:
            mod.write(file_response.content)

        # Try to add file to cache.
        if not dep_cache_dir.exists():
            dep_cache_dir.mkdir(parents=True)
        with open(str(dep_cache_dir / file_name), "wb") as mod:
            mod.write(file_response.content)

        i += 1

    # This is not available in curse-only packs
    if 'directDownload' in manifest_json:
        i = 1
        i_len = len(manifest_json['directDownload'])
        programGui.set_output("%d additional files to download." % i_len)
        for download_entry in manifest_json['directDownload']:
            if "url" not in download_entry or "filename" not in download_entry:
                programGui.set_output("[%d/%d] <Error>" % (i, i_len))
                i += 1
                continue
            source_url = urlparse(download_entry['url'])
            download_cache_children = Path(
                source_url.path).parent.relative_to('/')
            download_cache_dir = cache_path / "directdownloads" / download_cache_children
            cache_target = Path(download_cache_dir /
                                download_entry['filename'])
            if cache_target.exists():
                # Cached
                target_file = minecraft_path / "mods" / cache_target.name
                shutil.copyfile(str(cache_target), str(target_file))

                i += 1

                # Cache access is successful,
                # Don't download the file
                continue
            # File is not cached and needs to be downloaded
            file_response = sess.get(source_url, stream=True)
            while file_response.is_redirect:
                source = file_response
                file_response = sess.get(source, stream=True)
            programGui.set_output("[%d/%d] %s" %
                                  (i, i_len, download_entry['filename']))
            with open(
                    str(minecraft_path / "mods" / download_entry['filename']),
                    "wb") as mod:
                mod.write(file_response.content)

            i += 1

    print_text("Unpacking Complete")