From 9642555458e1f5828d73cb3c0f0f964fd4fa3d81 Mon Sep 17 00:00:00 2001 From: Oleh Onyshchenko <110289150+seesmof@users.noreply.github.com> Date: Fri, 22 Dec 2023 11:20:27 +0200 Subject: [PATCH] feat: add loading from file --- src/ui/ui.py | 32 +++++++++++++++++++++++++++++--- src/util/utils.py | 19 +++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/ui/ui.py b/src/ui/ui.py index a361ac5..e6ea796 100644 --- a/src/ui/ui.py +++ b/src/ui/ui.py @@ -4,7 +4,7 @@ console = Console() -from util.utils import getCurrentMetrics, showPopularWords +from util.utils import getCurrentMetrics, getTextFromFile, showPopularWords def updateMetrics( @@ -97,7 +97,26 @@ def renderButtonsSection(root) -> tuple[CTkLabel, CTkButton, CTkButton, CTkButto loadTextFromFileButton.place(x=210, y=260) saveTextToFileButton.place(x=210, y=300) - return interactWithTextHeading, showMostPopularWordsButton, loadTextFromFileButton + return ( + interactWithTextHeading, + showMostPopularWordsButton, + loadTextFromFileButton, + saveTextToFileButton, + ) + + +def loadTextFromFile( + textField: CTkTextbox, + resultsLines: CTkLabel, + resultsSymbols: CTkLabel, + resultsWords: CTkLabel, + resultsReadingTime: CTkLabel, +) -> None: + textFromFile = getTextFromFile() + textField.insert("0.0", textFromFile) + updateMetrics( + textFromFile, resultsLines, resultsSymbols, resultsWords, resultsReadingTime + ) def renderMainTab(root) -> None: @@ -115,14 +134,21 @@ def renderMainTab(root) -> None: interactWithTextHeading, showMostPopularWordsButton, loadTextFromFileButton, + saveTextToFileButton, ) = renderButtonsSection(root) showMostPopularWordsButton.configure( command=lambda: showPopularWords(getTextInput.get("0.0", "end")) ) loadTextFromFileButton.configure( - command=lambda: console.print("TODO: load text from file") + command=lambda: loadTextFromFile( + getTextInput, resultsLines, resultsSymbols, resultsWords, resultsReadingTime + ) ) + saveTextToFileButton.configure( + command=lambda: console.print("TODO: save text to file") + ) + getTextInput.bind( "", lambda event: updateMetrics( diff --git a/src/util/utils.py b/src/util/utils.py index 3928aad..29a502d 100644 --- a/src/util/utils.py +++ b/src/util/utils.py @@ -1,6 +1,7 @@ from collections import defaultdict from math import ceil from rich.console import Console +from customtkinter import * from components.AlertPopup import AlertPopup @@ -78,3 +79,21 @@ def getCurrentMetrics(text) -> tuple[int, int, int, int]: timeToRead = ceil(wordsCount / 200) return lines, linesCount, symbolsCount, wordsCount, timeToRead + + +def readTextFromFile(filePath): + try: + with open(filePath, "r") as f: + text = f.read() + except Exception as e: + console.print(e) + text = "" + return text + + +def getTextFromFile(): + getFilePath = CTkInputDialog(text="Enter file path", title="Load Text") + filePath = getFilePath.get_input() + textFromFile = readTextFromFile(filePath) + + return textFromFile