File size: 7,895 Bytes
001cde3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
###################################################
#
#  Copyright (C) 2008-2013 Mario Kemper <mario.kemper@gmail.com>
#
#  This file is part of Shutter.
#
#  Shutter is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  Shutter is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with Shutter; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
###################################################

package Shutter::App::Filename;

# Filename helpers extracted from bin/shutter: wildcard expansion,
# auto-incremented "next filename" lookup and filename entry validation.
#
# All application state that these functions used to read from file-scoped
# variables in bin/shutter is passed explicitly as leading arguments:
#   $sc  - Shutter::App::Common (only ->get_debug is used)
#   $d   - Locale::gettext domain (only ->get is used)
#   $sd  - Shutter::App::SimpleDialogs (only ->dlg_error_message is used)
#   $shf - Shutter::App::HelperFunctions (only ->utf8_decode is used)
#
# Glib::IO (Gio via Glib::Object::Introspection) and Gtk3 are expected to be
# set up by the caller (bin/shutter does this in a BEGIN block).

use utf8;
use strict;
use warnings;

use Exporter    qw/ import /;
use Digest::MD5 qw/ md5_hex /;
use Time::HiRes qw/ time /;
use Glib        qw/ TRUE FALSE /;

our @EXPORT_OK = qw/ validate_filename parse_filename_wildcards get_next_filename /;

sub validate_filename {
	my $d               = shift;
	my $myfilename      = shift;
	my $myfilename_hint = shift;
	my @invalid_codes   = (47, 92);
	return $myfilename->signal_connect(
		'key-press-event' => sub {
			shift;
			my $event = shift;

			my $input = Gtk3::Gdk::keyval_to_unicode($event->keyval);

			#invalid input
			#~ print $input."\n";
			if (grep { $input == $_ } @invalid_codes) {
				my $char = chr($input);
				$char = 'amp();' if $char eq '&';
				$myfilename_hint->set_markup("<span size='small'>" . sprintf($d->get("Reserved character %s is not allowed to be in a filename."), "'" . $char . "'") . "</span>");
				return TRUE;
			} else {

				#clear possible message when valid char is entered
				$myfilename_hint->set_markup("<span size='small'></span>");
				return FALSE;
			}
		});
}

