computer-use-ootb-internal 0.0.188__py3-none-any.whl → 0.0.190__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,112 +1,112 @@
1
- import os
2
- import platform
3
- import subprocess
4
- import logging
5
- from pathlib import Path
6
- import time
7
-
8
- log = logging.getLogger(__name__)
9
-
10
- def run_preparation(state):
11
- """
12
- Performs environment preparation specific to Adobe Premiere Pro on Windows.
13
- Opens a specific template project file located on the user's desktop and maximizes the window.
14
- Kills existing Premiere Pro processes first.
15
- """
16
- if platform.system() != "Windows":
17
- log.warning("Premiere Pro preparation skipped: Not running on Windows.")
18
- return
19
-
20
- log.info(f"Premiere Pro preparation: Starting on Windows platform...")
21
-
22
- try:
23
- # Determine the desktop path for Windows
24
- try:
25
- username = os.environ.get("USERNAME", "")
26
- if not username:
27
- log.error("Could not determine Windows username from environment")
28
- return
29
-
30
- log.info(f"Using Windows username: {username}")
31
- desktop_path = Path(f"C:/Users/{username}/Desktop")
32
-
33
- if not desktop_path.exists():
34
- log.error(f"Desktop path not found at: {desktop_path}")
35
- alt_path = Path(f"C:/Documents and Settings/{username}/Desktop")
36
- if alt_path.exists():
37
- desktop_path = alt_path
38
- log.info(f"Using alternative desktop path: {desktop_path}")
39
- else:
40
- log.error("Failed to find user's desktop directory")
41
- return
42
-
43
- except Exception as e:
44
- log.error(f"Error determining Windows user desktop: {e}", exc_info=True)
45
- return
46
-
47
- # Construct path to template file
48
- template_file = desktop_path / "template.prproj" # Changed extension
49
- log.info(f"Looking for template file at: {template_file}")
50
-
51
- template_exists = template_file.exists()
52
- if not template_exists:
53
- log.warning(f"Template file not found at: {template_file}. Will attempt to launch Premiere Pro directly.")
54
-
55
- # --- Kill existing Premiere Pro processes ---
56
- log.info("Attempting to close existing Adobe Premiere Pro processes...")
57
- try:
58
- # Command to forcefully terminate Premiere Pro processes by image name
59
- # Assuming the process name includes the year for 2024 version.
60
- kill_cmd = ['taskkill', '/F', '/IM', 'Adobe Premiere Pro 2024.exe'] # Updated process name
61
- kill_result = subprocess.run(kill_cmd,
62
- capture_output=True, text=True, check=False)
63
-
64
- # Check taskkill result
65
- if kill_result.returncode == 0:
66
- log.info("Successfully sent termination signal to Adobe Premiere Pro 2024.exe processes.")
67
- elif "not found" in kill_result.stderr.lower() or "not found" in kill_result.stdout.lower():
68
- log.info("No running Adobe Premiere Pro 2024.exe processes found to close.")
69
- else:
70
- log.warning(f"taskkill command finished with return code {kill_result.returncode}. Output: {kill_result.stdout} Stderr: {kill_result.stderr}")
71
- time.sleep(2) # Increased sleep time slightly for potentially heavier app
72
- except FileNotFoundError:
73
- log.error("Error: 'taskkill' command not found. Make sure it's in the system PATH.")
74
- except Exception as e:
75
- log.error(f"Error occurred while trying to close Premiere Pro: {e}", exc_info=True)
76
- # --- End of kill process ---
77
-
78
- # Open the file with Premiere Pro maximized on Windows
79
- try:
80
- pr_executable = r"C:\Program Files\Adobe\Adobe Premiere Pro 2024\Adobe Premiere Pro.exe"
81
- # Check if template exists and construct command accordingly
82
- if template_file.exists():
83
- log.info(f"Template file found. Attempting to open {template_file} with Premiere Pro maximized...")
84
- # Use empty title "" for start when executable path has spaces
85
- cmd = ['cmd', '/c', 'start', '/max', '""', pr_executable, str(template_file)]
86
- else:
87
- log.info(f"Template file not found. Attempting to launch Premiere Pro maximized...")
88
- cmd = ['cmd', '/c', 'start', '/max', '""', pr_executable]
89
-
90
- log.info(f"Executing command: {' '.join(cmd)}")
91
- print(f"[DEBUG] Attempting command in pr_prepare: {' '.join(cmd)}")
92
- result = subprocess.run(cmd, check=False, capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
93
-
94
- # ADDED PRINTS for result
95
- print(f"[DEBUG] pr_prepare command result:")
96
- print(f"[DEBUG] Return Code: {result.returncode}")
97
- print(f"[DEBUG] Stdout: {result.stdout.strip() if result.stdout else ''}")
98
- print(f"[DEBUG] Stderr: {result.stderr.strip() if result.stderr else ''}")
99
-
100
- if result.returncode == 0:
101
- log.info(f"Successfully executed command for Premiere Pro.")
102
- else:
103
- log.error(f"Error executing command for Premiere Pro: {result.stderr.strip() if result else 'Command not run'}")
104
- if result and result.stdout:
105
- log.error(f"Stdout from start command: {result.stdout.strip()}")
106
- except FileNotFoundError:
107
- log.error("Error: 'cmd' or 'start' command not found. Ensure system PATH is configured correctly.")
108
- except Exception as e:
109
- log.error(f"Exception opening Premiere Pro on Windows: {e}", exc_info=True)
110
-
111
- except Exception as e:
1
+ import os
2
+ import platform
3
+ import subprocess
4
+ import logging
5
+ from pathlib import Path
6
+ import time
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+ def run_preparation(state):
11
+ """
12
+ Performs environment preparation specific to Adobe Premiere Pro on Windows.
13
+ Opens a specific template project file located on the user's desktop and maximizes the window.
14
+ Kills existing Premiere Pro processes first.
15
+ """
16
+ if platform.system() != "Windows":
17
+ log.warning("Premiere Pro preparation skipped: Not running on Windows.")
18
+ return
19
+
20
+ log.info(f"Premiere Pro preparation: Starting on Windows platform...")
21
+
22
+ try:
23
+ # Determine the desktop path for Windows
24
+ try:
25
+ username = os.environ.get("USERNAME", "")
26
+ if not username:
27
+ log.error("Could not determine Windows username from environment")
28
+ return
29
+
30
+ log.info(f"Using Windows username: {username}")
31
+ desktop_path = Path(f"C:/Users/{username}/Desktop")
32
+
33
+ if not desktop_path.exists():
34
+ log.error(f"Desktop path not found at: {desktop_path}")
35
+ alt_path = Path(f"C:/Documents and Settings/{username}/Desktop")
36
+ if alt_path.exists():
37
+ desktop_path = alt_path
38
+ log.info(f"Using alternative desktop path: {desktop_path}")
39
+ else:
40
+ log.error("Failed to find user's desktop directory")
41
+ return
42
+
43
+ except Exception as e:
44
+ log.error(f"Error determining Windows user desktop: {e}", exc_info=True)
45
+ return
46
+
47
+ # Construct path to template file
48
+ template_file = desktop_path / "template.prproj" # Changed extension
49
+ log.info(f"Looking for template file at: {template_file}")
50
+
51
+ template_exists = template_file.exists()
52
+ if not template_exists:
53
+ log.warning(f"Template file not found at: {template_file}. Will attempt to launch Premiere Pro directly.")
54
+
55
+ # --- Kill existing Premiere Pro processes ---
56
+ log.info("Attempting to close existing Adobe Premiere Pro processes...")
57
+ try:
58
+ # Command to forcefully terminate Premiere Pro processes by image name
59
+ # Assuming the process name includes the year for 2024 version.
60
+ kill_cmd = ['taskkill', '/F', '/IM', 'Adobe Premiere Pro 2024.exe'] # Updated process name
61
+ kill_result = subprocess.run(kill_cmd,
62
+ capture_output=True, text=True, check=False)
63
+
64
+ # Check taskkill result
65
+ if kill_result.returncode == 0:
66
+ log.info("Successfully sent termination signal to Adobe Premiere Pro 2024.exe processes.")
67
+ elif "not found" in kill_result.stderr.lower() or "not found" in kill_result.stdout.lower():
68
+ log.info("No running Adobe Premiere Pro 2024.exe processes found to close.")
69
+ else:
70
+ log.warning(f"taskkill command finished with return code {kill_result.returncode}. Output: {kill_result.stdout} Stderr: {kill_result.stderr}")
71
+ time.sleep(2) # Increased sleep time slightly for potentially heavier app
72
+ except FileNotFoundError:
73
+ log.error("Error: 'taskkill' command not found. Make sure it's in the system PATH.")
74
+ except Exception as e:
75
+ log.error(f"Error occurred while trying to close Premiere Pro: {e}", exc_info=True)
76
+ # --- End of kill process ---
77
+
78
+ # Open the file with Premiere Pro maximized on Windows
79
+ try:
80
+ pr_executable = r"C:\Program Files\Adobe\Adobe Premiere Pro 2024\Adobe Premiere Pro.exe"
81
+ # Check if template exists and construct command accordingly
82
+ if template_file.exists():
83
+ log.info(f"Template file found. Attempting to open {template_file} with Premiere Pro maximized...")
84
+ # Use empty title "" for start when executable path has spaces
85
+ cmd = ['cmd', '/c', 'start', '/max', '""', pr_executable, str(template_file)]
86
+ else:
87
+ log.info(f"Template file not found. Attempting to launch Premiere Pro maximized...")
88
+ cmd = ['cmd', '/c', 'start', '/max', '""', pr_executable]
89
+
90
+ log.info(f"Executing command: {' '.join(cmd)}")
91
+ print(f"[DEBUG] Attempting command in pr_prepare: {' '.join(cmd)}")
92
+ result = subprocess.run(cmd, check=False, capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
93
+
94
+ # ADDED PRINTS for result
95
+ print(f"[DEBUG] pr_prepare command result:")
96
+ print(f"[DEBUG] Return Code: {result.returncode}")
97
+ print(f"[DEBUG] Stdout: {result.stdout.strip() if result.stdout else ''}")
98
+ print(f"[DEBUG] Stderr: {result.stderr.strip() if result.stderr else ''}")
99
+
100
+ if result.returncode == 0:
101
+ log.info(f"Successfully executed command for Premiere Pro.")
102
+ else:
103
+ log.error(f"Error executing command for Premiere Pro: {result.stderr.strip() if result else 'Command not run'}")
104
+ if result and result.stdout:
105
+ log.error(f"Stdout from start command: {result.stdout.strip()}")
106
+ except FileNotFoundError:
107
+ log.error("Error: 'cmd' or 'start' command not found. Ensure system PATH is configured correctly.")
108
+ except Exception as e:
109
+ log.error(f"Exception opening Premiere Pro on Windows: {e}", exc_info=True)
110
+
111
+ except Exception as e:
112
112
  log.error(f"An unexpected error occurred during Premiere Pro preparation: {e}", exc_info=True)
@@ -1,100 +1,100 @@
1
- # src/computer_use_ootb_internal/preparation/star_rail_prepare.py
2
- import time
3
- import platform
4
- import subprocess # Added for taskkill
5
- import pyautogui
6
- import webbrowser
7
- import logging # Use logging instead of print for better practice
8
-
9
- # Set up logging for this module if needed, or rely on root logger
10
- log = logging.getLogger(__name__)
11
-
12
- def run_preparation(state):
13
- """
14
- Performs environment preparation specific to Star Rail on Windows.
15
- Closes existing Edge browsers, opens the specified URL in a new Edge instance,
16
- and performs initial clicks.
17
- """
18
- if platform.system() != "Windows":
19
- log.info("Star Rail preparation skipped: Not running on Windows.")
20
- return
21
-
22
- log.info("Star Rail preparation: Starting environment setup on Windows...")
23
- url = "https://sr.mihoyo.com/cloud/#/" # Consider making this configurable later
24
- browser_opened = False
25
- try:
26
- # Attempt to close existing Microsoft Edge processes
27
- log.info("Attempting to close existing Microsoft Edge processes...")
28
- try:
29
- # /F forces termination, /IM specifies image name
30
- result = subprocess.run(['taskkill', '/F', '/IM', 'msedge.exe'],
31
- capture_output=True, text=True, check=False)
32
- if result.returncode == 0:
33
- log.info("Successfully sent termination signal to msedge.exe processes.")
34
- elif "not found" in result.stderr.lower() or "not found" in result.stdout.lower():
35
- log.info("No running msedge.exe processes found to close.")
36
- else:
37
- log.warning(f"taskkill command finished with return code {result.returncode}. Output: {result.stdout} Stderr: {result.stderr}")
38
- time.sleep(2) # Give processes time to close
39
- except FileNotFoundError:
40
- log.error("Error: 'taskkill' command not found. Make sure it's in the system PATH.")
41
- except Exception as e:
42
- log.error(f"Error occurred while trying to close Edge: {e}", exc_info=True)
43
-
44
- # Use only webbrowser.open
45
- log.info(f"Attempting to open {url} using webbrowser.open()...")
46
- if webbrowser.open(url):
47
- log.info(f"Successfully requested browser to open {url} via webbrowser.open().")
48
- browser_opened = True
49
- # Ensure sleep time for browser load before clicks is present
50
- time.sleep(5)
51
- else:
52
- log.warning("webbrowser.open() returned False, indicating potential failure.")
53
-
54
- if not browser_opened:
55
- log.error("Failed to confirm browser opening via webbrowser.open(). Will still attempt clicks.")
56
-
57
- # Add pyautogui click after attempting to open the browser
58
- log.info("Proceeding with pyautogui actions...")
59
- time.sleep(5) # Wait time for the browser to load
60
-
61
- # Get screen size
62
- screen_width, screen_height = pyautogui.size()
63
- log.info(f"Detected screen size: {screen_width}x{screen_height}")
64
-
65
- # Calculate click coordinates based on a reference resolution (e.g., 1280x720)
66
- # TODO: Make these coordinates more robust or configurable
67
- click_x_1 = int(screen_width * (1036 / 1280))
68
- click_y_1 = int(screen_height * (500 / 720))
69
- log.info(f"Calculated click coordinates for starting the game: ({click_x_1}, {click_y_1})")
70
- click_x_2 = int(screen_width * (1233 / 1280))
71
- click_y_2 = int(screen_height * (30 / 720))
72
- log.info(f"Calculated click coordinates for closing the browser warning: ({click_x_2}, {click_y_2})")
73
-
74
- # Disable failsafe before clicking
75
- pyautogui.FAILSAFE = False
76
- log.info("PyAutoGUI failsafe temporarily disabled.")
77
-
78
- log.info(f"Clicking at coordinates: ({click_x_1}, {click_y_1})")
79
- pyautogui.click(click_x_1, click_y_1)
80
- time.sleep(2)
81
- pyautogui.click(click_x_1, click_y_1) # Double click?
82
-
83
- # Press F11 to attempt fullscreen
84
- log.info("Pressing F11 to enter fullscreen...")
85
- time.sleep(1) # Short delay before pressing F11
86
- pyautogui.press('f11')
87
- time.sleep(1)
88
- log.info(f"Clicking at coordinates: ({click_x_2}, {click_y_2})")
89
- pyautogui.click(click_x_2, click_y_2)
90
- time.sleep(1)
91
- pyautogui.click(click_x_2, click_y_2)
92
-
93
- log.info("Star Rail preparation clicks completed.")
94
-
95
- except Exception as e:
96
- log.error(f"Error during Star Rail preparation (browser/click): {e}", exc_info=True)
97
- finally:
98
- # Ensure failsafe is re-enabled
99
- pyautogui.FAILSAFE = True
1
+ # src/computer_use_ootb_internal/preparation/star_rail_prepare.py
2
+ import time
3
+ import platform
4
+ import subprocess # Added for taskkill
5
+ import pyautogui
6
+ import webbrowser
7
+ import logging # Use logging instead of print for better practice
8
+
9
+ # Set up logging for this module if needed, or rely on root logger
10
+ log = logging.getLogger(__name__)
11
+
12
+ def run_preparation(state):
13
+ """
14
+ Performs environment preparation specific to Star Rail on Windows.
15
+ Closes existing Edge browsers, opens the specified URL in a new Edge instance,
16
+ and performs initial clicks.
17
+ """
18
+ if platform.system() != "Windows":
19
+ log.info("Star Rail preparation skipped: Not running on Windows.")
20
+ return
21
+
22
+ log.info("Star Rail preparation: Starting environment setup on Windows...")
23
+ url = "https://sr.mihoyo.com/cloud/#/" # Consider making this configurable later
24
+ browser_opened = False
25
+ try:
26
+ # Attempt to close existing Microsoft Edge processes
27
+ log.info("Attempting to close existing Microsoft Edge processes...")
28
+ try:
29
+ # /F forces termination, /IM specifies image name
30
+ result = subprocess.run(['taskkill', '/F', '/IM', 'msedge.exe'],
31
+ capture_output=True, text=True, check=False)
32
+ if result.returncode == 0:
33
+ log.info("Successfully sent termination signal to msedge.exe processes.")
34
+ elif "not found" in result.stderr.lower() or "not found" in result.stdout.lower():
35
+ log.info("No running msedge.exe processes found to close.")
36
+ else:
37
+ log.warning(f"taskkill command finished with return code {result.returncode}. Output: {result.stdout} Stderr: {result.stderr}")
38
+ time.sleep(2) # Give processes time to close
39
+ except FileNotFoundError:
40
+ log.error("Error: 'taskkill' command not found. Make sure it's in the system PATH.")
41
+ except Exception as e:
42
+ log.error(f"Error occurred while trying to close Edge: {e}", exc_info=True)
43
+
44
+ # Use only webbrowser.open
45
+ log.info(f"Attempting to open {url} using webbrowser.open()...")
46
+ if webbrowser.open(url):
47
+ log.info(f"Successfully requested browser to open {url} via webbrowser.open().")
48
+ browser_opened = True
49
+ # Ensure sleep time for browser load before clicks is present
50
+ time.sleep(5)
51
+ else:
52
+ log.warning("webbrowser.open() returned False, indicating potential failure.")
53
+
54
+ if not browser_opened:
55
+ log.error("Failed to confirm browser opening via webbrowser.open(). Will still attempt clicks.")
56
+
57
+ # Add pyautogui click after attempting to open the browser
58
+ log.info("Proceeding with pyautogui actions...")
59
+ time.sleep(5) # Wait time for the browser to load
60
+
61
+ # Get screen size
62
+ screen_width, screen_height = pyautogui.size()
63
+ log.info(f"Detected screen size: {screen_width}x{screen_height}")
64
+
65
+ # Calculate click coordinates based on a reference resolution (e.g., 1280x720)
66
+ # TODO: Make these coordinates more robust or configurable
67
+ click_x_1 = int(screen_width * (1036 / 1280))
68
+ click_y_1 = int(screen_height * (500 / 720))
69
+ log.info(f"Calculated click coordinates for starting the game: ({click_x_1}, {click_y_1})")
70
+ click_x_2 = int(screen_width * (1233 / 1280))
71
+ click_y_2 = int(screen_height * (30 / 720))
72
+ log.info(f"Calculated click coordinates for closing the browser warning: ({click_x_2}, {click_y_2})")
73
+
74
+ # Disable failsafe before clicking
75
+ pyautogui.FAILSAFE = False
76
+ log.info("PyAutoGUI failsafe temporarily disabled.")
77
+
78
+ log.info(f"Clicking at coordinates: ({click_x_1}, {click_y_1})")
79
+ pyautogui.click(click_x_1, click_y_1)
80
+ time.sleep(2)
81
+ pyautogui.click(click_x_1, click_y_1) # Double click?
82
+
83
+ # Press F11 to attempt fullscreen
84
+ log.info("Pressing F11 to enter fullscreen...")
85
+ time.sleep(1) # Short delay before pressing F11
86
+ pyautogui.press('f11')
87
+ time.sleep(1)
88
+ log.info(f"Clicking at coordinates: ({click_x_2}, {click_y_2})")
89
+ pyautogui.click(click_x_2, click_y_2)
90
+ time.sleep(1)
91
+ pyautogui.click(click_x_2, click_y_2)
92
+
93
+ log.info("Star Rail preparation clicks completed.")
94
+
95
+ except Exception as e:
96
+ log.error(f"Error during Star Rail preparation (browser/click): {e}", exc_info=True)
97
+ finally:
98
+ # Ensure failsafe is re-enabled
99
+ pyautogui.FAILSAFE = True
100
100
  log.info("PyAutoGUI failsafe re-enabled.")
@@ -1,109 +1,109 @@
1
- import os
2
- import platform
3
- import subprocess
4
- import logging
5
- from pathlib import Path
6
- import time
7
-
8
- log = logging.getLogger(__name__)
9
-
10
- def run_preparation(state):
11
- """
12
- Performs environment preparation specific to Word on Windows.
13
- Opens a specific template file located on the user's desktop and maximizes the window.
14
- Kills existing Word processes first.
15
- """
16
- if platform.system() != "Windows":
17
- log.warning("Word preparation skipped: Not running on Windows.")
18
- return
19
-
20
- log.info(f"Word preparation: Starting on Windows platform...")
21
-
22
- try:
23
- # Determine the desktop path for Windows
24
- try:
25
- username = os.environ.get("USERNAME", "")
26
- if not username:
27
- log.error("Could not determine Windows username from environment")
28
- return
29
-
30
- log.info(f"Using Windows username: {username}")
31
- desktop_path = Path(f"C:/Users/{username}/Desktop")
32
-
33
- if not desktop_path.exists():
34
- log.error(f"Desktop path not found at: {desktop_path}")
35
- alt_path = Path(f"C:/Documents and Settings/{username}/Desktop")
36
- if alt_path.exists():
37
- desktop_path = alt_path
38
- log.info(f"Using alternative desktop path: {desktop_path}")
39
- else:
40
- log.error("Failed to find user's desktop directory")
41
- return
42
-
43
- except Exception as e:
44
- log.error(f"Error determining Windows user desktop: {e}", exc_info=True)
45
- return
46
-
47
- # Construct path to template file
48
- template_file = desktop_path / "template.docx" # Changed extension
49
- log.info(f"Looking for template file at: {template_file}")
50
-
51
- template_exists = template_file.exists()
52
- if not template_exists:
53
- log.warning(f"Template file not found at: {template_file}. Will attempt to launch Word directly.")
54
-
55
- # --- Kill existing Word processes ---
56
- log.info("Attempting to close existing Microsoft Word processes...")
57
- try:
58
- # Command to forcefully terminate Word processes by image name
59
- kill_cmd = ['taskkill', '/F', '/IM', 'WINWORD.EXE'] # Changed process name
60
- kill_result = subprocess.run(kill_cmd,
61
- capture_output=True, text=True, check=False)
62
-
63
- # Check taskkill result
64
- if kill_result.returncode == 0:
65
- log.info("Successfully sent termination signal to WINWORD.EXE processes.")
66
- elif "not found" in kill_result.stderr.lower() or "not found" in kill_result.stdout.lower():
67
- log.info("No running WINWORD.EXE processes found to close.")
68
- else:
69
- log.warning(f"taskkill command finished with return code {kill_result.returncode}. Output: {kill_result.stdout} Stderr: {kill_result.stderr}")
70
- time.sleep(2)
71
- except FileNotFoundError:
72
- log.error("Error: 'taskkill' command not found. Make sure it's in the system PATH.")
73
- except Exception as e:
74
- log.error(f"Error occurred while trying to close Word: {e}", exc_info=True)
75
- # --- End of kill process ---
76
-
77
- # Open the file with Word maximized on Windows
78
- try:
79
- # Check if template exists and construct command accordingly
80
- if template_file.exists():
81
- log.info(f"Template file found. Attempting to open {template_file} with Word maximized...")
82
- cmd = ['cmd', '/c', 'start', '/max', 'winword', str(template_file)]
83
- else:
84
- log.info(f"Template file not found. Attempting to launch Word maximized...")
85
- cmd = ['cmd', '/c', 'start', '/max', 'winword']
86
-
87
- log.info(f"Executing command: {' '.join(cmd)}")
88
- print(f"[DEBUG] Attempting command in word_prepare: {' '.join(cmd)}")
89
- result = subprocess.run(cmd, check=False, capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
90
-
91
- # ADDED PRINTS for result
92
- print(f"[DEBUG] word_prepare command result:")
93
- print(f"[DEBUG] Return Code: {result.returncode}")
94
- print(f"[DEBUG] Stdout: {result.stdout.strip() if result.stdout else ''}")
95
- print(f"[DEBUG] Stderr: {result.stderr.strip() if result.stderr else ''}")
96
-
97
- if result.returncode == 0:
98
- log.info(f"Successfully executed command for Word.")
99
- else:
100
- log.error(f"Error opening Word: {result.stderr.strip()}")
101
- if result.stdout:
102
- log.error(f"Stdout from start command: {result.stdout.strip()}")
103
- except FileNotFoundError:
104
- log.error("Error: 'cmd' or 'start' command not found. Ensure system PATH is configured correctly.")
105
- except Exception as e:
106
- log.error(f"Exception opening Word on Windows: {e}", exc_info=True)
107
-
108
- except Exception as e:
1
+ import os
2
+ import platform
3
+ import subprocess
4
+ import logging
5
+ from pathlib import Path
6
+ import time
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+ def run_preparation(state):
11
+ """
12
+ Performs environment preparation specific to Word on Windows.
13
+ Opens a specific template file located on the user's desktop and maximizes the window.
14
+ Kills existing Word processes first.
15
+ """
16
+ if platform.system() != "Windows":
17
+ log.warning("Word preparation skipped: Not running on Windows.")
18
+ return
19
+
20
+ log.info(f"Word preparation: Starting on Windows platform...")
21
+
22
+ try:
23
+ # Determine the desktop path for Windows
24
+ try:
25
+ username = os.environ.get("USERNAME", "")
26
+ if not username:
27
+ log.error("Could not determine Windows username from environment")
28
+ return
29
+
30
+ log.info(f"Using Windows username: {username}")
31
+ desktop_path = Path(f"C:/Users/{username}/Desktop")
32
+
33
+ if not desktop_path.exists():
34
+ log.error(f"Desktop path not found at: {desktop_path}")
35
+ alt_path = Path(f"C:/Documents and Settings/{username}/Desktop")
36
+ if alt_path.exists():
37
+ desktop_path = alt_path
38
+ log.info(f"Using alternative desktop path: {desktop_path}")
39
+ else:
40
+ log.error("Failed to find user's desktop directory")
41
+ return
42
+
43
+ except Exception as e:
44
+ log.error(f"Error determining Windows user desktop: {e}", exc_info=True)
45
+ return
46
+
47
+ # Construct path to template file
48
+ template_file = desktop_path / "template.docx" # Changed extension
49
+ log.info(f"Looking for template file at: {template_file}")
50
+
51
+ template_exists = template_file.exists()
52
+ if not template_exists:
53
+ log.warning(f"Template file not found at: {template_file}. Will attempt to launch Word directly.")
54
+
55
+ # --- Kill existing Word processes ---
56
+ log.info("Attempting to close existing Microsoft Word processes...")
57
+ try:
58
+ # Command to forcefully terminate Word processes by image name
59
+ kill_cmd = ['taskkill', '/F', '/IM', 'WINWORD.EXE'] # Changed process name
60
+ kill_result = subprocess.run(kill_cmd,
61
+ capture_output=True, text=True, check=False)
62
+
63
+ # Check taskkill result
64
+ if kill_result.returncode == 0:
65
+ log.info("Successfully sent termination signal to WINWORD.EXE processes.")
66
+ elif "not found" in kill_result.stderr.lower() or "not found" in kill_result.stdout.lower():
67
+ log.info("No running WINWORD.EXE processes found to close.")
68
+ else:
69
+ log.warning(f"taskkill command finished with return code {kill_result.returncode}. Output: {kill_result.stdout} Stderr: {kill_result.stderr}")
70
+ time.sleep(2)
71
+ except FileNotFoundError:
72
+ log.error("Error: 'taskkill' command not found. Make sure it's in the system PATH.")
73
+ except Exception as e:
74
+ log.error(f"Error occurred while trying to close Word: {e}", exc_info=True)
75
+ # --- End of kill process ---
76
+
77
+ # Open the file with Word maximized on Windows
78
+ try:
79
+ # Check if template exists and construct command accordingly
80
+ if template_file.exists():
81
+ log.info(f"Template file found. Attempting to open {template_file} with Word maximized...")
82
+ cmd = ['cmd', '/c', 'start', '/max', 'winword', str(template_file)]
83
+ else:
84
+ log.info(f"Template file not found. Attempting to launch Word maximized...")
85
+ cmd = ['cmd', '/c', 'start', '/max', 'winword']
86
+
87
+ log.info(f"Executing command: {' '.join(cmd)}")
88
+ print(f"[DEBUG] Attempting command in word_prepare: {' '.join(cmd)}")
89
+ result = subprocess.run(cmd, check=False, capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
90
+
91
+ # ADDED PRINTS for result
92
+ print(f"[DEBUG] word_prepare command result:")
93
+ print(f"[DEBUG] Return Code: {result.returncode}")
94
+ print(f"[DEBUG] Stdout: {result.stdout.strip() if result.stdout else ''}")
95
+ print(f"[DEBUG] Stderr: {result.stderr.strip() if result.stderr else ''}")
96
+
97
+ if result.returncode == 0:
98
+ log.info(f"Successfully executed command for Word.")
99
+ else:
100
+ log.error(f"Error opening Word: {result.stderr.strip()}")
101
+ if result.stdout:
102
+ log.error(f"Stdout from start command: {result.stdout.strip()}")
103
+ except FileNotFoundError:
104
+ log.error("Error: 'cmd' or 'start' command not found. Ensure system PATH is configured correctly.")
105
+ except Exception as e:
106
+ log.error(f"Exception opening Word on Windows: {e}", exc_info=True)
107
+
108
+ except Exception as e:
109
109
  log.error(f"An unexpected error occurred during Word preparation: {e}", exc_info=True)