1 /*
2  * rofi
3  *
4  * MIT/X11 License
5  * Copyright © 2013-2020 Qball Cow <qball@gmpclient.org>
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining
8  * a copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sublicense, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be
16  * included in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  */
27 
28 /**
29  * \ingroup RUNMode
30  * @{
31  */
32 
33 /** The log domain of this dialog. */
34 #define G_LOG_DOMAIN    "Dialogs.Run"
35 
36 #include <config.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 
40 #include <unistd.h>
41 #include <limits.h>
42 #include <signal.h>
43 #include <sys/types.h>
44 #include <dirent.h>
45 #include <strings.h>
46 #include <string.h>
47 #include <errno.h>
48 
49 #include "rofi.h"
50 #include "settings.h"
51 #include "helper.h"
52 #include "history.h"
53 #include "dialogs/run.h"
54 
55 #include "mode-private.h"
56 
57 #include "timings.h"
58 #include "rofi-icon-fetcher.h"
59 /**
60  * Name of the history file where previously chosen commands are stored.
61  */
62 #define RUN_CACHE_FILE    "rofi-3.runcache"
63 
64 /**
65  * The internal data structure holding the private data of the Run Mode.
66  */
67 typedef struct
68 {
69     /** list of available commands. */
70     char         **cmd_list;
71     /** Length of the #cmd_list. */
72     unsigned int cmd_list_length;
73 } RunModePrivateData;
74 
75 /**
76  * @param cmd The cmd to execute
77  * @param run_in_term Indicate if command should be run in a terminal
78  *
79  * Execute command and add to history.
80  */
exec_cmd(const char * cmd,int run_in_term)81 static gboolean exec_cmd ( const char *cmd, int run_in_term )
82 {
83     GError *error = NULL;
84     if ( !cmd || !cmd[0] ) {
85         return FALSE;
86     }
87     gsize lf_cmd_size = 0;
88     gchar *lf_cmd     = g_locale_from_utf8 ( cmd, -1, NULL, &lf_cmd_size, &error );
89     if ( error != NULL ) {
90         g_warning ( "Failed to convert command to locale encoding: %s", error->message );
91         g_error_free ( error );
92         return FALSE;
93     }
94 
95     char                     *path   = g_build_filename ( cache_dir, RUN_CACHE_FILE, NULL );
96     RofiHelperExecuteContext context = { .name = NULL };
97     // FIXME: assume startup notification support for terminals
98     if (  helper_execute_command ( NULL, lf_cmd, run_in_term, run_in_term ? &context : NULL ) ) {
99         /**
100          * This happens in non-critical time (After launching app)
101          * It is allowed to be a bit slower.
102          */
103 
104         history_set ( path, cmd );
105         g_free ( path );
106         g_free ( lf_cmd );
107         return TRUE;
108     }
109     else {
110         history_remove ( path, cmd );
111         g_free ( path );
112         g_free ( lf_cmd );
113         return FALSE;
114     }
115 }
116 
117 /**
118  * @param cmd The command to remove from history
119  *
120  * Remove command from history.
121  */
delete_entry(const char * cmd)122 static void delete_entry ( const char *cmd )
123 {
124     char *path = g_build_filename ( cache_dir, RUN_CACHE_FILE, NULL );
125 
126     history_remove ( path, cmd );
127 
128     g_free ( path );
129 }
130 
131 /**
132  * @param a The First key to compare
133  * @param b The second key to compare
134  * @param data Unused.
135  *
136  * Function used for sorting.
137  *
138  * @returns returns less then, equal to and greater than zero is a is less than, is a match or greater than b.
139  */
sort_func(const void * a,const void * b,G_GNUC_UNUSED void * data)140 static int sort_func ( const void *a, const void *b, G_GNUC_UNUSED void *data )
141 {
142     const char *astr = *( const char * const * ) a;
143     const char *bstr = *( const char * const * ) b;
144 
145     if ( astr == NULL && bstr == NULL ) {
146         return 0;
147     }
148     else if ( astr == NULL ) {
149         return 1;
150     }
151     else if ( bstr == NULL ) {
152         return -1;
153     }
154     return g_strcmp0 ( astr, bstr );
155 }
156 
157 /**
158  * External spider to get list of executables.
159  */
get_apps_external(char ** retv,unsigned int * length,unsigned int num_favorites)160 static char ** get_apps_external ( char **retv, unsigned int *length, unsigned int num_favorites )
161 {
162     int fd = execute_generator ( config.run_list_command );
163     if ( fd >= 0 ) {
164         FILE *inp = fdopen ( fd, "r" );
165         if ( inp ) {
166             char   *buffer       = NULL;
167             size_t buffer_length = 0;
168 
169             while ( getline ( &buffer, &buffer_length, inp ) > 0 ) {
170                 int found = 0;
171                 // Filter out line-end.
172                 if ( buffer[strlen ( buffer ) - 1] == '\n' ) {
173                     buffer[strlen ( buffer ) - 1] = '\0';
174                 }
175 
176                 // This is a nice little penalty, but doable? time will tell.
177                 // given num_favorites is max 25.
178                 for ( unsigned int j = 0; found == 0 && j < num_favorites; j++ ) {
179                     if ( strcasecmp ( buffer, retv[j] ) == 0 ) {
180                         found = 1;
181                     }
182                 }
183 
184                 if ( found == 1 ) {
185                     continue;
186                 }
187 
188                 // No duplicate, add it.
189                 retv              = g_realloc ( retv, ( ( *length ) + 2 ) * sizeof ( char* ) );
190                 retv[( *length )] = g_strdup ( buffer );
191 
192                 ( *length )++;
193             }
194             if ( buffer != NULL ) {
195                 free ( buffer );
196             }
197             if ( fclose ( inp ) != 0 ) {
198                 g_warning ( "Failed to close stdout off executor script: '%s'",
199                             g_strerror ( errno ) );
200             }
201         }
202     }
203     retv[( *length ) ] = NULL;
204     return retv;
205 }
206 
207 /**
208  * Internal spider used to get list of executables.
209  */
get_apps(unsigned int * length)210 static char ** get_apps ( unsigned int *length )
211 {
212     GError       *error        = NULL;
213     char         **retv        = NULL;
214     unsigned int num_favorites = 0;
215     char         *path;
216 
217     if ( g_getenv ( "PATH" ) == NULL ) {
218         return NULL;
219     }
220     TICK_N ( "start" );
221     path = g_build_filename ( cache_dir, RUN_CACHE_FILE, NULL );
222     retv = history_get_list ( path, length );
223     g_free ( path );
224     // Keep track of how many where loaded as favorite.
225     num_favorites = ( *length );
226 
227     path = g_strdup ( g_getenv ( "PATH" ) );
228 
229     gsize l        = 0;
230     gchar *homedir = g_locale_to_utf8 (  g_get_home_dir (), -1, NULL, &l, &error );
231     if ( error != NULL ) {
232         g_debug ( "Failed to convert homedir to UTF-8: %s", error->message );
233         g_clear_error ( &error );
234         g_free ( homedir );
235         return NULL;
236     }
237 
238     const char *const sep                 = ":";
239     char              *strtok_savepointer = NULL;
240     for ( const char *dirname = strtok_r ( path, sep, &strtok_savepointer ); dirname != NULL; dirname = strtok_r ( NULL, sep, &strtok_savepointer ) ) {
241         char *fpath = rofi_expand_path ( dirname );
242         DIR  *dir   = opendir ( fpath );
243         g_debug ( "Checking path %s for executable.", fpath );
244         g_free ( fpath );
245 
246         if ( dir != NULL ) {
247             struct dirent *dent;
248             gsize         dirn_len = 0;
249             gchar         *dirn    = g_locale_to_utf8 ( dirname, -1, NULL, &dirn_len, &error );
250             if ( error != NULL ) {
251                 g_debug ( "Failed to convert directory name to UTF-8: %s", error->message );
252                 g_clear_error ( &error );
253                 closedir ( dir );
254                 continue;
255             }
256             gboolean is_homedir = g_str_has_prefix ( dirn, homedir );
257             g_free ( dirn );
258 
259             while ( ( dent = readdir ( dir ) ) != NULL ) {
260                 if ( dent->d_type != DT_REG && dent->d_type != DT_LNK && dent->d_type != DT_UNKNOWN ) {
261                     continue;
262                 }
263                 // Skip dot files.
264                 if ( dent->d_name[0] == '.' ) {
265                     continue;
266                 }
267                 if ( is_homedir ) {
268                     gchar    *fpath = g_build_filename ( dirname, dent->d_name, NULL );
269                     gboolean b      = g_file_test ( fpath, G_FILE_TEST_IS_EXECUTABLE );
270                     g_free ( fpath );
271                     if ( !b ) {
272                         continue;
273                     }
274                 }
275 
276                 gsize name_len;
277                 gchar *name = g_filename_to_utf8 ( dent->d_name, -1, NULL, &name_len, &error );
278                 if ( error != NULL ) {
279                     g_debug ( "Failed to convert filename to UTF-8: %s", error->message );
280                     g_clear_error ( &error );
281                     g_free ( name );
282                     continue;
283                 }
284                 // This is a nice little penalty, but doable? time will tell.
285                 // given num_favorites is max 25.
286                 int found = 0;
287                 for ( unsigned int j = 0; found == 0 && j < num_favorites; j++ ) {
288                     if ( g_strcmp0 ( name, retv[j] ) == 0 ) {
289                         found = 1;
290                     }
291                 }
292 
293                 if ( found == 1 ) {
294                     g_free ( name );
295                     continue;
296                 }
297 
298                 retv                  = g_realloc ( retv, ( ( *length ) + 2 ) * sizeof ( char* ) );
299                 retv[( *length )]     = name;
300                 retv[( *length ) + 1] = NULL;
301                 ( *length )++;
302             }
303 
304             closedir ( dir );
305         }
306     }
307     g_free ( homedir );
308 
309     // Get external apps.
310     if ( config.run_list_command != NULL && config.run_list_command[0] != '\0' ) {
311         retv = get_apps_external ( retv, length, num_favorites );
312     }
313     // No sorting needed.
314     if ( ( *length ) == 0 ) {
315         return retv;
316     }
317     // TODO: check this is still fast enough. (takes 1ms on laptop.)
318     if ( ( *length ) > num_favorites ) {
319         g_qsort_with_data ( &retv[num_favorites], ( *length ) - num_favorites, sizeof ( char* ), sort_func, NULL );
320     }
321     g_free ( path );
322 
323     unsigned int removed = 0;
324     for ( unsigned int index = num_favorites; index < ( ( *length ) - 1 ); index++ ) {
325         if ( g_strcmp0 ( retv[index], retv[index + 1] ) == 0 ) {
326             g_free ( retv[index] );
327             retv[index] = NULL;
328             removed++;
329         }
330     }
331 
332     if ( ( *length ) > num_favorites ) {
333         g_qsort_with_data ( &retv[num_favorites], ( *length ) - num_favorites, sizeof ( char* ),
334                             sort_func,
335                             NULL );
336     }
337     // Reduce array length;
338     ( *length ) -= removed;
339 
340     TICK_N ( "stop" );
341     return retv;
342 }
343 
run_mode_init(Mode * sw)344 static int run_mode_init ( Mode *sw )
345 {
346     if ( sw->private_data == NULL ) {
347         RunModePrivateData *pd = g_malloc0 ( sizeof ( *pd ) );
348         sw->private_data = (void *) pd;
349         pd->cmd_list     = get_apps ( &( pd->cmd_list_length ) );
350     }
351 
352     return TRUE;
353 }
run_mode_destroy(Mode * sw)354 static void run_mode_destroy ( Mode *sw )
355 {
356     RunModePrivateData *rmpd = (RunModePrivateData *) sw->private_data;
357     if ( rmpd != NULL ) {
358         g_strfreev ( rmpd->cmd_list );
359         g_free ( rmpd );
360         sw->private_data = NULL;
361     }
362 }
363 
run_mode_get_num_entries(const Mode * sw)364 static unsigned int run_mode_get_num_entries ( const Mode *sw )
365 {
366     const RunModePrivateData *rmpd = (const RunModePrivateData *) sw->private_data;
367     return rmpd->cmd_list_length;
368 }
369 
run_mode_result(Mode * sw,int mretv,char ** input,unsigned int selected_line)370 static ModeMode run_mode_result ( Mode *sw, int mretv, char **input, unsigned int selected_line )
371 {
372     RunModePrivateData *rmpd = (RunModePrivateData *) sw->private_data;
373     ModeMode           retv  = MODE_EXIT;
374 
375     gboolean           run_in_term = ( ( mretv & MENU_CUSTOM_ACTION ) == MENU_CUSTOM_ACTION );
376 
377     if ( ( mretv & MENU_OK ) && rmpd->cmd_list[selected_line] != NULL ) {
378         if ( !exec_cmd ( rmpd->cmd_list[selected_line], run_in_term ) ) {
379             retv = RELOAD_DIALOG;
380         }
381     }
382     else if ( ( mretv & MENU_CUSTOM_INPUT ) && *input != NULL && *input[0] != '\0' ) {
383         if ( !exec_cmd ( *input, run_in_term ) ) {
384             retv = RELOAD_DIALOG;
385         }
386     }
387     else if ( ( mretv & MENU_ENTRY_DELETE ) && rmpd->cmd_list[selected_line] ) {
388         delete_entry ( rmpd->cmd_list[selected_line] );
389 
390         // Clear the list.
391         retv = RELOAD_DIALOG;
392         run_mode_destroy ( sw );
393         run_mode_init ( sw );
394     }
395     return retv;
396 }
397 
_get_display_value(const Mode * sw,unsigned int selected_line,G_GNUC_UNUSED int * state,G_GNUC_UNUSED GList ** list,int get_entry)398 static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_GNUC_UNUSED int *state, G_GNUC_UNUSED GList **list, int get_entry )
399 {
400     const RunModePrivateData *rmpd = (const RunModePrivateData *) sw->private_data;
401     return get_entry ? g_strdup ( rmpd->cmd_list[selected_line] ) : NULL;
402 }
403 
run_token_match(const Mode * sw,rofi_int_matcher ** tokens,unsigned int index)404 static int run_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index )
405 {
406     const RunModePrivateData *rmpd = (const RunModePrivateData *) sw->private_data;
407     return helper_token_match ( tokens, rmpd->cmd_list[index] );
408 }
409 
410 #include "mode-private.h"
411 Mode run_mode =
412 {
413     .name               = "run",
414     .cfg_name_key       = "display-run",
415     ._init              = run_mode_init,
416     ._get_num_entries   = run_mode_get_num_entries,
417     ._result            = run_mode_result,
418     ._destroy           = run_mode_destroy,
419     ._token_match       = run_token_match,
420     ._get_display_value = _get_display_value,
421     ._get_icon          = NULL,
422     ._get_completion    = NULL,
423     ._preprocess_input  = NULL,
424     .private_data       = NULL,
425     .free               = NULL
426 };
427 /** @}*/
428