sub parse_filename_wildcards {
	my ($sc, $combobox_settings_profiles, $filename_value, $screenshooter, $screenshot, $capture_mode) = @_;

	my $screenshot_name = $filename_value;

	print "Parsing wildcards for $screenshot_name\n"
		if $sc->get_debug;

	#parse width and height
	my $swidth  = $screenshot->get_width;
	my $sheight = $screenshot->get_height;

	$screenshot_name =~ s/\$w/$swidth/g;
	$screenshot_name =~ s/\$h/$sheight/g;

	print "Parsed \$width and \$height: $screenshot_name\n"
		if $sc->get_debug;

	#parse profile name
	my $current_pname = $combobox_settings_profiles->get_active_text;
	$screenshot_name =~ s/\$profile/$current_pname/g;

	print "Parsed \$profile: $screenshot_name\n"
		if $sc->get_debug;

	#set name
	#e.g. window or workspace name
	my $resolved_action_name = undef;

	if (my $action_name = $screenshooter->get_action_name) {
		$resolved_action_name = $action_name;
	}

	# Unified processing for both X11 and Wayland strings
	if ($resolved_action_name) {
		utf8::decode $resolved_action_name;
		$resolved_action_name =~ s/(\/|\#|\>|\<|\%|\*)/-/g;
		$screenshot_name      =~ s/\$name/$resolved_action_name/g;

		#no blanks (special wildcard)
		$resolved_action_name =~ s/\ //g;
		$screenshot_name      =~ s/\$nb_name/$resolved_action_name/g;
	} else {
		$screenshot_name =~ s/(\$name|\$nb_name)/unknown/g;
	}

	print "Parsed \$name: $screenshot_name\n"
		if $sc->get_debug;

	return $screenshot_name;
}

sub get_next_filename {
	my ($sc, $d, $sd, $shf, $filename_value, $folder, $filetype_value) = @_;

	#remove possible dots
	$filetype_value =~ s/\.//;

	$filename_value =~ s/\\//g;

	#random number - should be earlier than %N reading, as $R is actually a part of date
	if ($filename_value =~ /\$R{1,}/) {

		#how many Rs are used? (important for formatting)
		my $pos_proc  = index($filename_value, "\$R", 0);
		my $r_counter = 0;
		my $last_pos  = $pos_proc;
		$pos_proc++;

		while ($pos_proc <= length($filename_value)) {
			$last_pos = index($filename_value, "R", $pos_proc);
			if ($last_pos != -1 && ($last_pos - $pos_proc <= 1)) {
				$r_counter++;
				$pos_proc++;
			} else {
				last;
			}
		}

		#prepare filename
		print "---$r_counter Rs used in wild-card\n" if $sc->get_debug;
		my $marks = "";
		my $i     = 0;

		# Md5 will contain a salt (shutter) and a seconds since 1970
		my $md5_data = "shutter" . time;
		my $md5_hash = md5_hex($md5_data);

		# TODO: set random offset? I guess, current implementation is sufficient
		$marks = substr($md5_hash, 0, $r_counter);

		#switch $Rs to a part of the hash
		$filename_value =~ s/\$R{1,}/$marks/g;
	}

	#auto increment  (%NNN is the pattern for the increment placeholder)
	if ($filename_value =~ /\%(N{1,})/) {

		#how many Ns are used? (important for formatting)
		my $n_counter = length($1);

		#prepare filename
		print "$n_counter Ns used in wild-card\n" if $sc->get_debug;

		my $filename_template = quotemeta $filename_value;

		#replace %NNN by a \d+ regex to search for digits
		#also take into account conflicted filenames Ex.: "_014(002)"
		$filename_template =~ s/\\\%N+/(\\d+)(?:\\(\\d+\\))?/g;

		#store regex to string
		my $search_pattern = qr/$filename_template\.$filetype_value/;

		print "Searching for files with pattern: $search_pattern\n"
			if $sc->get_debug;

		#get_all files from directory
		#we handle the listing with GnomeVFS to read remote dirs as well
		my $dir        = Glib::IO::File::new_for_path($folder);
		my $next_count = 0;
		eval {
			my $enumerator = $dir->enumerate_children('standard::*', []);
			while (my $fileinfo = $enumerator->next_file) {
				my $fname = $shf->utf8_decode($fileinfo->get_name);

				#not a regular file? -> skip
				next unless $fileinfo->get_file_type eq 'regular';

				#does the current file match the pattern?
				# print "Comparing $fname\n" if $sc->get_debug;
				if ($fname =~ $search_pattern) {
					my $curr_value = $1;
					if ($curr_value && $curr_value > $next_count) {
						$next_count = $curr_value;
						print "$next_count is currently greatest value...\n"
							if $sc->get_debug;
					}
				}
			}
			$enumerator->close;
		};
		if ($@) {
			my $response = $sd->dlg_error_message(
				sprintf($d->get("Error while opening directory %s."), "'" . $folder . "'"),
				$d->get("There was an error determining the filename."),
				undef, undef, undef, undef, undef, undef, $@
			);
			return FALSE;
		}

		$next_count = 0 unless $next_count =~ /^(\d+\.?\d*|\.\d+)$/;

		$next_count = sprintf("%0" . $n_counter . "d", $next_count + 1);

		#switch placeholder to $next_count
		$filename_value =~ s/\%N+/$next_count/g;

	}

	#create new uri
	my $new_giofile = Glib::IO::File::new_for_path("$folder/$filename_value.$filetype_value");
	if ($new_giofile->query_exists) {
		my $count             = 1;
		my $existing_filename = $filename_value;
		while ($new_giofile->query_exists) {
			$filename_value = $existing_filename . "(" . sprintf("%03d", $count++) . ")";
			$new_giofile    = Glib::IO::File::new_for_path($folder);
			$new_giofile    = $new_giofile->append_string("$filename_value.$filetype_value");
			print "Checking new uri: " . $new_giofile->to_string . "\n"
				if $sc->get_debug;
		}
	}

	return $new_giofile;
}

1;