Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclipboard_manager.py
More file actions
Latest commit
289 lines (240 loc) · 9 KB
/
Copy pathclipboard_manager.py
File metadata and controls
289 lines (240 loc) · 9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
importjson
importos
fromdatetimeimportdatetime
importplatform
importsubprocess
ifplatform.system() =="Windows":
importwin32clipboardasclipboard
importwin32con
documents_dir=os.path.join(os.path.expanduser("~"), "Documents")
HISTORY_FILE=os.path.join(documents_dir, "clipboard_history.json")
MAX_HISTORY_ITEMS=100
ifnotos.path.exists(HISTORY_FILE):
try:
withopen(HISTORY_FILE, 'w', encoding='utf-8') asf:
json.dump([], f)
exceptException:
pass
public_description="Manage clipboard history and retrieve previously copied items."
defget_clipboard_text():
ifplatform.system() =="Windows":
clipboard.OpenClipboard()
try:
ifclipboard.IsClipboardFormatAvailable(win32con.CF_TEXT):
data=clipboard.GetClipboardData(win32con.CF_TEXT)
returndata.decode('utf-8')
return""
finally:
clipboard.CloseClipboard()
elifplatform.system() =="Darwin":
try:
returnsubprocess.check_output(
['pbpaste'], universal_newlines=True, stderr=subprocess.DEVNULL
).strip()
exceptsubprocess.CalledProcessError:
return""
elifplatform.system() =="Linux":
try:
returnsubprocess.check_output(
['xclip', '-selection', 'clipboard', '-o'],
universal_newlines=True, stderr=subprocess.DEVNULL
).strip()
except (subprocess.SubprocessError, FileNotFoundError):
try:
returnsubprocess.check_output(
['xsel', '-b'],
universal_newlines=True, stderr=subprocess.DEVNULL
).strip()
except (subprocess.SubprocessError, FileNotFoundError):
return""
return""
defset_clipboard_text(text):
ifplatform.system() =="Windows":
clipboard.OpenClipboard()
try:
clipboard.EmptyClipboard()
clipboard.SetClipboardText(text, win32con.CF_UNICODETEXT)
finally:
clipboard.CloseClipboard()
elifplatform.system() =="Darwin":
try:
subprocess.run(['pbcopy'], input=text.encode('utf-8'), check=True)
exceptsubprocess.SubprocessError:
pass
elifplatform.system() =="Linux":
try:
subprocess.run(['xclip', '-selection', 'clipboard'], input=text.encode('utf-8'), check=True)
except (subprocess.SubprocessError, FileNotFoundError):
try:
subprocess.run(['xsel', '-ib'], input=text.encode('utf-8'), check=True)
except (subprocess.SubprocessError, FileNotFoundError):
pass
defload_history():
ifos.path.exists(HISTORY_FILE):
try:
withopen(HISTORY_FILE, 'r', encoding='utf-8') asf:
returnjson.load(f)
except (json.JSONDecodeError, UnicodeDecodeError):
return []
return []
defsave_history(history):
ifnotos.path.exists(documents_dir):
try:
os.makedirs(documents_dir)
exceptException:
pass
try:
withopen(HISTORY_FILE, 'w', encoding='utf-8') asf:
json.dump(history, f, ensure_ascii=False, indent=2)
exceptException:
pass
defadd_to_history(text):
ifnottextortext.isspace():
return
history=load_history()
history= [itemforiteminhistoryifitem["text"] !=text]
history.insert(0, {
"text": text,
"timestamp": datetime.now().isoformat(),
})
iflen(history) >MAX_HISTORY_ITEMS:
history=history[:MAX_HISTORY_ITEMS]
save_history(history)
defsearch_history(query):
history=load_history()
ifnotquery:
returnhistory[:10]
matches= []
foriteminhistory:
ifquery.lower() initem["text"].lower():
matches.append(item)
returnmatches
asyncdeffunction(args):
try:
current_clipboard=get_clipboard_text()
ifcurrent_clipboard:
add_to_history(current_clipboard)
operation=args.get("operation", "show")
ifnotargs:
args= {}
elifoperation=="show":
limit=int(args.get("limit", 10))
history=load_history()
ifnothistory:
returnjson.dumps({
"message": "No clipboard history found."
})
recent_items=history[:limit]
formatted_items= []
fori, iteminenumerate(recent_items):
try:
timestamp=datetime.fromisoformat(item["timestamp"])
time_str=timestamp.strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, KeyError):
time_str="Unknown time"
text=item["text"]
iflen(text) >100:
text=text[:97] +"..."
formatted_items.append({
"index": i,
"text": text,
"time": time_str
})
returnjson.dumps({
"message": {
"text": f"Showing {len(formatted_items)} clipboard history items",
"items": formatted_items
}
})
elifoperation=="search":
query=args.get("query", "")
ifnotquery:
returnjson.dumps({
"message": "Please provide a search query"
})
matches=search_history(query)
ifnotmatches:
returnjson.dumps({
"message": f"No matches found for '{query}'"
})
formatted_matches= []
fori, iteminenumerate(matches):
try:
timestamp=datetime.fromisoformat(item["timestamp"])
time_str=timestamp.strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, KeyError):
time_str="Unknown time"
text=item["text"]
iflen(text) >100:
text=text[:97] +"..."
formatted_matches.append({
"index": i,
"text": text,
"time": time_str
})
returnjson.dumps({
"message": {
"text": f"Found {len(formatted_matches)} matches for '{query}'",
"items": formatted_matches
}
})
elifoperation=="restore":
index=int(args.get("index", 0))
history=load_history()
ifnothistory:
returnjson.dumps({
"message": "No clipboard history available"
})
ifindex<0orindex>=len(history):
returnjson.dumps({
"message": f"Invalid index: {index}. Valid range is 0 to {len(history)-1}"
})
item=history[index]
set_clipboard_text(item["text"])
returnjson.dumps({
"message": {
"text": "Restored clipboard item",
"content": item["text"][:100] + ("..."iflen(item["text"]) >100else"")
}
})
elifoperation=="clear":
ifos.path.exists(HISTORY_FILE):
os.remove(HISTORY_FILE)
returnjson.dumps({
"message": "Clipboard history cleared"
})
else:
returnjson.dumps({
"message": f"Unknown operation: {operation}"
})
exceptExceptionase:
returnjson.dumps({
"message": str(e)
})
object= {
"name": "clipboard_manager",
"description": "Manage clipboard history and retrieve previously copied items.",
"parameters": {
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["show", "search", "restore", "clear"],
"description": "Operation to perform with clipboard history"
},
"query": {
"type": "string",
"description": "Search query when using search operation"
},
"index": {
"type": "integer",
"description": "Index of clipboard item to restore"
},
"limit": {
"type": "integer",
"description": "Maximum number of items to show (default: 10)"
}
},
"required": ["operation"]
}
}