-
Notifications
You must be signed in to change notification settings - Fork 0
/
autorenamer.py
311 lines (257 loc) · 12.3 KB
/
autorenamer.py
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/python3
# AutoRenamer - renames files so they sort in a given order
# Copyright 2011-2019 Marcin Owsiany <[email protected]>
# Derived from an example program from the ZetCode.com PyGTK tutorial
# Copyright 2007-2009 Jan Bodnar
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the Authors nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
import logging
import math
import os
import random
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
gi.require_version('GnomeDesktop', '3.0')
from gi.repository import GdkPixbuf
from autorenamer import thumbnails
COL_PATH = 0
COL_PIXBUF = 1
COL_IS_DIRECTORY = 2
APP_NAME = "AutoRenamer"
DEFAULT_WINDOW_WIDTH = 650
class AutoRenamer(Gtk.Window):
def close(self, unused_event, unused_data):
if self.modified_store:
return not self.pop_dialog("Discard changes?", "Do you want to exit and lose your changes?", ok_only=False, accept_save=False)
else:
return False
def __init__(self):
super(AutoRenamer, self).__init__()
self.thumbnailer = thumbnails.Thumbnailer()
self.set_size_request(DEFAULT_WINDOW_WIDTH, 400)
self.set_position(Gtk.WindowPosition.CENTER)
self.connect("delete-event", self.close)
self.connect("destroy", Gtk.main_quit)
self.set_title(APP_NAME)
self.home_directory = os.path.realpath(os.path.expanduser('~'))
self.current_directory = os.path.realpath('.')
self.store_modified_handle = None
self.upButton = Gtk.ToolButton(stock_id=Gtk.STOCK_GO_UP)
self.upButton.set_is_important(True)
self.upButton.connect("clicked", self.on_up_clicked)
self.homeButton = Gtk.ToolButton(stock_id=Gtk.STOCK_HOME)
self.homeButton.set_is_important(True)
self.homeButton.connect("clicked", self.on_home_clicked)
self.saveButton = Gtk.ToolButton(stock_id=Gtk.STOCK_SAVE)
self.saveButton.set_is_important(True)
self.saveButton.connect("clicked", self.on_save_clicked)
self.discardButton = Gtk.ToolButton(stock_id=Gtk.STOCK_CANCEL)
self.discardButton.set_is_important(True)
self.discardButton.connect("clicked", self.on_discard_clicked)
shuffle_image = Gtk.Image.new_from_icon_name("media-playlist-shuffle", Gtk.IconSize.BUTTON)
self.randomizeButton = Gtk.ToolButton()
self.randomizeButton.set_icon_widget(shuffle_image)
self.randomizeButton.set_is_important(True)
self.randomizeButton.set_label("Shuffle")
self.randomizeButton.connect("clicked", self.on_randomize_clicked)
self.dirsButton = Gtk.ToolButton(stock_id=Gtk.STOCK_DIRECTORY)
self.dirsButton.set_is_important(True)
self.dirsButton.set_label("Toggle directories")
self.dirsButton.connect("clicked", self.on_dirs_clicked)
toolbar = Gtk.Toolbar()
toolbar.insert(self.upButton, -1)
toolbar.insert(self.homeButton, -1)
toolbar.insert(self.saveButton, -1)
toolbar.insert(self.discardButton, -1)
toolbar.insert(self.randomizeButton, -1)
toolbar.insert(self.dirsButton, -1)
sw = Gtk.ScrolledWindow()
sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
vbox = Gtk.VBox()
vbox.pack_start(toolbar, False, False, 0)
vbox.pack_start(sw, True, True, 0)
self.store = Gtk.ListStore(str, GdkPixbuf.Pixbuf, bool)
self.fill_store()
self.iconView = Gtk.IconView(model=self.store)
self.iconView.set_reorderable(True)
self.iconView.set_selection_mode(Gtk.SelectionMode.MULTIPLE)
self.iconView.set_text_column(COL_PATH)
self.iconView.set_pixbuf_column(COL_PIXBUF)
self.iconView.connect("item-activated", self.on_item_activated)
sw.add(self.iconView)
self.iconView.grab_focus()
self.add(vbox)
self.show_all()
def fill_store(self):
if self.store_modified_handle:
self.store.disconnect(self.store_modified_handle)
self.store.clear()
self.modified_store = False
if self.current_directory == None:
return
if self.current_directory == "/":
self.upButton.set_sensitive(False)
else:
self.upButton.set_sensitive(True)
if self.current_directory == self.home_directory:
self.homeButton.set_sensitive(False)
else:
self.homeButton.set_sensitive(True)
self.saveButton.set_sensitive(False)
self.discardButton.set_sensitive(False)
self.initial_order = [f for f in sorted(os.listdir(self.current_directory)) if f[0] != "."]
self.randomizeButton.set_sensitive(bool(self.initial_order))
self.set_title(APP_NAME + ": " + self.current_directory)
directories_present = False
for fl in self.initial_order:
full_path = os.path.join(self.current_directory, fl)
is_dir = os.path.isdir(full_path)
if is_dir:
directories_present = True
self.store.append([fl, self.thumbnailer.pixbuf_for(full_path, is_dir), is_dir])
self.store_modified_handle = self.store.connect("row-deleted", self.on_row_deleted)
self.dirsButton.set_sensitive(directories_present)
def on_row_deleted(self, treemodel, path):
self.on_order_changed()
def on_order_changed(self):
if self.initial_order == [e[0] for e in self.store]:
self.modified_store = False
self.upButton.set_sensitive(True)
self.homeButton.set_sensitive(True)
self.saveButton.set_sensitive(False)
self.discardButton.set_sensitive(False)
else:
self.modified_store = True
self.upButton.set_sensitive(False)
self.homeButton.set_sensitive(False)
self.saveButton.set_sensitive(True)
self.discardButton.set_sensitive(True)
def on_home_clicked(self, widget):
self.current_directory = self.home_directory
self.fill_store()
def on_discard_clicked(self, widget):
self.fill_store()
def on_dirs_clicked(self, widget):
directory_indices = [index for index, item in enumerate(self.store) if item[COL_IS_DIRECTORY]]
for index in directory_indices:
path = Gtk.TreePath(index)
if self.iconView.path_is_selected(path):
self.iconView.unselect_path(path)
else:
self.iconView.select_path(path)
def selected_elements_in_order(self):
selected_indices = [path[0] for path in self.iconView.get_selected_items()]
selected_indices.sort()
return [self.store[index] for index in selected_indices]
def on_save_clicked(self, widget):
new_order_elements = self.selected_elements_in_order() or self.store
rename_selected_only = new_order_elements is not self.store
ordered_names_to_rename = [e[COL_PATH] for e in new_order_elements]
num_items = len(ordered_names_to_rename)
width = math.ceil(math.log10(num_items))
fmt = "%%0%dd-%%s" % width
prefixed = [(fmt % (i, f)) for i, f in enumerate(ordered_names_to_rename)]
all_names = [e[COL_PATH] for e in self.store]
conflicts = set.intersection(set(all_names), set(prefixed))
if conflicts:
self.pop_dialog("Cannot rename", "The following filenames conflict.",
column_names=("Filename",),
column_values=[(c,) for c in conflicts])
return
renames = list(zip(ordered_names_to_rename, prefixed))
if self.pop_dialog("Renames", "The following renames will be performed." +
(rename_selected_only and "\nNote: only the selected entries are renamed." or ""),
ok_only=False,
column_names=("From", "To"),
column_values=renames):
for source, dest in renames:
source = os.path.join(self.current_directory, source)
dest = os.path.join(self.current_directory, dest)
os.rename(source, dest)
self.fill_store()
def pop_dialog(self, title, label_text, ok_only=True, accept_save=True, column_names=None, column_values=None):
label = Gtk.Label(label=label_text)
dialog = Gtk.Dialog(title=title, parent=self, modal=True, destroy_with_parent=True)
if ok_only:
dialog.add_button(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT)
elif accept_save:
dialog.add_buttons(
Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT,
Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT)
else:
dialog.add_buttons(
Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT,
Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT)
dialog.vbox.props.homogeneous = False # Let children differ in size.
dialog.vbox.pack_start(label, False, False, 0)
if column_names is not None and column_values is not None:
types = [str for c in column_names]
store = Gtk.ListStore(*types)
for value in column_values:
store.append(value)
list_view = Gtk.TreeView(model=store)
list_view.set_reorderable(False)
for offset, name in enumerate(column_names):
list_view.append_column(Gtk.TreeViewColumn(name, Gtk.CellRendererText(), text=offset))
sw = Gtk.ScrolledWindow()
sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
sw.add(list_view)
dialog.vbox.pack_start(sw, True, True, 0)
dialog.show_all()
try:
return dialog.run() == Gtk.ResponseType.ACCEPT
finally:
dialog.destroy()
def on_item_activated(self, widget, item):
model = widget.get_model()
path = model[item][COL_PATH]
isDir = model[item][COL_IS_DIRECTORY]
if not isDir:
return
if self.modified_store:
self.pop_dialog("Save or discard", "Save or discard first!")
return
self.current_directory = self.current_directory + os.path.sep + path
self.fill_store()
def on_up_clicked(self, widget):
self.current_directory = os.path.dirname(self.current_directory)
self.fill_store()
def on_randomize_clicked(self, widget):
order = list(range(len(self.initial_order)))
random.shuffle(order)
self.store.reorder(order)
self.on_order_changed()
def main():
import argparse
parser = argparse.ArgumentParser(description='Interactively rename files to reorder them.')
parser.add_argument('--debug', action='store_true', help='Turn on debug-level logging.')
args = parser.parse_args()
logging.basicConfig(level=(logging.DEBUG if args.debug else logging.INFO))
AutoRenamer()
Gtk.main()
if __name__ == '__main__':
main()