pomera-ai-commander 1.2.1 → 1.2.3

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.
@@ -0,0 +1,275 @@
1
+ """
2
+ Memento pattern implementation for Find & Replace undo/redo functionality.
3
+
4
+ This module provides a robust undo/redo system that preserves:
5
+ - Full text content before/after operations
6
+ - Cursor position and selection
7
+ - Scroll position
8
+ - Operation metadata (find/replace patterns, timestamp)
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import Optional, List, Tuple
13
+ from datetime import datetime
14
+ import time
15
+
16
+
17
+ @dataclass
18
+ class TextState:
19
+ """Stores the state of a text widget for restoration."""
20
+ content: str
21
+ cursor_position: str = "1.0" # Tk index format
22
+ selection_start: Optional[str] = None
23
+ selection_end: Optional[str] = None
24
+ scroll_position: Tuple[float, float] = (0.0, 0.0) # (yview start, yview end)
25
+
26
+ def has_selection(self) -> bool:
27
+ """Check if there's a text selection."""
28
+ return self.selection_start is not None and self.selection_end is not None
29
+
30
+
31
+ @dataclass
32
+ class FindReplaceMemento:
33
+ """
34
+ Memento class storing the complete state of a Find & Replace operation.
35
+
36
+ Implements the Memento design pattern for undo/redo functionality.
37
+ """
38
+ # Before/after states
39
+ before_state: TextState
40
+ after_state: Optional[TextState] = None
41
+
42
+ # Operation details
43
+ find_pattern: str = ""
44
+ replace_pattern: str = ""
45
+ is_regex: bool = False
46
+ match_case: bool = False
47
+
48
+ # Match statistics
49
+ match_count: int = 0
50
+ replaced_count: int = 0
51
+
52
+ # Metadata
53
+ timestamp: float = field(default_factory=time.time)
54
+ description: str = ""
55
+
56
+ def get_timestamp_str(self) -> str:
57
+ """Get human-readable timestamp."""
58
+ return datetime.fromtimestamp(self.timestamp).strftime("%H:%M:%S")
59
+
60
+ def get_summary(self) -> str:
61
+ """Get a short summary of the operation."""
62
+ if self.description:
63
+ return self.description
64
+ return f"Replace '{self.find_pattern[:20]}...' → '{self.replace_pattern[:20]}...' ({self.replaced_count} changes)"
65
+
66
+
67
+ class MementoCaretaker:
68
+ """
69
+ Caretaker class that manages the undo/redo stacks.
70
+
71
+ Implements the Caretaker role in the Memento pattern.
72
+ """
73
+
74
+ def __init__(self, max_history: int = 50):
75
+ """
76
+ Initialize the caretaker.
77
+
78
+ Args:
79
+ max_history: Maximum number of operations to keep in history
80
+ """
81
+ self.max_history = max_history
82
+ self._undo_stack: List[FindReplaceMemento] = []
83
+ self._redo_stack: List[FindReplaceMemento] = []
84
+ self._change_callbacks: List[callable] = []
85
+
86
+ def add_change_callback(self, callback: callable):
87
+ """Add a callback to be notified when stacks change."""
88
+ self._change_callbacks.append(callback)
89
+
90
+ def _notify_change(self):
91
+ """Notify all callbacks of stack changes."""
92
+ for callback in self._change_callbacks:
93
+ try:
94
+ callback(self.can_undo(), self.can_redo())
95
+ except Exception:
96
+ pass # Don't let callback errors break functionality
97
+
98
+ def save(self, memento: FindReplaceMemento) -> None:
99
+ """
100
+ Save a new memento to the undo stack.
101
+
102
+ This clears the redo stack as new changes invalidate future states.
103
+
104
+ Args:
105
+ memento: The memento to save
106
+ """
107
+ self._undo_stack.append(memento)
108
+ self._redo_stack.clear() # New action invalidates redo history
109
+
110
+ # Limit stack size
111
+ if len(self._undo_stack) > self.max_history:
112
+ self._undo_stack.pop(0)
113
+
114
+ self._notify_change()
115
+
116
+ def undo(self) -> Optional[FindReplaceMemento]:
117
+ """
118
+ Pop and return the last memento from undo stack.
119
+
120
+ The memento is moved to the redo stack.
121
+
122
+ Returns:
123
+ The memento to restore, or None if stack is empty
124
+ """
125
+ if not self._undo_stack:
126
+ return None
127
+
128
+ memento = self._undo_stack.pop()
129
+ self._redo_stack.append(memento)
130
+ self._notify_change()
131
+ return memento
132
+
133
+ def redo(self) -> Optional[FindReplaceMemento]:
134
+ """
135
+ Pop and return the last memento from redo stack.
136
+
137
+ The memento is moved back to the undo stack.
138
+
139
+ Returns:
140
+ The memento to re-apply, or None if stack is empty
141
+ """
142
+ if not self._redo_stack:
143
+ return None
144
+
145
+ memento = self._redo_stack.pop()
146
+ self._undo_stack.append(memento)
147
+ self._notify_change()
148
+ return memento
149
+
150
+ def can_undo(self) -> bool:
151
+ """Check if undo is available."""
152
+ return len(self._undo_stack) > 0
153
+
154
+ def can_redo(self) -> bool:
155
+ """Check if redo is available."""
156
+ return len(self._redo_stack) > 0
157
+
158
+ def get_undo_count(self) -> int:
159
+ """Get the number of undo operations available."""
160
+ return len(self._undo_stack)
161
+
162
+ def get_redo_count(self) -> int:
163
+ """Get the number of redo operations available."""
164
+ return len(self._redo_stack)
165
+
166
+ def get_undo_history(self) -> List[str]:
167
+ """Get summaries of all undo operations (most recent first)."""
168
+ return [m.get_summary() for m in reversed(self._undo_stack)]
169
+
170
+ def get_redo_history(self) -> List[str]:
171
+ """Get summaries of all redo operations (most recent first)."""
172
+ return [m.get_summary() for m in reversed(self._redo_stack)]
173
+
174
+ def clear(self) -> None:
175
+ """Clear all undo/redo history."""
176
+ self._undo_stack.clear()
177
+ self._redo_stack.clear()
178
+ self._notify_change()
179
+
180
+ def peek_undo(self) -> Optional[FindReplaceMemento]:
181
+ """Peek at the next undo operation without removing it."""
182
+ return self._undo_stack[-1] if self._undo_stack else None
183
+
184
+ def peek_redo(self) -> Optional[FindReplaceMemento]:
185
+ """Peek at the next redo operation without removing it."""
186
+ return self._redo_stack[-1] if self._redo_stack else None
187
+
188
+
189
+ def capture_text_state(text_widget) -> TextState:
190
+ """
191
+ Capture the current state of a Tk Text widget.
192
+
193
+ Args:
194
+ text_widget: A tkinter Text widget
195
+
196
+ Returns:
197
+ TextState containing the current state
198
+ """
199
+ try:
200
+ content = text_widget.get("1.0", "end-1c")
201
+ cursor_position = text_widget.index("insert")
202
+
203
+ # Capture selection if any
204
+ try:
205
+ selection_start = text_widget.index("sel.first")
206
+ selection_end = text_widget.index("sel.last")
207
+ except Exception:
208
+ selection_start = None
209
+ selection_end = None
210
+
211
+ # Capture scroll position
212
+ try:
213
+ scroll_position = text_widget.yview()
214
+ except Exception:
215
+ scroll_position = (0.0, 0.0)
216
+
217
+ return TextState(
218
+ content=content,
219
+ cursor_position=cursor_position,
220
+ selection_start=selection_start,
221
+ selection_end=selection_end,
222
+ scroll_position=scroll_position
223
+ )
224
+ except Exception:
225
+ # Fallback for edge cases
226
+ return TextState(content="", cursor_position="1.0")
227
+
228
+
229
+ def restore_text_state(text_widget, state: TextState, restore_scroll: bool = True) -> bool:
230
+ """
231
+ Restore a text widget to a saved state.
232
+
233
+ Args:
234
+ text_widget: A tkinter Text widget
235
+ state: The TextState to restore
236
+ restore_scroll: Whether to restore scroll position
237
+
238
+ Returns:
239
+ True if restoration was successful
240
+ """
241
+ try:
242
+ # Temporarily enable widget if disabled
243
+ original_state = text_widget.cget("state")
244
+ text_widget.config(state="normal")
245
+
246
+ # Restore content
247
+ text_widget.delete("1.0", "end")
248
+ text_widget.insert("1.0", state.content)
249
+
250
+ # Restore cursor position
251
+ try:
252
+ text_widget.mark_set("insert", state.cursor_position)
253
+ except Exception:
254
+ pass
255
+
256
+ # Restore selection
257
+ if state.has_selection():
258
+ try:
259
+ text_widget.tag_add("sel", state.selection_start, state.selection_end)
260
+ except Exception:
261
+ pass
262
+
263
+ # Restore scroll position
264
+ if restore_scroll and state.scroll_position:
265
+ try:
266
+ text_widget.yview_moveto(state.scroll_position[0])
267
+ except Exception:
268
+ pass
269
+
270
+ # Restore original state
271
+ text_widget.config(state=original_state)
272
+
273
+ return True
274
+ except Exception:
275
+ return False
package/mcp.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pomera-ai-commander",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "description": "Text processing toolkit with 22 MCP tools including case transformation, encoding, hashing, text analysis, and notes management for AI assistants.",
5
5
  "homepage": "https://github.com/matbanik/Pomera-AI-Commander",
6
6
  "repository": "https://github.com/matbanik/Pomera-AI-Commander",
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Pre-Update Migration Script for Pomera AI Commander
4
+
5
+ Run this script BEFORE updating via npm or pip to migrate your databases
6
+ to the platform-appropriate user data directory.
7
+
8
+ Usage:
9
+ python migrate_data.py
10
+
11
+ This will:
12
+ 1. Find existing databases in the installation directory
13
+ 2. Copy them to the user data directory (safe from updates)
14
+ 3. Verify the migration was successful
15
+ """
16
+
17
+ import os
18
+ import sys
19
+ import shutil
20
+ from pathlib import Path
21
+
22
+ def get_user_data_dir():
23
+ """Get platform-appropriate user data directory."""
24
+ import platform
25
+ system = platform.system()
26
+ app_name = "Pomera-AI-Commander"
27
+
28
+ try:
29
+ from platformdirs import user_data_dir
30
+ return Path(user_data_dir(app_name, "PomeraAI"))
31
+ except ImportError:
32
+ pass
33
+
34
+ if system == "Windows":
35
+ base = os.environ.get("LOCALAPPDATA", os.path.expanduser("~"))
36
+ return Path(base) / app_name
37
+ elif system == "Darwin":
38
+ return Path.home() / "Library" / "Application Support" / app_name
39
+ else:
40
+ xdg_data = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
41
+ return Path(xdg_data) / app_name
42
+
43
+ def get_installation_dir():
44
+ """Get the current installation directory."""
45
+ return Path(__file__).parent
46
+
47
+ def migrate():
48
+ """Migrate databases from installation dir to user data dir."""
49
+ install_dir = get_installation_dir()
50
+ user_dir = get_user_data_dir()
51
+
52
+ print(f"Installation directory: {install_dir}")
53
+ print(f"User data directory: {user_dir}")
54
+ print()
55
+
56
+ # Create user data directory
57
+ user_dir.mkdir(parents=True, exist_ok=True)
58
+
59
+ databases = ['settings.db', 'notes.db', 'settings.json']
60
+ migrated = []
61
+ skipped = []
62
+ not_found = []
63
+
64
+ for db_name in databases:
65
+ src = install_dir / db_name
66
+ dst = user_dir / db_name
67
+
68
+ if not src.exists():
69
+ not_found.append(db_name)
70
+ continue
71
+
72
+ if dst.exists():
73
+ src_size = src.stat().st_size
74
+ dst_size = dst.stat().st_size
75
+ print(f"⚠️ {db_name}: Already exists in target")
76
+ print(f" Source size: {src_size:,} bytes")
77
+ print(f" Target size: {dst_size:,} bytes")
78
+
79
+ if src_size > dst_size:
80
+ response = input(f" Source is larger. Overwrite target? [y/N]: ")
81
+ if response.lower() == 'y':
82
+ shutil.copy2(src, dst)
83
+ migrated.append(db_name)
84
+ print(f" ✅ Overwritten")
85
+ else:
86
+ skipped.append(db_name)
87
+ print(f" ⏭️ Skipped")
88
+ else:
89
+ skipped.append(db_name)
90
+ print(f" ⏭️ Keeping existing (same or larger)")
91
+ else:
92
+ shutil.copy2(src, dst)
93
+ migrated.append(db_name)
94
+ print(f"✅ {db_name}: Migrated ({src.stat().st_size:,} bytes)")
95
+
96
+ print()
97
+ print("=" * 50)
98
+ print("Migration Summary")
99
+ print("=" * 50)
100
+
101
+ if migrated:
102
+ print(f"✅ Migrated: {', '.join(migrated)}")
103
+ if skipped:
104
+ print(f"⏭️ Skipped: {', '.join(skipped)}")
105
+ if not_found:
106
+ print(f"➖ Not found: {', '.join(not_found)}")
107
+
108
+ print()
109
+ print(f"Your data is now safe in: {user_dir}")
110
+ print()
111
+ print("You can now safely update Pomera via npm or pip!")
112
+
113
+ return len(migrated) > 0 or len(skipped) > 0
114
+
115
+ if __name__ == "__main__":
116
+ print("=" * 50)
117
+ print("Pomera AI Commander - Pre-Update Migration")
118
+ print("=" * 50)
119
+ print()
120
+
121
+ if migrate():
122
+ print("✅ Migration complete!")
123
+ sys.exit(0)
124
+ else:
125
+ print("ℹ️ No databases found to migrate.")
126
+ print(" (This is normal for fresh installations)")
127
+ sys.exit(0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pomera-ai-commander",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "description": "Text processing toolkit with 22 MCP tools for AI assistants - case transformation, encoding, hashing, text analysis, and notes management",
5
5
  "main": "pomera_mcp_server.py",
6
6
  "bin": {
@@ -11,7 +11,8 @@
11
11
  "start": "python pomera_mcp_server.py",
12
12
  "mcp": "python pomera_mcp_server.py",
13
13
  "list-tools": "python pomera_mcp_server.py --list-tools",
14
- "test": "python -m pytest"
14
+ "test": "python -m pytest",
15
+ "postinstall": "node scripts/postinstall.js"
15
16
  },
16
17
  "keywords": [
17
18
  "mcp",
@@ -48,8 +49,10 @@
48
49
  "bin/",
49
50
  "core/",
50
51
  "tools/",
52
+ "scripts/",
51
53
  "pomera_mcp_server.py",
52
54
  "pomera.py",
55
+ "migrate_data.py",
53
56
  "mcp.json",
54
57
  "README.md",
55
58
  "LICENSE",